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/plugins/org.eclipse.vjet.eclipse.core/codeassist/org/eclipse/vjet/eclipse/internal/codeassist/select/translator/JstFunctionRefTypeTranslator.java b/plugins/org.eclipse.vjet.eclipse.core/codeassist/org/eclipse/vjet/eclipse/internal/codeassist/select/translator/JstFunctionRefTypeTranslator.java
index 715e3740..d9a5b6f3 100644
--- a/plugins/org.eclipse.vjet.eclipse.core/codeassist/org/eclipse/vjet/eclipse/internal/codeassist/select/translator/JstFunctionRefTypeTranslator.java
+++ b/plugins/org.eclipse.vjet.eclipse.core/codeassist/org/eclipse/vjet/eclipse/internal/codeassist/select/translator/JstFunctionRefTypeTranslator.java
@@ -1,125 +1,130 @@
/*******************************************************************************
* Copyright (c) 2005, 2012 eBay Inc.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
*******************************************************************************/
/**
*
*/
package org.eclipse.vjet.eclipse.internal.codeassist.select.translator;
import org.eclipse.vjet.dsf.jst.IJstMethod;
import org.eclipse.vjet.dsf.jst.IJstNode;
import org.eclipse.vjet.dsf.jst.IJstType;
import org.eclipse.vjet.dsf.jst.declaration.JstFunctionRefType;
import org.eclipse.vjet.eclipse.codeassist.CodeassistUtils;
import org.eclipse.vjet.eclipse.core.IVjoSourceModule;
import org.eclipse.vjet.eclipse.core.VjetPlugin;
import org.eclipse.dltk.mod.core.IModelElement;
import org.eclipse.dltk.mod.core.IScriptProject;
import org.eclipse.dltk.mod.core.IType;
import org.eclipse.dltk.mod.core.ModelException;
import org.eclipse.dltk.mod.internal.core.ScriptProject;
/**
*
*
*/
public class JstFunctionRefTypeTranslator extends DefaultNodeTranslator {
public IModelElement[] convert(IJstNode jstNode) {
if(!(jstNode instanceof JstFunctionRefType)){
return null;
}
IJstType jstType = (IJstType)jstNode.getParentNode();
if (CodeassistUtils.isNativeType(jstType)) {
IType type = CodeassistUtils.findNativeSourceType(jstType);
return type != null ? new IModelElement[] { type }
: new IModelElement[0];
} else {
IType rootDLTKType = CodeassistUtils
.findType(jstType.getRootType());
if (rootDLTKType == null)
return null;
IModelElement converted = this.getType(rootDLTKType, jstType.getName());
final JstFunctionRefType jstFunctionRefType = (JstFunctionRefType)jstNode;
final IJstMethod methodRef = jstFunctionRefType.getMethodRef();
if(converted instanceof IType
&& methodRef != null
&& methodRef.getName() != null
&& methodRef.getName().getName() != null){
IModelElement method = ((IType)converted).getMethod(methodRef.getName().getName());
converted = method != null ? method : converted;
}
return converted != null ? new IModelElement[] { converted }
: new IModelElement[0];
}
}
@Override
public IModelElement[] convert(IVjoSourceModule module, IJstNode jstNode) {
if(!(jstNode instanceof JstFunctionRefType)){
return null;
}
IJstType jstType = (IJstType)jstNode.getParentNode();
IScriptProject sProject = null;
if (module != null) {
sProject = module.getScriptProject();
}
IModelElement mElement = null;
if (sProject != null && (!CodeassistUtils.isNativeType(jstType) // type
// in
// workspace
|| CodeassistUtils // type in external source type
.isBinaryType(jstType))) {
mElement = CodeassistUtils.findType((ScriptProject) sProject,
jstType);
}
if (mElement == null) {
- mElement = convert(jstNode)[0];
+ IModelElement[] convert = convert(jstNode);
+ if(convert.length>0){
+ mElement = convert[0];
+ }else{
+ System.err.println("could not find converter for " + jstNode.getClass());
+ }
}
final JstFunctionRefType jstFunctionRefType = (JstFunctionRefType)jstNode;
final IJstMethod methodRef = jstFunctionRefType.getMethodRef();
if(mElement instanceof IType
&& methodRef != null
&& methodRef.getName() != null
&& methodRef.getName().getName() != null){
IModelElement method = ((IType)mElement).getMethod(methodRef.getName().getName());
mElement = method != null ? method : mElement;
}
return mElement != null ? new IModelElement[] { mElement }
: new IModelElement[0];
}
/**
* get corresponding type, including inner type
*
* @param rootType
* @param dltkTypeName
* @return
*/
private IType getType(IType rootType, String dltkTypeName) {
try {
if (rootType.getFullyQualifiedName(".").equals(dltkTypeName))
return rootType;
else {
IType[] types = rootType.getTypes();
for (int i = 0; i < types.length; i++) {
IType type = this.getType(types[i], dltkTypeName);
if (type != null)
return type;
}
}
} catch (ModelException e) {
VjetPlugin.error(e.getLocalizedMessage(), e);
}
return null;
}
}
| true | true | public IModelElement[] convert(IVjoSourceModule module, IJstNode jstNode) {
if(!(jstNode instanceof JstFunctionRefType)){
return null;
}
IJstType jstType = (IJstType)jstNode.getParentNode();
IScriptProject sProject = null;
if (module != null) {
sProject = module.getScriptProject();
}
IModelElement mElement = null;
if (sProject != null && (!CodeassistUtils.isNativeType(jstType) // type
// in
// workspace
|| CodeassistUtils // type in external source type
.isBinaryType(jstType))) {
mElement = CodeassistUtils.findType((ScriptProject) sProject,
jstType);
}
if (mElement == null) {
mElement = convert(jstNode)[0];
}
final JstFunctionRefType jstFunctionRefType = (JstFunctionRefType)jstNode;
final IJstMethod methodRef = jstFunctionRefType.getMethodRef();
if(mElement instanceof IType
&& methodRef != null
&& methodRef.getName() != null
&& methodRef.getName().getName() != null){
IModelElement method = ((IType)mElement).getMethod(methodRef.getName().getName());
mElement = method != null ? method : mElement;
}
return mElement != null ? new IModelElement[] { mElement }
: new IModelElement[0];
}
| public IModelElement[] convert(IVjoSourceModule module, IJstNode jstNode) {
if(!(jstNode instanceof JstFunctionRefType)){
return null;
}
IJstType jstType = (IJstType)jstNode.getParentNode();
IScriptProject sProject = null;
if (module != null) {
sProject = module.getScriptProject();
}
IModelElement mElement = null;
if (sProject != null && (!CodeassistUtils.isNativeType(jstType) // type
// in
// workspace
|| CodeassistUtils // type in external source type
.isBinaryType(jstType))) {
mElement = CodeassistUtils.findType((ScriptProject) sProject,
jstType);
}
if (mElement == null) {
IModelElement[] convert = convert(jstNode);
if(convert.length>0){
mElement = convert[0];
}else{
System.err.println("could not find converter for " + jstNode.getClass());
}
}
final JstFunctionRefType jstFunctionRefType = (JstFunctionRefType)jstNode;
final IJstMethod methodRef = jstFunctionRefType.getMethodRef();
if(mElement instanceof IType
&& methodRef != null
&& methodRef.getName() != null
&& methodRef.getName().getName() != null){
IModelElement method = ((IType)mElement).getMethod(methodRef.getName().getName());
mElement = method != null ? method : mElement;
}
return mElement != null ? new IModelElement[] { mElement }
: new IModelElement[0];
}
|
diff --git a/src/main/java/de/fiz/akubra/hdfs/HDFSIdIterator.java b/src/main/java/de/fiz/akubra/hdfs/HDFSIdIterator.java
index f53e6d5..cf82dee 100644
--- a/src/main/java/de/fiz/akubra/hdfs/HDFSIdIterator.java
+++ b/src/main/java/de/fiz/akubra/hdfs/HDFSIdIterator.java
@@ -1,104 +1,104 @@
/*
Copyright 2011 FIZ Karlsruhe
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/
package de.fiz.akubra.hdfs;
import java.io.IOException;
import java.net.URI;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.Queue;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.FileSystem;
import org.apache.hadoop.fs.Path;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* An very simple {@link Iterator} implementation for the
* {@link HDFSBlobStoreConnection}
*
* @author frank asseg
*
*/
public class HDFSIdIterator implements Iterator<URI> {
private static final Logger log = LoggerFactory.getLogger(HDFSIdIterator.class);
private final FileSystem hdfs;
private final String prefix;
private final Queue<Path> dirQueue = new LinkedList<Path>();
private final Queue<Path> fileQueue = new LinkedList<Path>();
public HDFSIdIterator(final FileSystem hdfs, final String prefix) {
this.hdfs = hdfs;
if (prefix == null) {
this.prefix = "";
} else {
this.prefix = prefix;
}
dirQueue.add(new Path("/"));
}
@Override
public boolean hasNext() {
while (fileQueue.isEmpty()) {
if (!updateQueues()) {
return false;
}
}
return !fileQueue.isEmpty();
}
@Override
public URI next() {
while (fileQueue.isEmpty()) {
if (!updateQueues()) {
return null;
}
}
return fileQueue.poll().toUri();
}
@Override
public void remove() throws UnsupportedOperationException {
throw new UnsupportedOperationException("remove is not implemented");
}
private boolean updateQueues() {
if (fileQueue.isEmpty()) {
if (dirQueue.isEmpty()) {
return false; // all queues are empty
}
Path dir = dirQueue.poll();
try {
for (FileStatus stat : hdfs.listStatus(dir)) {
- if (stat.isDirectory()) {
+ if (stat.isDir()) {
dirQueue.add(stat.getPath());
} else if (stat.getPath().getName().startsWith(prefix)) {
fileQueue.add(stat.getPath());
}
}
} catch (IOException e) {
log.error("Exception while updateing iterator queues", e);
throw new RuntimeException(e);
}
}
return true;
}
}
| true | true | private boolean updateQueues() {
if (fileQueue.isEmpty()) {
if (dirQueue.isEmpty()) {
return false; // all queues are empty
}
Path dir = dirQueue.poll();
try {
for (FileStatus stat : hdfs.listStatus(dir)) {
if (stat.isDirectory()) {
dirQueue.add(stat.getPath());
} else if (stat.getPath().getName().startsWith(prefix)) {
fileQueue.add(stat.getPath());
}
}
} catch (IOException e) {
log.error("Exception while updateing iterator queues", e);
throw new RuntimeException(e);
}
}
return true;
}
| private boolean updateQueues() {
if (fileQueue.isEmpty()) {
if (dirQueue.isEmpty()) {
return false; // all queues are empty
}
Path dir = dirQueue.poll();
try {
for (FileStatus stat : hdfs.listStatus(dir)) {
if (stat.isDir()) {
dirQueue.add(stat.getPath());
} else if (stat.getPath().getName().startsWith(prefix)) {
fileQueue.add(stat.getPath());
}
}
} catch (IOException e) {
log.error("Exception while updateing iterator queues", e);
throw new RuntimeException(e);
}
}
return true;
}
|
diff --git a/Plugins/ExternalServices/Edemande/src/java/fr/capwebct/capdemat/plugins/externalservices/edemande/service/EdemandeService.java b/Plugins/ExternalServices/Edemande/src/java/fr/capwebct/capdemat/plugins/externalservices/edemande/service/EdemandeService.java
index e69450136..88b265601 100644
--- a/Plugins/ExternalServices/Edemande/src/java/fr/capwebct/capdemat/plugins/externalservices/edemande/service/EdemandeService.java
+++ b/Plugins/ExternalServices/Edemande/src/java/fr/capwebct/capdemat/plugins/externalservices/edemande/service/EdemandeService.java
@@ -1,782 +1,778 @@
package fr.capwebct.capdemat.plugins.externalservices.edemande.service;
import java.io.IOException;
import java.io.StringReader;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TreeMap;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.apache.commons.lang.StringUtils;
import org.apache.xmlbeans.XmlObject;
import org.jaxen.JaxenException;
import org.jaxen.dom.DOMXPath;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanFactory;
import org.springframework.beans.factory.BeanFactoryAware;
import org.springframework.beans.factory.ListableBeanFactory;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import com.jcraft.jsch.JSchException;
import com.jcraft.jsch.SftpException;
import com.unilog.gda.edem.service.EnregistrerValiderFormulaireResponseDocument;
import com.unilog.gda.glob.service.GestionCompteResponseDocument;
import fr.capwebct.capdemat.plugins.externalservices.edemande.webservice.client.IEdemandeClient;
import fr.cg95.cvq.business.document.Document;
import fr.cg95.cvq.business.document.DocumentBinary;
import fr.cg95.cvq.business.external.ExternalServiceTrace;
import fr.cg95.cvq.business.external.TraceStatusEnum;
import fr.cg95.cvq.business.request.Request;
import fr.cg95.cvq.business.request.RequestDocument;
import fr.cg95.cvq.business.request.RequestState;
import fr.cg95.cvq.business.users.Individual;
import fr.cg95.cvq.business.users.SexType;
import fr.cg95.cvq.business.users.payment.ExternalAccountItem;
import fr.cg95.cvq.business.users.payment.ExternalDepositAccountItem;
import fr.cg95.cvq.business.users.payment.ExternalInvoiceItem;
import fr.cg95.cvq.business.users.payment.PurchaseItem;
import fr.cg95.cvq.exception.CvqConfigurationException;
import fr.cg95.cvq.exception.CvqException;
import fr.cg95.cvq.exception.CvqInvalidTransitionException;
import fr.cg95.cvq.exception.CvqObjectNotFoundException;
import fr.cg95.cvq.external.ExternalServiceBean;
import fr.cg95.cvq.external.IExternalProviderService;
import fr.cg95.cvq.external.IExternalService;
import fr.cg95.cvq.permission.CvqPermissionException;
import fr.cg95.cvq.service.document.IDocumentService;
import fr.cg95.cvq.service.document.IDocumentTypeService;
import fr.cg95.cvq.service.request.IRequestWorkflowService;
import fr.cg95.cvq.service.request.school.IStudyGrantRequestService;
import fr.cg95.cvq.service.users.IHomeFolderService;
import fr.cg95.cvq.util.translation.ITranslationService;
import fr.cg95.cvq.xml.request.school.StudyGrantRequestDocument;
import fr.cg95.cvq.xml.request.school.StudyGrantRequestDocument.StudyGrantRequest;
public class EdemandeService implements IExternalProviderService, BeanFactoryAware {
private String label;
private IEdemandeClient edemandeClient;
private IExternalService externalService;
private IStudyGrantRequestService requestService;
private IDocumentService documentService;
private IRequestWorkflowService requestWorkflowService;
private ITranslationService translationService;
private IHomeFolderService homeFolderService;
private EdemandeUploader uploader;
private ListableBeanFactory beanFactory;
private static final String ADDRESS_FIELDS[] = {
"miCode", "moNature/miCode", "msVoie", "miBoitePostale", "msCodePostal", "msVille",
"miCedex", "msPays", "msTel", "msFax", "msMail", "mbUsuel"
};
private static final String SUBJECT_TRACE_SUBKEY = "subject";
private static final String ACCOUNT_HOLDER_TRACE_SUBKEY = "accountHolder";
private DateFormat formatter = new SimpleDateFormat("dd/MM/yyyy");
public void init() {
this.homeFolderService = (IHomeFolderService)beanFactory.getBean("homeFolderService");
}
@Override
public String sendRequest(XmlObject requestXml) {
StudyGrantRequest sgr = ((StudyGrantRequestDocument) requestXml).getStudyGrantRequest();
String psCodeTiersAH = null;
if (!sgr.getIsSubjectAccountHolder()) {
psCodeTiersAH = sgr.getAccountHolderEdemandeId();
if (psCodeTiersAH == null || psCodeTiersAH.trim().isEmpty()) {
psCodeTiersAH = searchAccountHolder(sgr);
if (psCodeTiersAH == null || psCodeTiersAH.trim().isEmpty()) {
if (mustCreateAccountHolder(sgr)) {
createAccountHolder(sgr);
} else if (psCodeTiersAH != null) {
addTrace(sgr.getId(), ACCOUNT_HOLDER_TRACE_SUBKEY, TraceStatusEnum.IN_PROGRESS,
"Le tiers viré n'est pas encore créé");
}
return null;
} else {
sgr.setAccountHolderEdemandeId(psCodeTiersAH);
try {
requestService.setAccountHolderEdemandeId(sgr.getId(), psCodeTiersAH);
} catch (CvqException e) {
// TODO
}
}
}
}
String psCodeTiersS = sgr.getSubject().getIndividual().getExternalId();
if (psCodeTiersS == null || psCodeTiersS.trim().isEmpty()) {
// external id (code tiers) not known locally :
// either check if tiers has been created in eDemande
// either ask for its creation in eDemande
psCodeTiersS = searchSubject(sgr);
// add a "hack" condition when psCodeTiersS == psCodeTiersAH
// to handle homonyms until individual search accepts birth date etc.
if (psCodeTiersS == null || psCodeTiersS.trim().isEmpty() || psCodeTiersS.trim().equals(psCodeTiersAH)) {
// tiers has not been created in eDemande ...
if (mustCreateSubject(sgr)) {
// ... and no request in progress so ask for its creation
createSubject(sgr);
} else if (psCodeTiersS != null) {
// eDemande answered since psCodeTiers is not null,
// and that means psCodeTiers is empty, so tiers
// has not been created yet.
// If psCodeTiers was null, that would mean searchIndividual
// caught an exception while contacting eDemande, and
// has already added a NOT_SENT trace.
// FIXME BOR : is this trace really needed ?
addTrace(sgr.getId(), SUBJECT_TRACE_SUBKEY, TraceStatusEnum.IN_PROGRESS,
"Le tiers sujet n'est pas encore créé");
}
return null;
} else {
// tiers has been created in eDemande, store its code locally
sgr.getSubject().getIndividual().setExternalId(psCodeTiersS);
externalService.setExternalId(label, sgr.getHomeFolder().getId(),
sgr.getSubject().getIndividual().getId(), psCodeTiersS);
}
}
// reaching this code means we have valid psCodeTiers (either because
// they were already set since it is not the subject and account holder's first request, or because
// searchIndividual returned the newly created tiers' psCodeTiers)
// Try to get the external ID if we don't already know it
String psCodeDemande = sgr.getEdemandeId();
if (psCodeDemande == null || psCodeDemande.trim().isEmpty()) {
psCodeDemande = searchRequest(sgr, psCodeTiersS);
if (psCodeDemande != null && !psCodeDemande.trim().isEmpty() && !"-1".equals(psCodeDemande)) {
sgr.setEdemandeId(psCodeDemande);
try {
requestService.setEdemandeId(sgr.getId(), psCodeDemande);
} catch (CvqException e) {
// TODO
}
}
}
// (Re)send request if needed
if (mustSendNewRequest(sgr)) {
submitRequest(sgr, psCodeTiersS, true);
} else if (mustResendRequest(sgr)) {
submitRequest(sgr, psCodeTiersS, false);
}
// check request status
String msStatut = getRequestStatus(sgr, psCodeTiersS);
if (msStatut == null) {
// got an exception while contacting Edemande
return null;
}
if (msStatut.trim().isEmpty()) {
addTrace(sgr.getId(), null, TraceStatusEnum.NOT_SENT,
"La demande n'a pas encore été reçue");
return null;
}
if ("En attente de réception par la collectivité".equals(msStatut)) {
return null;
} else if ("A compléter ou corriger".equals(msStatut) ||
"A compléter".equals(msStatut) ||
"En erreur".equals(msStatut)) {
addTrace(sgr.getId(), null, TraceStatusEnum.ERROR, msStatut);
} else if ("En cours d'analyse".equals(msStatut) ||
"En attente d'avis externe".equals(msStatut) ||
"En cours d'instruction".equals(msStatut)) {
addTrace(sgr.getId(), null, TraceStatusEnum.ACKNOWLEDGED, msStatut);
} else if ("Accepté".equals(msStatut) ||
"En cours de paiement".equals(msStatut) ||
"Payé partiellement".equals(msStatut) ||
"Terminé".equals(msStatut)) {
addTrace(sgr.getId(), null, TraceStatusEnum.ACCEPTED, msStatut);
} else if ("Refusé".equals(msStatut)) {
addTrace(sgr.getId(), null, TraceStatusEnum.REJECTED, msStatut);
}
return null;
}
private void addTrace(Long requestId, String subkey, TraceStatusEnum status, String message) {
ExternalServiceTrace est = new ExternalServiceTrace();
est.setDate(new Date());
est.setKey(String.valueOf(requestId));
est.setSubkey(subkey);
est.setKeyOwner("capdemat");
est.setMessage(message);
est.setName(label);
est.setStatus(status);
try {
externalService.create(est);
} catch (CvqPermissionException e) {
// should never happen
e.printStackTrace();
}
if (TraceStatusEnum.ERROR.equals(status)) {
try {
requestWorkflowService.updateRequestState(requestId, RequestState.UNCOMPLETE, message);
} catch (CvqObjectNotFoundException e) {
// TODO
} catch (CvqInvalidTransitionException e) {
// TODO
} catch (CvqException e) {
// TODO
}
}
}
/**
* Search for this request's individual in eDemande.
*
* @return the individual's code in eDemande, an empty string if the individual is not found,
* or null if there is an error while contacting eDemande.
*/
private String searchIndividual(StudyGrantRequest sgr, String lastName, String subkey) {
Map<String, Object> model = new HashMap<String, Object>();
model.put("lastName", lastName);
model.put("bankCode", sgr.getBankCode());
model.put("counterCode", sgr.getCounterCode());
model.put("accountNumber", sgr.getAccountNumber());
model.put("accountKey", sgr.getAccountKey());
try {
return parseData(edemandeClient.rechercherTiers(model).getRechercherTiersResponse().getReturn(),
"//resultatRechTiers/listeTiers/tiers/codeTiers");
} catch (CvqException e) {
addTrace(sgr.getId(), subkey, TraceStatusEnum.NOT_SENT, e.getMessage());
return null;
}
}
private String searchSubject(StudyGrantRequest sgr) {
return searchIndividual(sgr, sgr.getSubject().getIndividual().getLastName(), SUBJECT_TRACE_SUBKEY);
}
private String searchAccountHolder(StudyGrantRequest sgr) {
return searchIndividual(sgr, sgr.getAccountHolderLastName(), ACCOUNT_HOLDER_TRACE_SUBKEY);
}
private void createSubject(StudyGrantRequest sgr) {
Map<String, Object> model = new HashMap<String, Object>();
model.put("lastName", sgr.getSubject().getIndividual().getLastName());
model.put("address", sgr.getSubjectInformations().getSubjectAddress());
if (sgr.getSubjectInformations().getSubjectPhone() != null && !sgr.getSubjectInformations().getSubjectPhone().trim().isEmpty()) {
model.put("phone", sgr.getSubjectInformations().getSubjectPhone());
} else if (sgr.getSubjectInformations().getSubjectMobilePhone() != null && !sgr.getSubjectInformations().getSubjectMobilePhone().trim().isEmpty()) {
model.put("phone", sgr.getSubjectInformations().getSubjectMobilePhone());
}
if (sgr.getSubject().getAdult() != null) {
model.put("title",
translationService.translate("homeFolder.adult.title."
+ sgr.getSubject().getAdult().getTitle().toString().toLowerCase(), Locale.FRANCE));
} else {
if (SexType.MALE.toString().equals(sgr.getSubject().getIndividual().getSex().toString())) {
model.put("title",
translationService.translate("homeFolder.adult.title.mister", Locale.FRANCE));
} else if (SexType.FEMALE.toString().equals(sgr.getSubject().getIndividual().getSex().toString())) {
model.put("title",
translationService.translate("homeFolder.adult.title.miss", Locale.FRANCE));
} else {
model.put("title",
translationService.translate("homeFolder.adult.title.unknown", Locale.FRANCE));
}
}
model.put("firstName", sgr.getSubject().getIndividual().getFirstName());
model.put("birthPlace",
sgr.getSubject().getIndividual().getBirthPlace() != null ?
StringUtils.defaultString(sgr.getSubject().getIndividual().getBirthPlace().getCity())
: "");
model.put("birthDate", formatDate(sgr.getSubjectInformations().getSubjectBirthDate()));
model.put("bankCode", sgr.getBankCode());
model.put("counterCode", sgr.getCounterCode());
model.put("accountNumber", sgr.getAccountNumber());
model.put("accountKey", sgr.getAccountKey());
try {
model.put("email",
StringUtils.defaultIfEmpty(sgr.getSubjectInformations().getSubjectEmail(),
homeFolderService.getHomeFolderResponsible(sgr.getHomeFolder().getId()).getEmail()));
GestionCompteResponseDocument response = edemandeClient.creerTiers(model);
if (!"0".equals(parseData(response.getGestionCompteResponse().getReturn(), "//Retour/codeRetour"))) {
addTrace(sgr.getId(), SUBJECT_TRACE_SUBKEY, TraceStatusEnum.ERROR, parseData(response.getGestionCompteResponse().getReturn(), "//Retour/messageRetour"));
} else {
addTrace(sgr.getId(), SUBJECT_TRACE_SUBKEY, TraceStatusEnum.IN_PROGRESS, "Demande de création du tiers sujet");
}
} catch (CvqException e) {
e.printStackTrace();
addTrace(sgr.getId(), SUBJECT_TRACE_SUBKEY, TraceStatusEnum.NOT_SENT, e.getMessage());
}
}
private void createAccountHolder(StudyGrantRequest sgr) {
Map<String, Object> model = new HashMap<String, Object>();
model.put("title",
translationService.translate("homeFolder.adult.title."
+ sgr.getAccountHolderTitle().toString().toLowerCase(), Locale.FRANCE));
model.put("lastName", sgr.getAccountHolderLastName());
//FIXME placeholders; are these really needed ?
model.put("address", sgr.getSubjectInformations().getSubjectAddress());
model.put("phone", "");
model.put("birthPlace", "");
//ENDFIXME
model.put("firstName", sgr.getAccountHolderFirstName());
model.put("birthDate", formatDate(sgr.getAccountHolderBirthDate()));
model.put("bankCode", sgr.getBankCode());
model.put("counterCode", sgr.getCounterCode());
model.put("accountNumber", sgr.getAccountNumber());
model.put("accountKey", sgr.getAccountKey());
try {
//FIXME placeholder
model.put("email",
homeFolderService.getHomeFolderResponsible(sgr.getHomeFolder().getId()).getEmail());
GestionCompteResponseDocument response = edemandeClient.creerTiers(model);
if (!"0".equals(parseData(response.getGestionCompteResponse().getReturn(), "//Retour/codeRetour"))) {
addTrace(sgr.getId(), ACCOUNT_HOLDER_TRACE_SUBKEY, TraceStatusEnum.ERROR, parseData(response.getGestionCompteResponse().getReturn(), "//Retour/messageRetour"));
} else {
addTrace(sgr.getId(), ACCOUNT_HOLDER_TRACE_SUBKEY, TraceStatusEnum.IN_PROGRESS, "Demande de création du tiers viré");
}
} catch (CvqException e) {
e.printStackTrace();
addTrace(sgr.getId(), ACCOUNT_HOLDER_TRACE_SUBKEY, TraceStatusEnum.NOT_SENT, e.getMessage());
}
}
private void submitRequest(StudyGrantRequest sgr, String psCodeTiers, boolean firstSending) {
Map<String, Object> model = new HashMap<String, Object>();
String requestData = null;
if (!firstSending) {
try {
requestData = edemandeClient.chargerDemande(psCodeTiers, sgr.getEdemandeId()).getChargerDemandeResponse().getReturn();
} catch (CvqException e) {
e.printStackTrace();
addTrace(sgr.getId(), null, TraceStatusEnum.NOT_SENT, e.getMessage());
}
}
model.put("externalRequestId", buildExternalRequestId(sgr));
model.put("psCodeTiers", psCodeTiers);
model.put("psCodeDemande",
StringUtils.defaultIfEmpty(sgr.getEdemandeId(), "-1"));
model.put("etatCourant", firstSending ? 2 : 1);
model.put("firstName", sgr.getSubject().getIndividual().getFirstName());
model.put("lastName", sgr.getSubject().getIndividual().getLastName());
model.put("postalCode", sgr.getSubjectInformations().getSubjectAddress().getPostalCode());
model.put("city", sgr.getSubjectInformations().getSubjectAddress().getCity());
model.put("bankCode", sgr.getBankCode());
model.put("counterCode", sgr.getCounterCode());
model.put("accountNumber", sgr.getAccountNumber());
model.put("accountKey", sgr.getAccountKey());
model.put("firstRequest", sgr.getSubjectInformations().getSubjectFirstRequest());
model.put("creationDate", formatDate(sgr.getCreationDate()));
model.put("taxHouseholdCityCode", sgr.getTaxHouseholdCityArray(0).getName());
model.put("taxHouseholdIncome", sgr.getTaxHouseholdIncome());
model.put("hasCROUSHelp", sgr.getHasCROUSHelp());
model.put("hasRegionalCouncilHelp", sgr.getHasRegionalCouncilHelp());
model.put("hasEuropeHelp", sgr.getHasEuropeHelp());
model.put("hasOtherHelp", sgr.getHasOtherHelp());
model.put("AlevelsDate", sgr.getALevelsInformations().getAlevelsDate());
model.put("AlevelsType",
translationService.translate("sgr.property.alevels."
+ sgr.getALevelsInformations().getAlevels().toString().toLowerCase(), Locale.FRANCE));
model.put("currentStudiesType",
StringUtils.defaultIfEmpty(sgr.getCurrentStudiesInformations().getOtherStudiesLabel(),
translationService.translate("sgr.property.currentStudies."
+ sgr.getCurrentStudiesInformations().getCurrentStudies().toString(), Locale.FRANCE)));
model.put("currentStudiesLevel",
translationService.translate("sgr.property.currentStudiesLevel."
+ sgr.getCurrentStudiesInformations().getCurrentStudiesLevel().toString(), Locale.FRANCE));
model.put("sandwichCourses", sgr.getCurrentStudiesInformations().getSandwichCourses());
model.put("abroadInternship", sgr.getCurrentStudiesInformations().getAbroadInternship());
model.put("abroadInternshipStartDate",
formatDate(sgr.getCurrentStudiesInformations().getAbroadInternshipStartDate()));
model.put("abroadInternshipEndDate",
formatDate(sgr.getCurrentStudiesInformations().getAbroadInternshipEndDate()));
model.put("currentSchoolName",
StringUtils.defaultIfEmpty(sgr.getCurrentSchool().getCurrentSchoolNamePrecision(),
sgr.getCurrentSchool().getCurrentSchoolNameArray(0).getName()));
model.put("currentSchoolPostalCode",
StringUtils.defaultString(sgr.getCurrentSchool().getCurrentSchoolPostalCode()));
model.put("currentSchoolCity",
StringUtils.defaultString(sgr.getCurrentSchool().getCurrentSchoolCity()));
model.put("currentSchoolCountry", sgr.getCurrentSchool().getCurrentSchoolCountry() != null ?
translationService.translate("sgr.property.currentSchoolCountry."
+ sgr.getCurrentSchool().getCurrentSchoolCountry()) : "");
model.put("abroadInternshipSchoolName", sgr.getCurrentStudiesInformations().getAbroadInternship() ?
sgr.getCurrentStudiesInformations().getAbroadInternshipSchoolName() : "");
model.put("abroadInternshipSchoolCountry", sgr.getCurrentStudiesInformations().getAbroadInternship() ?
translationService.translate("sgr.property.abroadInternshipSchoolCountry."
+ sgr.getCurrentStudiesInformations().getAbroadInternshipSchoolCountry()) : "");
model.put("distance",
translationService.translate("sgr.property.distance."
+ sgr.getDistance().toString(), Locale.FRANCE));
List<Map<String, String>> documents = new ArrayList<Map<String, String>>();
model.put("documents", documents);
try {
for (RequestDocument requestDoc : requestService.getAssociatedDocuments(sgr.getId())) {
Document document = documentService.getById(requestDoc.getDocumentId());
- //Map<String, Object> doc = new HashMap<String, Object>();
- //documents.add(doc);
- //List<Map<String, String>> parts = new ArrayList<Map<String, String>>();
- //doc.put("parts", parts);
int i = 1;
for (DocumentBinary documentBinary : document.getDatas()) {
Map<String, String> doc = new HashMap<String, String>();
documents.add(doc);
String filename = org.springframework.util.StringUtils.arrayToDelimitedString(
new String[] {
"CapDemat", document.getDocumentType().getName(),
String.valueOf(sgr.getId()), String.valueOf(i++)
}, "-");
doc.put("filename", filename);
if (IDocumentTypeService.BANK_IDENTITY_RECEIPT_TYPE.equals(
document.getDocumentType().getType())) {
doc.put("label", "RIB");
} else if (IDocumentTypeService.SCHOOL_CERTIFICATE_TYPE.equals(
document.getDocumentType().getType())) {
doc.put("label", "Certificat d'inscription");
- } else if (IDocumentTypeService.SCHOOL_CERTIFICATE_TYPE.equals(
+ } else if (IDocumentTypeService.REVENUE_TAXES_NOTIFICATION_TWO_YEARS_AGO.equals(
document.getDocumentType().getType())) {
doc.put("label", "Avis d'imposition");
} else {
// should never happen
doc.put("label", document.getDocumentType().getName());
}
try {
doc.put("remotePath", uploader.upload(filename, documentBinary.getData()));
} catch (JSchException e) {
addTrace(sgr.getId(), null, TraceStatusEnum.ERROR, "Erreur à l'envoi d'une pièce jointe");
} catch (SftpException e) {
addTrace(sgr.getId(), null, TraceStatusEnum.ERROR, "Erreur à l'envoi d'une pièce jointe");
}
}
}
model.put("taxHouseholdCityPrecision",
StringUtils.defaultString(sgr.getTaxHouseholdCityPrecision()));
model.put("msStatut", firstSending ? "" :
getRequestStatus(sgr, psCodeTiers));
model.put("millesime", firstSending ? "" :
parseData(requestData, "//donneesDemande/Demande/miMillesime"));
model.put("msCodext", firstSending ? "" :
parseData(requestData, "//donneesDemande/Demande/msCodext"));
model.put("requestTypeCode",
parseData(edemandeClient.chargerTypeDemande().getChargerTypeDemandeResponse().getReturn(), "//typeDemande/code"));
model.put("address", parseAddress((String)model.get("psCodeTiers")));
EnregistrerValiderFormulaireResponseDocument enregistrerValiderFormulaireResponseDocument = edemandeClient.enregistrerValiderFormulaire(model);
if (!"0".equals(parseData(enregistrerValiderFormulaireResponseDocument.getEnregistrerValiderFormulaireResponse().getReturn(), "//Retour/codeRetour"))) {
addTrace(sgr.getId(), null, TraceStatusEnum.ERROR, parseData(enregistrerValiderFormulaireResponseDocument.getEnregistrerValiderFormulaireResponse().getReturn(), "//Retour/messageRetour"));
} else {
addTrace(sgr.getId(), null, TraceStatusEnum.SENT, "Demande transmise");
}
} catch (CvqException e) {
e.printStackTrace();
addTrace(sgr.getId(), null, TraceStatusEnum.NOT_SENT, e.getMessage());
}
}
private String searchRequest(StudyGrantRequest sgr, String psCodeTiers) {
try {
return parseData(edemandeClient.rechercheDemandesTiers(psCodeTiers)
.getRechercheDemandesTiersResponse().getReturn(),
"//resultatRechDemandes/listeDemandes/Demande/moOrigineApsect[msIdentifiant ='"
+ buildExternalRequestId(sgr) + "']/../miCode");
} catch (CvqException e) {
addTrace(sgr.getId(), null, TraceStatusEnum.NOT_SENT, e.getMessage());
return null;
}
}
private String getRequestStatus(StudyGrantRequest sgr, String psCodeTiers) {
try {
if (sgr.getEdemandeId() == null || sgr.getEdemandeId().trim().isEmpty()) {
return parseData(edemandeClient.rechercheDemandesTiers(psCodeTiers)
.getRechercheDemandesTiersResponse().getReturn(),
"//resultatRechDemandes/listeDemandes/Demande/moOrigineApsect[msIdentifiant ='"
+ buildExternalRequestId(sgr) + "']/../msStatut");
} else {
return parseData(edemandeClient.chargerDemande(psCodeTiers, sgr.getEdemandeId())
.getChargerDemandeResponse().getReturn(),
"//donneesDemande/Demande/msStatut");
}
} catch (CvqException e) {
addTrace(sgr.getId(), null, TraceStatusEnum.NOT_SENT, e.getMessage());
return null;
}
}
public List<String> checkExternalReferential(final XmlObject requestXml) {
StudyGrantRequest sgr = ((StudyGrantRequestDocument) requestXml).getStudyGrantRequest();
List<String> result = new ArrayList<String>();
try {
String postalCodeAndCityCheck = edemandeClient.existenceCommunePostale(sgr.getSubjectInformations().getSubjectAddress().getPostalCode(), sgr.getSubjectInformations().getSubjectAddress().getCity()).getExistenceCommunePostaleResponse().getReturn();
if (!"0".equals(parseData(postalCodeAndCityCheck, "//FluxWebService/msCodeRet"))) {
result.add(parseData(postalCodeAndCityCheck, "//FluxWebService/erreur/message"));
}
String bankInformationsCheck = edemandeClient.verifierRIB(sgr.getBankCode(), sgr.getCounterCode(), sgr.getAccountNumber(), sgr.getAccountKey()).getVerifierRIBResponse().getReturn();
if (!"0".equals(parseData(bankInformationsCheck, "//FluxWebService/msCodeRet"))) {
result.add(parseData(bankInformationsCheck, "//FluxWebService/erreur/message"));
}
} catch (CvqException e) {
result.add("Impossible de contacter Edemande");
}
return result;
}
public Map<String, Object> loadExternalInformations(XmlObject requestXml)
throws CvqException {
StudyGrantRequest sgr = ((StudyGrantRequestDocument) requestXml).getStudyGrantRequest();
if (sgr.getSubject().getIndividual().getExternalId() == null
|| sgr.getSubject().getIndividual().getExternalId().trim().isEmpty()
|| sgr.getEdemandeId() == null || sgr.getEdemandeId().trim().isEmpty()) {
return Collections.emptyMap();
}
Map<String, Object> informations = new TreeMap<String, Object>();
String request = edemandeClient.chargerDemande(
sgr.getSubject().getIndividual().getExternalId(), sgr.getEdemandeId())
.getChargerDemandeResponse().getReturn();
String status = getRequestStatus(sgr, sgr.getSubject().getIndividual().getExternalId());
if (status != null && !status.trim().isEmpty()) {
informations.put("sgr.property.externalStatus", status);
}
String grantedAmount = parseData(request, "//donneesDemande/Demande/mdMtAccorde");
if (grantedAmount != null && !grantedAmount.trim().isEmpty()) {
informations.put("sgr.property.grantedAmount",
new DecimalFormat(translationService.translate("format.currency"))
.format(new BigDecimal(grantedAmount)));
}
String paidAmount = parseData(request, "//donneesDemande/Demande/mdMtRealise");
if (paidAmount != null && !paidAmount.trim().isEmpty()) {
informations.put("sgr.property.paidAmount",
new DecimalFormat(translationService.translate("format.currency"))
.format(new BigDecimal(paidAmount)));
}
return informations;
}
public void setLabel(String label) {
this.label = label;
}
public void setEdemandeClient(IEdemandeClient edemandeClient) {
this.edemandeClient = edemandeClient;
}
public boolean supportsConsumptions() {
return false;
}
public boolean handlesTraces() {
return true;
}
private Map<String, String> parseAddress(String psCodeTiers)
throws CvqException {
String tiers = edemandeClient.initialiserSuiviDemande(psCodeTiers).getInitialiserSuiviDemandeResponse().getReturn();
Map<String, String> address = new HashMap<String, String>();
for (String addressField : ADDRESS_FIELDS) {
address.put(addressField, parseData(tiers, "//donneesTiers/tiers/mvAdresses/CTierAdresseVO/" + addressField));
}
return address;
}
private String parseData(String returnElement, String path)
throws CvqException {
try {
return new DOMXPath(path)
.stringValueOf(
DocumentBuilderFactory.newInstance().newDocumentBuilder()
.parse(new InputSource(new StringReader(returnElement)))
.getDocumentElement());
} catch (JaxenException e) {
e.printStackTrace();
throw new CvqException("Erreur lors de la lecture de la réponse du service externe");
} catch (SAXException e) {
e.printStackTrace();
throw new CvqException("Erreur lors de la lecture de la réponse du service externe");
} catch (IOException e) {
e.printStackTrace();
throw new CvqException("Erreur lors de la lecture de la réponse du service externe");
} catch (ParserConfigurationException e) {
e.printStackTrace();
throw new CvqException("Erreur lors de la lecture de la réponse du service externe");
}
}
private String buildExternalRequestId(StudyGrantRequest sgr) {
return org.springframework.util.StringUtils.arrayToDelimitedString(
new String[] {
"CapDemat",
new SimpleDateFormat("yyyyMMdd").format(new Date(sgr.getCreationDate().getTimeInMillis())),
sgr.getSubject().getIndividual().getFirstName(),
sgr.getSubject().getIndividual().getLastName(),
String.valueOf(sgr.getId())
},
"-");
}
/**
* Whether or not we have to send the request.
*
* @return true if the request has no SENT trace (it has never been successfully sent)
* or it has an error trace and no Edemande ID (it was sent and received, but rejected and must be sent as new)
*/
private boolean mustSendNewRequest(StudyGrantRequest sgr) {
return !externalService.hasTraceWithStatus(sgr.getId(), null, label, TraceStatusEnum.SENT)
|| (externalService.hasTraceWithStatus(sgr.getId(), null, label, TraceStatusEnum.ERROR)
&& (sgr.getEdemandeId() == null || sgr.getEdemandeId().trim().isEmpty()));
}
/**
* Whether or not we have to resend the request.
*
* @return true if the request has an Edemande ID (so it was already sent),
* and an ERROR trace not followed by a SENT trace
*/
private boolean mustResendRequest(StudyGrantRequest sgr) {
if (!externalService.hasTraceWithStatus(sgr.getId(), null, label, TraceStatusEnum.ERROR)
|| sgr.getEdemandeId() == null || sgr.getEdemandeId().trim().isEmpty()) {
return false;
}
List<ExternalServiceTrace> traces = new ArrayList<ExternalServiceTrace>(
externalService.getTraces(sgr.getId(), label));
Collections.sort(traces, new Comparator<ExternalServiceTrace>() {
public int compare(ExternalServiceTrace o1, ExternalServiceTrace o2) {
return o2.getDate().compareTo(o1.getDate());
}
});
for (ExternalServiceTrace est : traces) {
if (TraceStatusEnum.SENT.equals(est.getStatus())) {
return false;
} else if (TraceStatusEnum.ERROR.equals(est.getStatus())) {
return true;
}
}
// we should never execute the next line :
// the above loop should have found a SENT trace and returned false,
// or found the ERROR trace that IS in the list
// (otherwise the first test would have succeded)
// however, for compilation issues (and an hypothetic concurrent traces deletion)
// we return false, to do nothing rather than doing something wrong
return false;
}
/**
* Determines if we must send an individual creation request for the request's subject
* or account holder when this individual has no psCodeTiers yet.
*/
private boolean mustCreateIndividual(StudyGrantRequest sgr, String subkey) {
if (!externalService.hasTraceWithStatus(sgr.getId(), subkey, label,
TraceStatusEnum.IN_PROGRESS)) {
return true;
}
List<ExternalServiceTrace> traces = new ArrayList<ExternalServiceTrace>(
externalService.getTraces(sgr.getId(), subkey, label));
Collections.sort(traces, new Comparator<ExternalServiceTrace>() {
public int compare(ExternalServiceTrace o1, ExternalServiceTrace o2) {
return o2.getDate().compareTo(o1.getDate());
}
});
for (ExternalServiceTrace est : traces) {
if (TraceStatusEnum.IN_PROGRESS.equals(est.getStatus())) {
return false;
} else if (TraceStatusEnum.ERROR.equals(est.getStatus())) {
return true;
}
}
return false;
}
private String formatDate(Calendar calendar) {
if (calendar == null) return "";
return formatter.format(new Date(calendar.getTimeInMillis()));
}
private boolean mustCreateAccountHolder(StudyGrantRequest sgr) {
return mustCreateIndividual(sgr, ACCOUNT_HOLDER_TRACE_SUBKEY);
}
private boolean mustCreateSubject(StudyGrantRequest sgr) {
return mustCreateIndividual(sgr, SUBJECT_TRACE_SUBKEY);
}
@Override
public void checkConfiguration(ExternalServiceBean externalServiceBean)
throws CvqConfigurationException {
}
@Override
public void creditHomeFolderAccounts(Collection<PurchaseItem> purchaseItems,
String cvqReference, String bankReference, Long homeFolderId,
String externalHomeFolderId, String externalId, Date validationDate)
throws CvqException {
}
@Override
public Map<String, List<ExternalAccountItem>> getAccountsByHomeFolder(Long homeFolderId,
String externalHomeFolderId, String externalId) throws CvqException {
return null;
}
@Override
public Map<Date, String> getConsumptionsByRequest(Request request, Date dateFrom, Date dateTo)
throws CvqException {
return null;
}
@Override
public Map<Individual, Map<String, String>> getIndividualAccountsInformation(Long homeFolderId,
String externalHomeFolderId, String externalId) throws CvqException {
return null;
}
@Override
public String getLabel() {
return label;
}
@Override
public String helloWorld() throws CvqException {
return null;
}
@Override
public void loadDepositAccountDetails(ExternalDepositAccountItem edai) throws CvqException {
}
@Override
public void loadInvoiceDetails(ExternalInvoiceItem eii) throws CvqException {
}
public void setRequestService(IStudyGrantRequestService requestService) {
this.requestService = requestService;
}
public void setDocumentService(IDocumentService documentService) {
this.documentService = documentService;
}
public void setExternalService(IExternalService externalService) {
this.externalService = externalService;
}
public void setRequestWorkflowService(IRequestWorkflowService requestWorkflowService) {
this.requestWorkflowService = requestWorkflowService;
}
public void setTranslationService(ITranslationService translationService) {
this.translationService = translationService;
}
public void setUploader(EdemandeUploader uploader) {
this.uploader = uploader;
}
public void setBeanFactory(BeanFactory beanFactory) throws BeansException {
this.beanFactory = (ListableBeanFactory)beanFactory;
}
}
| false | true | private void submitRequest(StudyGrantRequest sgr, String psCodeTiers, boolean firstSending) {
Map<String, Object> model = new HashMap<String, Object>();
String requestData = null;
if (!firstSending) {
try {
requestData = edemandeClient.chargerDemande(psCodeTiers, sgr.getEdemandeId()).getChargerDemandeResponse().getReturn();
} catch (CvqException e) {
e.printStackTrace();
addTrace(sgr.getId(), null, TraceStatusEnum.NOT_SENT, e.getMessage());
}
}
model.put("externalRequestId", buildExternalRequestId(sgr));
model.put("psCodeTiers", psCodeTiers);
model.put("psCodeDemande",
StringUtils.defaultIfEmpty(sgr.getEdemandeId(), "-1"));
model.put("etatCourant", firstSending ? 2 : 1);
model.put("firstName", sgr.getSubject().getIndividual().getFirstName());
model.put("lastName", sgr.getSubject().getIndividual().getLastName());
model.put("postalCode", sgr.getSubjectInformations().getSubjectAddress().getPostalCode());
model.put("city", sgr.getSubjectInformations().getSubjectAddress().getCity());
model.put("bankCode", sgr.getBankCode());
model.put("counterCode", sgr.getCounterCode());
model.put("accountNumber", sgr.getAccountNumber());
model.put("accountKey", sgr.getAccountKey());
model.put("firstRequest", sgr.getSubjectInformations().getSubjectFirstRequest());
model.put("creationDate", formatDate(sgr.getCreationDate()));
model.put("taxHouseholdCityCode", sgr.getTaxHouseholdCityArray(0).getName());
model.put("taxHouseholdIncome", sgr.getTaxHouseholdIncome());
model.put("hasCROUSHelp", sgr.getHasCROUSHelp());
model.put("hasRegionalCouncilHelp", sgr.getHasRegionalCouncilHelp());
model.put("hasEuropeHelp", sgr.getHasEuropeHelp());
model.put("hasOtherHelp", sgr.getHasOtherHelp());
model.put("AlevelsDate", sgr.getALevelsInformations().getAlevelsDate());
model.put("AlevelsType",
translationService.translate("sgr.property.alevels."
+ sgr.getALevelsInformations().getAlevels().toString().toLowerCase(), Locale.FRANCE));
model.put("currentStudiesType",
StringUtils.defaultIfEmpty(sgr.getCurrentStudiesInformations().getOtherStudiesLabel(),
translationService.translate("sgr.property.currentStudies."
+ sgr.getCurrentStudiesInformations().getCurrentStudies().toString(), Locale.FRANCE)));
model.put("currentStudiesLevel",
translationService.translate("sgr.property.currentStudiesLevel."
+ sgr.getCurrentStudiesInformations().getCurrentStudiesLevel().toString(), Locale.FRANCE));
model.put("sandwichCourses", sgr.getCurrentStudiesInformations().getSandwichCourses());
model.put("abroadInternship", sgr.getCurrentStudiesInformations().getAbroadInternship());
model.put("abroadInternshipStartDate",
formatDate(sgr.getCurrentStudiesInformations().getAbroadInternshipStartDate()));
model.put("abroadInternshipEndDate",
formatDate(sgr.getCurrentStudiesInformations().getAbroadInternshipEndDate()));
model.put("currentSchoolName",
StringUtils.defaultIfEmpty(sgr.getCurrentSchool().getCurrentSchoolNamePrecision(),
sgr.getCurrentSchool().getCurrentSchoolNameArray(0).getName()));
model.put("currentSchoolPostalCode",
StringUtils.defaultString(sgr.getCurrentSchool().getCurrentSchoolPostalCode()));
model.put("currentSchoolCity",
StringUtils.defaultString(sgr.getCurrentSchool().getCurrentSchoolCity()));
model.put("currentSchoolCountry", sgr.getCurrentSchool().getCurrentSchoolCountry() != null ?
translationService.translate("sgr.property.currentSchoolCountry."
+ sgr.getCurrentSchool().getCurrentSchoolCountry()) : "");
model.put("abroadInternshipSchoolName", sgr.getCurrentStudiesInformations().getAbroadInternship() ?
sgr.getCurrentStudiesInformations().getAbroadInternshipSchoolName() : "");
model.put("abroadInternshipSchoolCountry", sgr.getCurrentStudiesInformations().getAbroadInternship() ?
translationService.translate("sgr.property.abroadInternshipSchoolCountry."
+ sgr.getCurrentStudiesInformations().getAbroadInternshipSchoolCountry()) : "");
model.put("distance",
translationService.translate("sgr.property.distance."
+ sgr.getDistance().toString(), Locale.FRANCE));
List<Map<String, String>> documents = new ArrayList<Map<String, String>>();
model.put("documents", documents);
try {
for (RequestDocument requestDoc : requestService.getAssociatedDocuments(sgr.getId())) {
Document document = documentService.getById(requestDoc.getDocumentId());
//Map<String, Object> doc = new HashMap<String, Object>();
//documents.add(doc);
//List<Map<String, String>> parts = new ArrayList<Map<String, String>>();
//doc.put("parts", parts);
int i = 1;
for (DocumentBinary documentBinary : document.getDatas()) {
Map<String, String> doc = new HashMap<String, String>();
documents.add(doc);
String filename = org.springframework.util.StringUtils.arrayToDelimitedString(
new String[] {
"CapDemat", document.getDocumentType().getName(),
String.valueOf(sgr.getId()), String.valueOf(i++)
}, "-");
doc.put("filename", filename);
if (IDocumentTypeService.BANK_IDENTITY_RECEIPT_TYPE.equals(
document.getDocumentType().getType())) {
doc.put("label", "RIB");
} else if (IDocumentTypeService.SCHOOL_CERTIFICATE_TYPE.equals(
document.getDocumentType().getType())) {
doc.put("label", "Certificat d'inscription");
} else if (IDocumentTypeService.SCHOOL_CERTIFICATE_TYPE.equals(
document.getDocumentType().getType())) {
doc.put("label", "Avis d'imposition");
} else {
// should never happen
doc.put("label", document.getDocumentType().getName());
}
try {
doc.put("remotePath", uploader.upload(filename, documentBinary.getData()));
} catch (JSchException e) {
addTrace(sgr.getId(), null, TraceStatusEnum.ERROR, "Erreur à l'envoi d'une pièce jointe");
} catch (SftpException e) {
addTrace(sgr.getId(), null, TraceStatusEnum.ERROR, "Erreur à l'envoi d'une pièce jointe");
}
}
}
model.put("taxHouseholdCityPrecision",
StringUtils.defaultString(sgr.getTaxHouseholdCityPrecision()));
model.put("msStatut", firstSending ? "" :
getRequestStatus(sgr, psCodeTiers));
model.put("millesime", firstSending ? "" :
parseData(requestData, "//donneesDemande/Demande/miMillesime"));
model.put("msCodext", firstSending ? "" :
parseData(requestData, "//donneesDemande/Demande/msCodext"));
model.put("requestTypeCode",
parseData(edemandeClient.chargerTypeDemande().getChargerTypeDemandeResponse().getReturn(), "//typeDemande/code"));
model.put("address", parseAddress((String)model.get("psCodeTiers")));
EnregistrerValiderFormulaireResponseDocument enregistrerValiderFormulaireResponseDocument = edemandeClient.enregistrerValiderFormulaire(model);
if (!"0".equals(parseData(enregistrerValiderFormulaireResponseDocument.getEnregistrerValiderFormulaireResponse().getReturn(), "//Retour/codeRetour"))) {
addTrace(sgr.getId(), null, TraceStatusEnum.ERROR, parseData(enregistrerValiderFormulaireResponseDocument.getEnregistrerValiderFormulaireResponse().getReturn(), "//Retour/messageRetour"));
} else {
addTrace(sgr.getId(), null, TraceStatusEnum.SENT, "Demande transmise");
}
} catch (CvqException e) {
e.printStackTrace();
addTrace(sgr.getId(), null, TraceStatusEnum.NOT_SENT, e.getMessage());
}
}
| private void submitRequest(StudyGrantRequest sgr, String psCodeTiers, boolean firstSending) {
Map<String, Object> model = new HashMap<String, Object>();
String requestData = null;
if (!firstSending) {
try {
requestData = edemandeClient.chargerDemande(psCodeTiers, sgr.getEdemandeId()).getChargerDemandeResponse().getReturn();
} catch (CvqException e) {
e.printStackTrace();
addTrace(sgr.getId(), null, TraceStatusEnum.NOT_SENT, e.getMessage());
}
}
model.put("externalRequestId", buildExternalRequestId(sgr));
model.put("psCodeTiers", psCodeTiers);
model.put("psCodeDemande",
StringUtils.defaultIfEmpty(sgr.getEdemandeId(), "-1"));
model.put("etatCourant", firstSending ? 2 : 1);
model.put("firstName", sgr.getSubject().getIndividual().getFirstName());
model.put("lastName", sgr.getSubject().getIndividual().getLastName());
model.put("postalCode", sgr.getSubjectInformations().getSubjectAddress().getPostalCode());
model.put("city", sgr.getSubjectInformations().getSubjectAddress().getCity());
model.put("bankCode", sgr.getBankCode());
model.put("counterCode", sgr.getCounterCode());
model.put("accountNumber", sgr.getAccountNumber());
model.put("accountKey", sgr.getAccountKey());
model.put("firstRequest", sgr.getSubjectInformations().getSubjectFirstRequest());
model.put("creationDate", formatDate(sgr.getCreationDate()));
model.put("taxHouseholdCityCode", sgr.getTaxHouseholdCityArray(0).getName());
model.put("taxHouseholdIncome", sgr.getTaxHouseholdIncome());
model.put("hasCROUSHelp", sgr.getHasCROUSHelp());
model.put("hasRegionalCouncilHelp", sgr.getHasRegionalCouncilHelp());
model.put("hasEuropeHelp", sgr.getHasEuropeHelp());
model.put("hasOtherHelp", sgr.getHasOtherHelp());
model.put("AlevelsDate", sgr.getALevelsInformations().getAlevelsDate());
model.put("AlevelsType",
translationService.translate("sgr.property.alevels."
+ sgr.getALevelsInformations().getAlevels().toString().toLowerCase(), Locale.FRANCE));
model.put("currentStudiesType",
StringUtils.defaultIfEmpty(sgr.getCurrentStudiesInformations().getOtherStudiesLabel(),
translationService.translate("sgr.property.currentStudies."
+ sgr.getCurrentStudiesInformations().getCurrentStudies().toString(), Locale.FRANCE)));
model.put("currentStudiesLevel",
translationService.translate("sgr.property.currentStudiesLevel."
+ sgr.getCurrentStudiesInformations().getCurrentStudiesLevel().toString(), Locale.FRANCE));
model.put("sandwichCourses", sgr.getCurrentStudiesInformations().getSandwichCourses());
model.put("abroadInternship", sgr.getCurrentStudiesInformations().getAbroadInternship());
model.put("abroadInternshipStartDate",
formatDate(sgr.getCurrentStudiesInformations().getAbroadInternshipStartDate()));
model.put("abroadInternshipEndDate",
formatDate(sgr.getCurrentStudiesInformations().getAbroadInternshipEndDate()));
model.put("currentSchoolName",
StringUtils.defaultIfEmpty(sgr.getCurrentSchool().getCurrentSchoolNamePrecision(),
sgr.getCurrentSchool().getCurrentSchoolNameArray(0).getName()));
model.put("currentSchoolPostalCode",
StringUtils.defaultString(sgr.getCurrentSchool().getCurrentSchoolPostalCode()));
model.put("currentSchoolCity",
StringUtils.defaultString(sgr.getCurrentSchool().getCurrentSchoolCity()));
model.put("currentSchoolCountry", sgr.getCurrentSchool().getCurrentSchoolCountry() != null ?
translationService.translate("sgr.property.currentSchoolCountry."
+ sgr.getCurrentSchool().getCurrentSchoolCountry()) : "");
model.put("abroadInternshipSchoolName", sgr.getCurrentStudiesInformations().getAbroadInternship() ?
sgr.getCurrentStudiesInformations().getAbroadInternshipSchoolName() : "");
model.put("abroadInternshipSchoolCountry", sgr.getCurrentStudiesInformations().getAbroadInternship() ?
translationService.translate("sgr.property.abroadInternshipSchoolCountry."
+ sgr.getCurrentStudiesInformations().getAbroadInternshipSchoolCountry()) : "");
model.put("distance",
translationService.translate("sgr.property.distance."
+ sgr.getDistance().toString(), Locale.FRANCE));
List<Map<String, String>> documents = new ArrayList<Map<String, String>>();
model.put("documents", documents);
try {
for (RequestDocument requestDoc : requestService.getAssociatedDocuments(sgr.getId())) {
Document document = documentService.getById(requestDoc.getDocumentId());
int i = 1;
for (DocumentBinary documentBinary : document.getDatas()) {
Map<String, String> doc = new HashMap<String, String>();
documents.add(doc);
String filename = org.springframework.util.StringUtils.arrayToDelimitedString(
new String[] {
"CapDemat", document.getDocumentType().getName(),
String.valueOf(sgr.getId()), String.valueOf(i++)
}, "-");
doc.put("filename", filename);
if (IDocumentTypeService.BANK_IDENTITY_RECEIPT_TYPE.equals(
document.getDocumentType().getType())) {
doc.put("label", "RIB");
} else if (IDocumentTypeService.SCHOOL_CERTIFICATE_TYPE.equals(
document.getDocumentType().getType())) {
doc.put("label", "Certificat d'inscription");
} else if (IDocumentTypeService.REVENUE_TAXES_NOTIFICATION_TWO_YEARS_AGO.equals(
document.getDocumentType().getType())) {
doc.put("label", "Avis d'imposition");
} else {
// should never happen
doc.put("label", document.getDocumentType().getName());
}
try {
doc.put("remotePath", uploader.upload(filename, documentBinary.getData()));
} catch (JSchException e) {
addTrace(sgr.getId(), null, TraceStatusEnum.ERROR, "Erreur à l'envoi d'une pièce jointe");
} catch (SftpException e) {
addTrace(sgr.getId(), null, TraceStatusEnum.ERROR, "Erreur à l'envoi d'une pièce jointe");
}
}
}
model.put("taxHouseholdCityPrecision",
StringUtils.defaultString(sgr.getTaxHouseholdCityPrecision()));
model.put("msStatut", firstSending ? "" :
getRequestStatus(sgr, psCodeTiers));
model.put("millesime", firstSending ? "" :
parseData(requestData, "//donneesDemande/Demande/miMillesime"));
model.put("msCodext", firstSending ? "" :
parseData(requestData, "//donneesDemande/Demande/msCodext"));
model.put("requestTypeCode",
parseData(edemandeClient.chargerTypeDemande().getChargerTypeDemandeResponse().getReturn(), "//typeDemande/code"));
model.put("address", parseAddress((String)model.get("psCodeTiers")));
EnregistrerValiderFormulaireResponseDocument enregistrerValiderFormulaireResponseDocument = edemandeClient.enregistrerValiderFormulaire(model);
if (!"0".equals(parseData(enregistrerValiderFormulaireResponseDocument.getEnregistrerValiderFormulaireResponse().getReturn(), "//Retour/codeRetour"))) {
addTrace(sgr.getId(), null, TraceStatusEnum.ERROR, parseData(enregistrerValiderFormulaireResponseDocument.getEnregistrerValiderFormulaireResponse().getReturn(), "//Retour/messageRetour"));
} else {
addTrace(sgr.getId(), null, TraceStatusEnum.SENT, "Demande transmise");
}
} catch (CvqException e) {
e.printStackTrace();
addTrace(sgr.getId(), null, TraceStatusEnum.NOT_SENT, e.getMessage());
}
}
|
diff --git a/UUID.java b/UUID.java
index a2cf795..e063cf6 100644
--- a/UUID.java
+++ b/UUID.java
@@ -1,51 +1,51 @@
import java.security.SecureRandom;
public final class UUID {
private static long lastTime = Long.MIN_VALUE;
// use a short instead of a byte to work around Java's lack of unsigned types.
private static short sequenceCounter = 0;
private static long versionIdentifier = 0xC000000000000000L;
private static long versionAndNodeIdentifier;
static {
// generate a random number for the node identifier.
SecureRandom random = new SecureRandom();
long nodeIdentifier = (random.nextLong() & 0x0000FFFFFFFFFFFFL) << 8;
versionAndNodeIdentifier = versionIdentifier | nodeIdentifier;
}
public static synchronized java.util.UUID next() {
// just pad out to microseconds for now.
long time = System.currentTimeMillis() * 1000;
// handle the clock moving backwards.
if (time < lastTime) time = lastTime;
// handle multiple ids generated "simultaneously".
if (time == lastTime) {
if (sequenceCounter == 256) {
// rather than block, we'll cheat and return a UUID from the very near future.
- lastTime = time++;
+ lastTime = ++time;
sequenceCounter = 0;
} else {
sequenceCounter++;
}
} else {
lastTime = time;
sequenceCounter = 0;
}
return new java.util.UUID(time, versionAndNodeIdentifier | (sequenceCounter & 0xFF));
}
// helper functions for comparing a UUID to a time range.
public static java.util.UUID from(long time) {
return new java.util.UUID(time, versionIdentifier);
}
public static java.util.UUID until(long time) {
return new java.util.UUID(time, versionIdentifier | 0x00FFFFFFFFFFFFFFL);
}
}
| true | true | public static synchronized java.util.UUID next() {
// just pad out to microseconds for now.
long time = System.currentTimeMillis() * 1000;
// handle the clock moving backwards.
if (time < lastTime) time = lastTime;
// handle multiple ids generated "simultaneously".
if (time == lastTime) {
if (sequenceCounter == 256) {
// rather than block, we'll cheat and return a UUID from the very near future.
lastTime = time++;
sequenceCounter = 0;
} else {
sequenceCounter++;
}
} else {
lastTime = time;
sequenceCounter = 0;
}
return new java.util.UUID(time, versionAndNodeIdentifier | (sequenceCounter & 0xFF));
}
| public static synchronized java.util.UUID next() {
// just pad out to microseconds for now.
long time = System.currentTimeMillis() * 1000;
// handle the clock moving backwards.
if (time < lastTime) time = lastTime;
// handle multiple ids generated "simultaneously".
if (time == lastTime) {
if (sequenceCounter == 256) {
// rather than block, we'll cheat and return a UUID from the very near future.
lastTime = ++time;
sequenceCounter = 0;
} else {
sequenceCounter++;
}
} else {
lastTime = time;
sequenceCounter = 0;
}
return new java.util.UUID(time, versionAndNodeIdentifier | (sequenceCounter & 0xFF));
}
|
diff --git a/statcvs-xml2/src/de/berlios/statcvs/xml/chart/AbstractTimeSeriesChart.java b/statcvs-xml2/src/de/berlios/statcvs/xml/chart/AbstractTimeSeriesChart.java
index df0af32..ef9dfbf 100644
--- a/statcvs-xml2/src/de/berlios/statcvs/xml/chart/AbstractTimeSeriesChart.java
+++ b/statcvs-xml2/src/de/berlios/statcvs/xml/chart/AbstractTimeSeriesChart.java
@@ -1,191 +1,192 @@
/*
StatCvs - CVS statistics generation
Copyright (C) 2002 Lukasz Pekacki <[email protected]>
http://statcvs.sf.net/
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package de.berlios.statcvs.xml.chart;
import java.util.Date;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;
import net.sf.statcvs.model.CvsRevision;
import net.sf.statcvs.model.SymbolicName;
import org.jfree.chart.ChartFactory;
import org.jfree.chart.axis.ValueAxis;
import org.jfree.chart.plot.XYPlot;
import org.jfree.chart.renderer.XYStepRenderer;
import org.jfree.data.time.Millisecond;
import org.jfree.data.time.TimeSeries;
import org.jfree.data.time.TimeSeriesCollection;
import de.berlios.statcvs.xml.I18n;
import de.berlios.statcvs.xml.model.Grouper;
import de.berlios.statcvs.xml.output.ReportSettings;
/**
* TimeLineChart
*
* @author Tammo van Lessen
*/
public class AbstractTimeSeriesChart extends AbstractChart {
private TimeSeriesCollection tsc;
/**
* @param filename
* @param title
*/
public AbstractTimeSeriesChart(ReportSettings settings, String filename, String title,
String rangeLabel)
{
super(settings, filename, title);
tsc = new TimeSeriesCollection();
setChart(ChartFactory.createTimeSeriesChart(
settings.getProjectName(),
I18n.tr("Date"), rangeLabel,
tsc,
true,
true,
false));
//Paint[] colors = new Paint[1];
//colors[0] = Color.blue;
//getChart().getPlot().setSeriesPaint(colors);
// setup axis
XYPlot plot = getChart().getXYPlot();
ValueAxis axis = plot.getDomainAxis();
axis.setVerticalTickLabels(true);
plot.setRenderer(new XYStepRenderer());
}
protected void addSymbolicNames(Iterator it)
{
XYPlot xyplot = getChart().getXYPlot();
while (it.hasNext()) {
SymbolicName sn = (SymbolicName)it.next();
xyplot.addAnnotation(new SymbolicNameAnnotation(sn));
}
}
protected void addTimeSeries(TimeSeries series, Date firstDate, int firstValue)
{
series.add(new Millisecond(new Date(firstDate.getTime() - 1)), firstValue);
tsc.addSeries(series);
}
protected void addTimeSeries(TimeSeries series)
{
tsc.addSeries(series);
}
protected int getSeriesCount()
{
return tsc.getSeriesCount();
}
protected TimeSeries createTimeSeries(String title, Iterator it, RevisionVisitor visitor)
{
DateTimeSeries result = new DateTimeSeries(title);
while (it.hasNext()) {
CvsRevision rev = (CvsRevision)it.next();
result.add(rev.getDate(), visitor.visit(rev));
}
result.addLast();
return result;
}
protected Map createTimeSerieses(Grouper grouper, Iterator it, RevisionVisitorFactory factory)
{
Hashtable timeSeriesByGroup = new Hashtable();
Hashtable visitorByGroup = new Hashtable();
ReportSettings.Predicate predicate = getSettings().getOutputPredicate();
while (it.hasNext()) {
CvsRevision rev = (CvsRevision)it.next();
Object group = grouper.getGroup(rev);
DateTimeSeries series = (DateTimeSeries)timeSeriesByGroup.get(group);
RevisionVisitor visitor = (RevisionVisitor)visitorByGroup.get(group);
if (series == null) {
series = new DateTimeSeries(grouper.getName(group));
timeSeriesByGroup.put(group, series);
visitor = factory.create(group);
visitorByGroup.put(group, visitor);
}
+ int value = visitor.visit(rev);
if (predicate == null || predicate.matches(rev)) {
- series.add(rev.getDate(), visitor.visit(rev));
+ series.add(rev.getDate(), value);
}
}
for (Iterator it2 = timeSeriesByGroup.values().iterator(); it2.hasNext();) {
((DateTimeSeries)it2.next()).addLast();
}
return timeSeriesByGroup;
}
public boolean hasData()
{
for (Iterator it = tsc.getSeries().iterator(); it.hasNext();) {
TimeSeries series = (TimeSeries)it.next();
if (series.getItemCount() <= 1) {
return false;
}
}
return true;
}
public static class DateTimeSeries extends TimeSeries {
private int currentValue;
private Date currentDate = null;
public DateTimeSeries(String name)
{
super(name, Millisecond.class);
}
public void add(Date date, int value)
{
if (currentDate == null) {
currentDate = date;
}
else if (!date.equals(currentDate)) {
super.add(new Millisecond(currentDate), currentValue);
currentDate = date;
}
currentValue = value;
}
public void addLast()
{
if (currentDate != null) {
super.add(new Millisecond(currentDate), currentValue);
}
}
}
}
| false | true | protected Map createTimeSerieses(Grouper grouper, Iterator it, RevisionVisitorFactory factory)
{
Hashtable timeSeriesByGroup = new Hashtable();
Hashtable visitorByGroup = new Hashtable();
ReportSettings.Predicate predicate = getSettings().getOutputPredicate();
while (it.hasNext()) {
CvsRevision rev = (CvsRevision)it.next();
Object group = grouper.getGroup(rev);
DateTimeSeries series = (DateTimeSeries)timeSeriesByGroup.get(group);
RevisionVisitor visitor = (RevisionVisitor)visitorByGroup.get(group);
if (series == null) {
series = new DateTimeSeries(grouper.getName(group));
timeSeriesByGroup.put(group, series);
visitor = factory.create(group);
visitorByGroup.put(group, visitor);
}
if (predicate == null || predicate.matches(rev)) {
series.add(rev.getDate(), visitor.visit(rev));
}
}
for (Iterator it2 = timeSeriesByGroup.values().iterator(); it2.hasNext();) {
((DateTimeSeries)it2.next()).addLast();
}
return timeSeriesByGroup;
}
| protected Map createTimeSerieses(Grouper grouper, Iterator it, RevisionVisitorFactory factory)
{
Hashtable timeSeriesByGroup = new Hashtable();
Hashtable visitorByGroup = new Hashtable();
ReportSettings.Predicate predicate = getSettings().getOutputPredicate();
while (it.hasNext()) {
CvsRevision rev = (CvsRevision)it.next();
Object group = grouper.getGroup(rev);
DateTimeSeries series = (DateTimeSeries)timeSeriesByGroup.get(group);
RevisionVisitor visitor = (RevisionVisitor)visitorByGroup.get(group);
if (series == null) {
series = new DateTimeSeries(grouper.getName(group));
timeSeriesByGroup.put(group, series);
visitor = factory.create(group);
visitorByGroup.put(group, visitor);
}
int value = visitor.visit(rev);
if (predicate == null || predicate.matches(rev)) {
series.add(rev.getDate(), value);
}
}
for (Iterator it2 = timeSeriesByGroup.values().iterator(); it2.hasNext();) {
((DateTimeSeries)it2.next()).addLast();
}
return timeSeriesByGroup;
}
|
diff --git a/org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/synchronize/action/PushAction.java b/org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/synchronize/action/PushAction.java
index 7192cae0..02e24e77 100644
--- a/org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/synchronize/action/PushAction.java
+++ b/org.eclipse.egit.ui/src/org/eclipse/egit/ui/internal/synchronize/action/PushAction.java
@@ -1,96 +1,96 @@
/*******************************************************************************
* Copyright (C) 2011, Dariusz Luksza <[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.synchronize.action;
import static org.eclipse.egit.ui.internal.synchronize.GitModelSynchronizeParticipant.SYNCHRONIZATION_DATA;
import java.lang.reflect.InvocationTargetException;
import java.net.URISyntaxException;
import org.eclipse.compare.structuremergeviewer.IDiffElement;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.egit.core.synchronize.dto.GitSynchronizeData;
import org.eclipse.egit.core.synchronize.dto.GitSynchronizeDataSet;
import org.eclipse.egit.ui.Activator;
import org.eclipse.egit.ui.UIPreferences;
import org.eclipse.egit.ui.credentials.EGitCredentialsProvider;
import org.eclipse.egit.ui.internal.push.PushOperationUI;
import org.eclipse.jgit.transport.RemoteConfig;
import org.eclipse.team.ui.synchronize.ISynchronizePageConfiguration;
import org.eclipse.team.ui.synchronize.SynchronizeModelAction;
import org.eclipse.team.ui.synchronize.SynchronizeModelOperation;
/**
* Push action used in Synchronize view toolbar
*/
public class PushAction extends SynchronizeModelAction {
/**
* Construct {@link PushAction}
*
* @param text the action's text
* @param configuration the actions synchronize page configuration
*/
public PushAction(String text, ISynchronizePageConfiguration configuration) {
super(text, configuration);
}
@Override
protected SynchronizeModelOperation getSubscriberOperation(
ISynchronizePageConfiguration configuration, IDiffElement[] elements) {
final int timeout = Activator.getDefault().getPreferenceStore()
.getInt(UIPreferences.REMOTE_CONNECTION_TIMEOUT);
return new SynchronizeModelOperation(configuration, elements) {
public void run(IProgressMonitor monitor) throws InvocationTargetException,
InterruptedException {
GitSynchronizeDataSet gsds = (GitSynchronizeDataSet) getConfiguration()
.getProperty(SYNCHRONIZATION_DATA);
GitSynchronizeData gsd = gsds.iterator().next();
String remoteName = gsd.getSrcRemoteName();
if (remoteName == null)
- remoteName = gsd.getDstRemoteName();
+ return;
RemoteConfig rc;
try {
- rc = new RemoteConfig(gsd.getRepository()
- .getConfig(), gsd.getDstRemoteName());
+ rc = new RemoteConfig(gsd.getRepository().getConfig(),
+ remoteName);
PushOperationUI push = new PushOperationUI(gsd.getRepository(),
rc, timeout, false);
push.setCredentialsProvider(new EGitCredentialsProvider());
push.execute(monitor);
} catch (URISyntaxException e) {
throw new InvocationTargetException(e);
} catch (CoreException e) {
throw new InvocationTargetException(e);
}
}
};
}
@Override
public boolean isEnabled() {
GitSynchronizeDataSet gsds = (GitSynchronizeDataSet) getConfiguration()
.getProperty(SYNCHRONIZATION_DATA);
if (gsds == null || gsds.size() != 1)
return false;
GitSynchronizeData gsd = gsds.iterator().next();
String srcRemoteName = gsd.getSrcRemoteName();
String dstRemoteName = gsd.getDstRemoteName();
return srcRemoteName != dstRemoteName
&& (srcRemoteName != null || dstRemoteName != null);
}
}
| false | true | protected SynchronizeModelOperation getSubscriberOperation(
ISynchronizePageConfiguration configuration, IDiffElement[] elements) {
final int timeout = Activator.getDefault().getPreferenceStore()
.getInt(UIPreferences.REMOTE_CONNECTION_TIMEOUT);
return new SynchronizeModelOperation(configuration, elements) {
public void run(IProgressMonitor monitor) throws InvocationTargetException,
InterruptedException {
GitSynchronizeDataSet gsds = (GitSynchronizeDataSet) getConfiguration()
.getProperty(SYNCHRONIZATION_DATA);
GitSynchronizeData gsd = gsds.iterator().next();
String remoteName = gsd.getSrcRemoteName();
if (remoteName == null)
remoteName = gsd.getDstRemoteName();
RemoteConfig rc;
try {
rc = new RemoteConfig(gsd.getRepository()
.getConfig(), gsd.getDstRemoteName());
PushOperationUI push = new PushOperationUI(gsd.getRepository(),
rc, timeout, false);
push.setCredentialsProvider(new EGitCredentialsProvider());
push.execute(monitor);
} catch (URISyntaxException e) {
throw new InvocationTargetException(e);
} catch (CoreException e) {
throw new InvocationTargetException(e);
}
}
};
}
| protected SynchronizeModelOperation getSubscriberOperation(
ISynchronizePageConfiguration configuration, IDiffElement[] elements) {
final int timeout = Activator.getDefault().getPreferenceStore()
.getInt(UIPreferences.REMOTE_CONNECTION_TIMEOUT);
return new SynchronizeModelOperation(configuration, elements) {
public void run(IProgressMonitor monitor) throws InvocationTargetException,
InterruptedException {
GitSynchronizeDataSet gsds = (GitSynchronizeDataSet) getConfiguration()
.getProperty(SYNCHRONIZATION_DATA);
GitSynchronizeData gsd = gsds.iterator().next();
String remoteName = gsd.getSrcRemoteName();
if (remoteName == null)
return;
RemoteConfig rc;
try {
rc = new RemoteConfig(gsd.getRepository().getConfig(),
remoteName);
PushOperationUI push = new PushOperationUI(gsd.getRepository(),
rc, timeout, false);
push.setCredentialsProvider(new EGitCredentialsProvider());
push.execute(monitor);
} catch (URISyntaxException e) {
throw new InvocationTargetException(e);
} catch (CoreException e) {
throw new InvocationTargetException(e);
}
}
};
}
|
diff --git a/src/jar/resolver/java/org/mulgara/resolver/StringPoolSession.java b/src/jar/resolver/java/org/mulgara/resolver/StringPoolSession.java
index fd08d9bd..b6e9f86f 100644
--- a/src/jar/resolver/java/org/mulgara/resolver/StringPoolSession.java
+++ b/src/jar/resolver/java/org/mulgara/resolver/StringPoolSession.java
@@ -1,799 +1,806 @@
/*
* 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 the Kowari Metadata Store.
*
* The Initial Developer of the Original Code is Plugged In Software Pty
* Ltd (http://www.pisoftware.com, mailto:[email protected]). Portions
* created by Plugged In Software Pty Ltd are Copyright (C) 2001,2002
* Plugged In Software Pty Ltd. All Rights Reserved.
*
* Contributor(s): N/A.
*
* [NOTE: The text of this Exhibit A may differ slightly from the text
* of the notices in the Source Code files of the Original Code. You
* should use the text of this Exhibit A rather than the text found in the
* Original Code Source Code for Your Modifications.]
*
*/
package org.mulgara.resolver;
// Java 2 standard packages
import java.net.URI;
import java.net.URISyntaxException;
import java.util.*;
// Third party packages
import org.apache.log4j.Logger;
import org.jrdf.graph.*;
// Local packages
import org.mulgara.query.*;
import org.mulgara.query.rdf.*;
import org.mulgara.resolver.spi.*;
import org.mulgara.store.nodepool.NodePool;
import org.mulgara.store.nodepool.NodePoolException;
import org.mulgara.store.stringpool.SPObject;
import org.mulgara.store.stringpool.SPObjectFactory;
import org.mulgara.store.stringpool.SPURI;
import org.mulgara.store.stringpool.StringPool;
import org.mulgara.store.stringpool.StringPoolException;
import org.mulgara.store.tuples.Tuples;
import org.mulgara.store.tuples.TuplesOperations;
import org.mulgara.store.xa.SimpleXAResource;
import org.mulgara.store.xa.SimpleXAResourceException;
import org.mulgara.store.xa.XANodePool;
import org.mulgara.store.xa.XAResolverSession;
import org.mulgara.store.xa.XAStringPool;
import org.mulgara.util.LongMapper;
import org.mulgara.util.QueryParams;
import org.mulgara.util.StackTrace;
/**
* A database session.
*
* @created 2004-04-26
* @author <a href="http://staff.pisoftware.com/andrae">Andrae Muys</a>
* @version $Revision: 1.9 $
* @modified $Date: 2005/02/22 08:16:10 $ by $Author: newmana $
* @company <a href="mailto:[email protected]">Plugged In Software</a>
* @copyright ©2004 <a href="http://www.tucanatech.com/">Tucana
* Technology, Inc</a>
* @licence <a href="{@docRoot}/../../LICENCE">Mozilla Public License v1.1</a>
*/
public class StringPoolSession implements XAResolverSession, BackupRestoreSession {
/** Logger. */
private static final Logger logger =
Logger.getLogger(StringPoolSession.class.getName());
/**
* Stopgap to deal with the lack of a <q>no match</q> return value from the
* string pool.
*/
private static final long NONE = NodePool.NONE;
private static final int OBTAIN = 0;
private static final int PREPARE = 1;
private static final int COMMIT = 2;
private static final int ROLLBACK = 3;
private static final int RELEASE = 4;
static final int READ = 0;
/** Query stringpool, create node if not found */
static final int WRITE = 1;
/** Query temp stringpool then persistent, node will be created in temp stringpool if required */
static final int TEMP = 0;
/** Query only persistent stringpool, node will be created in persistent stringpool if required */
static final int PERSIST = 2;
/** Extracts RW_FLAG */
static final int WRITE_MASK = 1;
/** Extracts STORE_FLAG */
static final int STORE_MASK = 2;
/** The name of the graph parameter in a URI */
static final String GRAPH = "graph";
/** The unique {@link URI} naming this database. */
private final URI databaseURI;
/** The set of alternative hostnames for the current host. */
private final Set<String> hostnameAliases;
/** Where to store literals for this phase. */
private XAStringPool persistentStringPool;
/** The source of nodes for this phase. */
private XANodePool persistentNodePool;
/** The source of nodes which won't outlive this session. */
private final NodePool temporaryNodePool;
/** Where to store literals which won't outlive this session. */
private final StringPool temporaryStringPool;
private int state;
private SimpleXAResource[] resources;
private Object globalLock;
private Thread currentThread;
StringPoolSession(URI databaseURI,
Set<String> hostnameAliases,
XAStringPool persistentStringPool,
XANodePool persistentNodePool,
StringPool temporaryStringPool,
NodePool temporaryNodePool,
Object globalLock
) {
if (logger.isDebugEnabled()) {
logger.debug("Constructing StringPoolSession " + System.identityHashCode(this) + "\n" + new StackTrace());
}
assert databaseURI.getFragment() == null;
this.databaseURI = databaseURI;
this.hostnameAliases = hostnameAliases;
this.persistentStringPool = persistentStringPool;
this.persistentNodePool = persistentNodePool;
this.temporaryStringPool = temporaryStringPool;
this.temporaryNodePool = temporaryNodePool;
this.globalLock = globalLock;
this.state = OBTAIN;
this.currentThread = null;
this.persistentStringPool.setNodePool(this.persistentNodePool);
}
//
// Globalize/Localize methods.
//
public Node globalize(long localNode) throws GlobalizeException {
// this should not require guarding, as read-only operations will usually not be on the current phase
// any reads on the current phase are about to start failing anyway if the state changes under us
// this should not require guarding, as read-only operations will usually not be on the current phase
// any reads on the current phase are about to start failing anyway if the state changes under us
if (state == ROLLBACK || state == RELEASE) {
throw new GlobalizeException(localNode, "Attempting to globalize outside transaction.");
}
// Validate "localNode" parameter
if (localNode == NONE) {
throw new IllegalArgumentException("NONE isn't a local node");
}
// Look up the local node in the string pool
SPObject spObject;
try {
if (localNode < 0) {
spObject = temporaryStringPool.findSPObject(-localNode);
} else {
spObject = mapAbsolute(persistentStringPool.findSPObject(localNode));
}
} catch (StringPoolException e) {
throw new GlobalizeException(localNode, "String pool lookup failed", e);
}
// Generate and return the corresponding RDF node
Node node = globalizeBlankNode(localNode, spObject);
assert node != null;
// Return the RDF node
return node;
}
public long lookup(Node node) throws LocalizeException {
return localize(node, READ | TEMP);
}
public long lookupPersistent(Node node) throws LocalizeException {
return localize(node, READ | PERSIST);
}
public long localize(Node node) throws LocalizeException {
return localize(node, WRITE | TEMP);
}
public long localizePersistent(Node node) throws LocalizeException {
checkCurrentThread();
try {
return localize(node, WRITE | PERSIST);
} finally {
releaseCurrentThread();
}
}
public long newBlankNode() throws NodePoolException {
checkCurrentThread();
try {
return persistentNodePool.newNode();
} finally {
releaseCurrentThread();
}
}
public void refresh(SimpleXAResource[] resources) throws SimpleXAResourceException {
checkCurrentThread();
try {
if (logger.isDebugEnabled()) {
logger.debug("Obtaining phase on StringPoolSession " + System.identityHashCode(this));
}
this.resources = resources;
synchronized (this.globalLock) {
this.persistentStringPool.refresh(); // calls refresh on the node pool
// !!Review: Call rollback on temporary? NB. Can't rollback non XA-SP/NP.
//this.temporaryStringPool.refresh();
//this.temporaryNodePool.refresh();
for (int i = 0; i < this.resources.length; i++) {
this.resources[i].refresh();
}
}
} finally {
releaseCurrentThread();
}
}
public void prepare() throws SimpleXAResourceException {
checkCurrentThread();
try {
synchronized (globalLock) {
if (logger.isDebugEnabled()) {
logger.debug("Preparing phase on StringPoolSession " + System.identityHashCode(this) + " SP=" + System.identityHashCode(persistentStringPool));
}
if (state == PREPARE) {
return;
} else if (state != OBTAIN) {
throw new SimpleXAResourceException("Attempting to prepare phase without obtaining phase");
}
state = PREPARE;
persistentStringPool.prepare(); // calls prepare on the node pool
for (int i = 0; i < resources.length; i++) resources[i].prepare();
}
} finally {
releaseCurrentThread();
}
}
public void commit() throws SimpleXAResourceException {
checkCurrentThread();
try {
synchronized (globalLock) {
if (logger.isDebugEnabled()) {
logger.debug("Committing phase on StringPoolSession " + System.identityHashCode(this));
}
if (state == COMMIT) {
return;
} else if (state != PREPARE) {
throw new SimpleXAResourceException("Attempting to commit phase without preparing");
}
state = COMMIT;
persistentStringPool.commit(); // calls commit() on the node pool
for (int i = 0; i < resources.length; i++) resources[i].commit();
}
} finally {
releaseCurrentThread();
}
}
public void rollback() throws SimpleXAResourceException {
checkCurrentThread();
try {
synchronized (globalLock) {
if (logger.isDebugEnabled()) {
logger.debug("Rollback phase on StringPoolSession " + System.identityHashCode(this));
}
if (state == RELEASE) {
throw new SimpleXAResourceException("Attempting to rollback phase outside transaction");
}
state = ROLLBACK;
persistentStringPool.rollback(); // calls rollback on the node pool
for (int i = 0; i < resources.length; i++) resources[i].rollback();
}
} finally {
releaseCurrentThread();
}
}
public void release() throws SimpleXAResourceException {
checkCurrentThread();
try {
synchronized (globalLock) {
if (logger.isDebugEnabled()) {
logger.debug("Release phase on StringPoolSession " + System.identityHashCode(this));
}
if (state == RELEASE) {
return;
} else if (state != COMMIT && state != ROLLBACK) {
throw new SimpleXAResourceException("Attempting to release phase without commit or rollback");
}
state = RELEASE;
persistentStringPool.release(); // calls release on the node pool
// TODO determine if release() should be called for the temp components.
//temporaryStringPool.release();
//temporaryNodePool.release();
for (int i = 0; i < resources.length; i++) resources[i].release();
}
} finally {
releaseCurrentThread();
}
}
/**
* {@inheritDoc}
*/
public Tuples findStringPoolRange(
SPObject lowValue, boolean inclLowValue,
SPObject highValue, boolean inclHighValue
) throws StringPoolException {
try {
// get the nodes from both string pools
Tuples[] tuples = new Tuples[2];
tuples[0] = persistentStringPool.findGNodes(lowValue, inclLowValue, highValue, inclHighValue);
tuples[1] = temporaryStringPool.findGNodes(lowValue, inclLowValue, highValue, inclHighValue);
Tuples result = appendTuples(tuples);
tuples[0].close();
tuples[1].close();
return result;
} catch (TuplesException te) {
throw new StringPoolException(te);
}
}
/**
* {@inheritDoc}
*/
public Tuples findStringPoolType(
SPObject.TypeCategory typeCategory, URI typeURI
) throws StringPoolException {
try {
// get the nodes from both string pools
Tuples[] tuples = new Tuples[2];
tuples[0] = persistentStringPool.findGNodes(typeCategory, typeURI);
tuples[1] = temporaryStringPool.findGNodes(typeCategory, typeURI);
return appendTuples(tuples);
} catch (TuplesException te) {
throw new StringPoolException(te);
}
}
/**
* {@inheritDoc}
*/
public SPObject findStringPoolObject(long gNode) throws StringPoolException {
// Container for our SPObject
SPObject spo = null;
if (gNode >= NodePool.MIN_NODE) {
if (logger.isDebugEnabled()) {
logger.debug("!! Searching for persistent node from id: " + gNode);
}
// Check if we have a persistent Node and find it if we have
spo = mapAbsolute(persistentStringPool.findSPObject(gNode));
} else {
if (logger.isDebugEnabled()) {
logger.debug("!! Searching for temporary node from id: " + gNode);
}
// We have a temporary node so check the temporary pool (Using the
// inverted negative id)
spo = temporaryStringPool.findSPObject(-gNode);
}
return spo;
}
/**
* Retrieve the SPObject factory from the stringpool to allow for the creation
* of new SPObjects.
*
* @return The factory to allow for creation of SPObjects
*/
public SPObjectFactory getSPObjectFactory() {
return persistentStringPool.getSPObjectFactory();
}
//
// Type specific localize methods.
//
protected long localize(Node node, int flags) throws LocalizeException
{
// this should not require guarding, as read-only operations will usually not be on the current phase
// any reads on the current phase are about to start failing anyway if the state changes under us
if (state != OBTAIN) {
throw new LocalizeException(node, "Attempting to localize outside transaction (STATE = " + state + ") " + System.identityHashCode(this));
}
if (node == null) {
throw new IllegalArgumentException("Null 'node' parameter");
}
if (node instanceof BlankNode) {
return localizeBlankNode((BlankNode)node, flags);
}
SPObjectFactory spoFactory = persistentStringPool.getSPObjectFactory();
SPObject spObject;
try {
spObject = spoFactory.newSPObject(node);
} catch (RuntimeException ex) {
throw new LocalizeException(node, "Couldn't convert Node to SPObject", ex);
}
assert spObject != null;
try {
return localizeSPObject(spObject, flags);
} catch (NodePoolException e) {
throw new LocalizeException(node, "Couldn't localize node", e);
} catch (StringPoolException e) {
throw new LocalizeException(node, "Couldn't localize node", e);
}
}
protected long localizeBlankNode(BlankNode node, int flags) throws LocalizeException {
try {
// Check to see that it's a blank node impl (a Mulgara blank node)
if (node instanceof BlankNodeImpl) {
BlankNodeImpl bi = (BlankNodeImpl) node;
// If the blank node id is greater then zero return it.
// FIXME: we should be checking that the BlankNodeImpl came from the
// correct phase, otherwise it is invalid to extract the NodeId.
if (bi.getNodeId() > 0) return bi.getNodeId();
// If the blank node does not have a blank node id and we are in a read
// phase then throw an exception.
if ((bi.getNodeId() == 0) && ((flags & WRITE_MASK) == READ)) {
throw new LocalizeException(node, "Attempt to get a node ID from a non-allocated BlankNodeImpl in a read phase");
}
// If we are in a write phase.
if ((flags & WRITE_MASK) == WRITE) {
// If the blank node if less than zero (query node) and we are
// persisting.
if ((bi.getNodeId() < 0) && ((flags & STORE_MASK) == PERSIST)) {
bi.setNodeId(persistentNodePool.newNode());
} else if (bi.getNodeId() == 0) {
if ((flags & STORE_MASK) == TEMP) {
bi.setNodeId(-temporaryNodePool.newNode());
} else {
bi.setNodeId(persistentNodePool.newNode());
}
}
return bi.getNodeId();
}
// Throw an exception here if we're in a read phase and the blank node
// id is negative.
throw new LocalizeException(node, "Attempt to persist a local blank node in a read phase");
} else if ((flags & WRITE_MASK) == WRITE) {
// Some other implementation of BlankNode, so we can't access internal
// node ID and we can only create one - we must be in the WRITE phase.
return getAllocatedNodeId(node, flags);
} else {
// If it's a read phase and not the local BlankNode then throw an
// exception.
throw new LocalizeException(node, "Attempt to read BlankNode from stringpool");
}
} catch (NodePoolException e) {
throw new LocalizeException(node, "Couldn't create blank node", e);
}
}
/**
* Allocates new node IDs for unknown nodes. Stores node IDs for later lookups.
* @param bn The blank node to get the ID for.
* @param flags Indicates the type of storage for the node ids.
* @return The node ID for this given blank node.
* @throws NodePoolException An error while allocating a new node.
*/
protected long getAllocatedNodeId(BlankNode bn, int flags) throws NodePoolException {
assert !(bn instanceof BlankNodeImpl);
long nodeId;
if ((flags & STORE_MASK) == TEMP) {
nodeId = -temporaryNodePool.newNode();
} else {
nodeId = persistentNodePool.newNode();
}
return nodeId;
}
protected Node globalizeBlankNode(long localNode, SPObject spObject) throws GlobalizeException {
return (spObject == null) ? new BlankNodeImpl(localNode) : spObject.getRDFNode();
}
private long localizeSPObject(SPObject spObject, int flags) throws StringPoolException, NodePoolException {
boolean persistent = true;
SPObject relativeSPObject = mapRelative(spObject);
long localNode = persistentStringPool.findGNode(relativeSPObject);
// If not found persistently then try the temp pool if permitted.
if (localNode == NONE && ((flags & STORE_MASK) == TEMP)) {
localNode = temporaryStringPool.findGNode(spObject);
persistent = false;
}
/* The following block could cause misbehavior if someone tries to
globalize a local node which was originally transient, but was later
"promoted" to being persistent.
if (localNode == NONE && ((flags & STORE_MASK) == PERSIST)) {
localNode = temporaryStringPool.findGNode(spObject);
if (localNode != NONE) {
// The node exists in the temporary pool, but not in the persistent
// pool, and we've been directed to write it into the persistent pool.
// We can therefore remove the version in the temporary pool.
if (logger.isDebugEnabled()) {
logger.debug("Removing " + spObject + " as " + localNode + " from temeporary sp " + temporaryStringPool + " because it's about to be written persistently");
}
temporaryStringPool.remove(localNode);
localNode = NONE;
}
}
*/
// If the literal wasn't already in the string pool, create it if requested.
if (localNode == NONE) {
if ((flags & WRITE_MASK) == WRITE) {
// Node does not already exist: create node in requested pool.
if ((flags & STORE_MASK) == PERSIST) {
localNode = persistentStringPool.put(relativeSPObject); // allocates from the internal node pool
if (logger.isDebugEnabled()) {
//logger.debug("Inserted " + spObject + " as " + localNode + " into persistent sp");
}
} else {
localNode = temporaryNodePool.newNode();
temporaryStringPool.put(localNode, spObject);
if (logger.isDebugEnabled()) {
//logger.debug("Inserted " + spObject + " as " + localNode + " into temporary sp");
}
persistent = false;
}
} else {
// Node not found when expected: throw exception.
throw new StringPoolException("Unable to find literal in StringPool");
}
}
// Node was found or has been successfully created in requested pool.
assert localNode != NONE;
// logger.warn("Localized " + spObject + " as " + (persistent ? localNode : -localNode));
return persistent ? localNode : -localNode;
}
private SPObject mapAbsolute(SPObject spObject) {
if (
spObject != null &&
spObject.getTypeCategory() == SPObject.TypeCategory.URI
) {
URI uri = ((SPURI)spObject).getURI();
if (!uri.isAbsolute()) {
// Model URIs are stored as a relative URI containing only a fragment.
// Relative URIs with both a query string and a fragment are also used
// for views.
SPObjectFactory spObjectFactory =
persistentStringPool.getSPObjectFactory();
try {
// Construct an absolute URI based on the database URI.
String query = uri.getQuery();
String ssp = databaseURI.getSchemeSpecificPart();
if (query != null) ssp += '?' + query;
spObject = spObjectFactory.newSPURI(new URI(databaseURI.getScheme(), ssp, uri.getFragment()));
} catch (URISyntaxException ex) {
logger.warn(
"Cannot create absolute URI with base:\"" + databaseURI +
"\", query:\"" + uri.getQuery() + "\", fragment:\"" +
uri.getFragment() + "\"", ex
);
}
}
}
return spObject;
}
private SPObject mapRelative(SPObject spObject) {
if (
spObject != null &&
spObject.getTypeCategory() == SPObject.TypeCategory.URI
) {
URI uri = ((SPURI)spObject).getURI();
// Check if the URI is relative to the database URI.
// The user info of the uri is ignored and is stripped from the URI if it
// ends up being relativized.
String scheme = uri.getScheme();
String fragment = uri.getFragment();
- if (scheme != null && scheme.equals(databaseURI.getScheme()) && fragment != null ) {
+ if (scheme != null && scheme.equals(databaseURI.getScheme())) {
if (databaseURI.isOpaque()) {
// databaseURI is opaque.
- if (uri.isOpaque()) {
+ if (fragment != null && uri.isOpaque()) {
// Get the query string.
// We have to do it this way for opaque URIs.
String ssp = uri.getSchemeSpecificPart();
String query;
int qIndex = ssp.indexOf('?');
if (qIndex >= 0) {
query = ssp.substring(qIndex + 1);
ssp = ssp.substring(0, qIndex);
} else {
query = null;
}
if (ssp.equals(databaseURI.getSchemeSpecificPart())) {
// Construct a new relative uri with just the fragment and
// optional query string.
SPObjectFactory spObjectFactory = persistentStringPool.getSPObjectFactory();
try {
spObject = spObjectFactory.newSPURI(new URI(null, null, null, query, fragment));
} catch (URISyntaxException ex) {
logger.warn("Cannot create relative URI with fragment:\"" + fragment + "\"", ex);
}
}
}
} else {
// databaseURI is hierarchial.
String path;
String host;
if (
!uri.isOpaque() && (
uri.getSchemeSpecificPart().equals(
databaseURI.getSchemeSpecificPart()
) || (
(host = uri.getHost()) != null &&
uri.getPort() == databaseURI.getPort() &&
(path = uri.getPath()) != null &&
path.equals(databaseURI.getPath()) &&
hostnameAliases.contains(host.toLowerCase())
)
)
) {
// Construct a new relative uri with just the fragment and
// optional query string.
SPObjectFactory spObjectFactory = persistentStringPool.getSPObjectFactory();
QueryParams query = QueryParams.decode(uri);
String gName = query.get(GRAPH);
- try {
- if (gName != null) spObject = spObjectFactory.newSPURI(new URI(gName));
- else spObject = spObjectFactory.newSPURI(new URI(null, null, null, uri.getQuery(), fragment));
- } catch (URISyntaxException ex) {
- logger.warn("Cannot create relative URI with fragment:\"" + fragment + "\"", ex);
+ if (gName != null) {
+ try {
+ spObject = spObjectFactory.newSPURI(new URI(gName));
+ } catch (URISyntaxException ex) {
+ logger.warn("Cannot extract a valid URI from:\"" + gName + "\"", ex);
+ }
+ } else if (fragment != null) {
+ try {
+ spObject = spObjectFactory.newSPURI(new URI(null, null, null, uri.getQuery(), fragment));
+ } catch (URISyntaxException ex) {
+ logger.warn("Cannot create relative URI with fragment:\"" + fragment + "\"", ex);
+ }
}
}
}
}
}
return spObject;
}
/**
* Internal helper method to append tuples.
*
* @param tuples Array of tuples to be unioned. Each element will be closed.
* @return A single tuples containing the contents of each of the elements in the tuples array.
* @throws TuplesException Internal exception while manipulating tuples.
*/
private Tuples appendTuples(Tuples[] tuples) throws TuplesException {
assert tuples[0] != null && tuples[1] != null;
// TODO: check to make sure these have the same variable names
int t;
if (logger.isDebugEnabled()) {
for (t = 0; t < tuples.length; t++) {
logger.debug("concatenating " + tuples[t].getRowCount() + " stringpool objects");
}
}
// sort each tuples object
Tuples[] st = new Tuples[tuples.length];
for (t = 0; t < tuples.length; t++) {
st[t] = TuplesOperations.sort(tuples[t]);
// close the original tuples
tuples[t].close();
}
// union the sorted tuples
Tuples result = TuplesOperations.append(Arrays.asList(st));
// close the sorted tuples
for (t = 0; t < st.length; t++) {
st[t].close();
}
return result;
}
/**
* {@inheritDoc}
*
* NB: This method does not perform any absolute/relative URI mapping.
*/
public SPObject findSPObject(long gNode) throws StringPoolException {
if (gNode < NodePool.MIN_NODE) {
throw new IllegalArgumentException("Attempt to resolve temporary gNode in BackupRestoreSession");
}
return persistentStringPool.findSPObject(gNode);
}
public long findGNode(SPObject spObject) throws StringPoolException {
return persistentStringPool.findGNode(spObject, persistentNodePool);
}
/** @see org.mulgara.resolver.spi.BackupRestoreSession#getRestoreMapper() */
public LongMapper getRestoreMapper() throws Exception {
return persistentNodePool.getNodeMapper();
}
/**
* Used purely as a sanity check in the hope that we might catch concurrency bugs in higher layers should
* they exist.
*/
private void checkCurrentThread() {
synchronized(this) {
if (currentThread == null || currentThread.equals(Thread.currentThread())) {
currentThread = Thread.currentThread();
} else {
logger.warn("Concurrent Access of StringPoolSession Attempted");
throw new IllegalStateException("Concurrent Access of StringPoolSession Attempted");
}
}
}
private void releaseCurrentThread() {
synchronized(this) {
currentThread = null;
}
}
}
| false | true | private SPObject mapRelative(SPObject spObject) {
if (
spObject != null &&
spObject.getTypeCategory() == SPObject.TypeCategory.URI
) {
URI uri = ((SPURI)spObject).getURI();
// Check if the URI is relative to the database URI.
// The user info of the uri is ignored and is stripped from the URI if it
// ends up being relativized.
String scheme = uri.getScheme();
String fragment = uri.getFragment();
if (scheme != null && scheme.equals(databaseURI.getScheme()) && fragment != null ) {
if (databaseURI.isOpaque()) {
// databaseURI is opaque.
if (uri.isOpaque()) {
// Get the query string.
// We have to do it this way for opaque URIs.
String ssp = uri.getSchemeSpecificPart();
String query;
int qIndex = ssp.indexOf('?');
if (qIndex >= 0) {
query = ssp.substring(qIndex + 1);
ssp = ssp.substring(0, qIndex);
} else {
query = null;
}
if (ssp.equals(databaseURI.getSchemeSpecificPart())) {
// Construct a new relative uri with just the fragment and
// optional query string.
SPObjectFactory spObjectFactory = persistentStringPool.getSPObjectFactory();
try {
spObject = spObjectFactory.newSPURI(new URI(null, null, null, query, fragment));
} catch (URISyntaxException ex) {
logger.warn("Cannot create relative URI with fragment:\"" + fragment + "\"", ex);
}
}
}
} else {
// databaseURI is hierarchial.
String path;
String host;
if (
!uri.isOpaque() && (
uri.getSchemeSpecificPart().equals(
databaseURI.getSchemeSpecificPart()
) || (
(host = uri.getHost()) != null &&
uri.getPort() == databaseURI.getPort() &&
(path = uri.getPath()) != null &&
path.equals(databaseURI.getPath()) &&
hostnameAliases.contains(host.toLowerCase())
)
)
) {
// Construct a new relative uri with just the fragment and
// optional query string.
SPObjectFactory spObjectFactory = persistentStringPool.getSPObjectFactory();
QueryParams query = QueryParams.decode(uri);
String gName = query.get(GRAPH);
try {
if (gName != null) spObject = spObjectFactory.newSPURI(new URI(gName));
else spObject = spObjectFactory.newSPURI(new URI(null, null, null, uri.getQuery(), fragment));
} catch (URISyntaxException ex) {
logger.warn("Cannot create relative URI with fragment:\"" + fragment + "\"", ex);
}
}
}
}
}
return spObject;
}
| private SPObject mapRelative(SPObject spObject) {
if (
spObject != null &&
spObject.getTypeCategory() == SPObject.TypeCategory.URI
) {
URI uri = ((SPURI)spObject).getURI();
// Check if the URI is relative to the database URI.
// The user info of the uri is ignored and is stripped from the URI if it
// ends up being relativized.
String scheme = uri.getScheme();
String fragment = uri.getFragment();
if (scheme != null && scheme.equals(databaseURI.getScheme())) {
if (databaseURI.isOpaque()) {
// databaseURI is opaque.
if (fragment != null && uri.isOpaque()) {
// Get the query string.
// We have to do it this way for opaque URIs.
String ssp = uri.getSchemeSpecificPart();
String query;
int qIndex = ssp.indexOf('?');
if (qIndex >= 0) {
query = ssp.substring(qIndex + 1);
ssp = ssp.substring(0, qIndex);
} else {
query = null;
}
if (ssp.equals(databaseURI.getSchemeSpecificPart())) {
// Construct a new relative uri with just the fragment and
// optional query string.
SPObjectFactory spObjectFactory = persistentStringPool.getSPObjectFactory();
try {
spObject = spObjectFactory.newSPURI(new URI(null, null, null, query, fragment));
} catch (URISyntaxException ex) {
logger.warn("Cannot create relative URI with fragment:\"" + fragment + "\"", ex);
}
}
}
} else {
// databaseURI is hierarchial.
String path;
String host;
if (
!uri.isOpaque() && (
uri.getSchemeSpecificPart().equals(
databaseURI.getSchemeSpecificPart()
) || (
(host = uri.getHost()) != null &&
uri.getPort() == databaseURI.getPort() &&
(path = uri.getPath()) != null &&
path.equals(databaseURI.getPath()) &&
hostnameAliases.contains(host.toLowerCase())
)
)
) {
// Construct a new relative uri with just the fragment and
// optional query string.
SPObjectFactory spObjectFactory = persistentStringPool.getSPObjectFactory();
QueryParams query = QueryParams.decode(uri);
String gName = query.get(GRAPH);
if (gName != null) {
try {
spObject = spObjectFactory.newSPURI(new URI(gName));
} catch (URISyntaxException ex) {
logger.warn("Cannot extract a valid URI from:\"" + gName + "\"", ex);
}
} else if (fragment != null) {
try {
spObject = spObjectFactory.newSPURI(new URI(null, null, null, uri.getQuery(), fragment));
} catch (URISyntaxException ex) {
logger.warn("Cannot create relative URI with fragment:\"" + fragment + "\"", ex);
}
}
}
}
}
}
return spObject;
}
|
diff --git a/hopper/src/main/java/org/atomhopper/abdera/WorkspaceHandler.java b/hopper/src/main/java/org/atomhopper/abdera/WorkspaceHandler.java
index be4622c4..a42437e5 100644
--- a/hopper/src/main/java/org/atomhopper/abdera/WorkspaceHandler.java
+++ b/hopper/src/main/java/org/atomhopper/abdera/WorkspaceHandler.java
@@ -1,73 +1,73 @@
package org.atomhopper.abdera;
import org.apache.abdera.model.Workspace;
import org.apache.abdera.parser.stax.FOMWorkspace;
import org.apache.abdera.protocol.server.CollectionInfo;
import org.apache.abdera.protocol.server.RequestContext;
import org.apache.abdera.protocol.server.WorkspaceInfo;
import org.apache.commons.lang.StringUtils;
import org.atomhopper.config.v1_0.WorkspaceConfiguration;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
public class WorkspaceHandler implements WorkspaceInfo {
private final Map<String, TargetAwareAbstractCollectionAdapter> collectionAdapterMap;
private final WorkspaceConfiguration myConfig;
public WorkspaceHandler(WorkspaceConfiguration myConfig) {
this.myConfig = myConfig;
this.collectionAdapterMap = new HashMap<String, TargetAwareAbstractCollectionAdapter>();
}
public void addCollectionAdapter(String collectionId, TargetAwareAbstractCollectionAdapter adapter) {
collectionAdapterMap.put(collectionId, adapter);
}
public TargetAwareAbstractCollectionAdapter getAnsweringAdapter(RequestContext rc) {
final String feedSpec = rc.getTarget().getParameter(TargetResolverField.FEED.toString());
TargetAwareAbstractCollectionAdapter collectionAdapter = null;
if(!StringUtils.isBlank(feedSpec)) {
final String adapterKey = new StringBuilder().append("/")
.append(rc.getTarget().getParameter(TargetResolverField.WORKSPACE.toString()))
.append("/")
.append(feedSpec).toString();
- if(false) {
+ if(myConfig.isEnableRegexFeeds()) {
Set<Entry<String, TargetAwareAbstractCollectionAdapter>> adapterEntries = collectionAdapterMap.entrySet();
for(Entry<String, TargetAwareAbstractCollectionAdapter> adapterEntry : adapterEntries) {
if(adapterKey.matches(adapterEntry.getKey())) {
collectionAdapter = adapterEntry.getValue();
break;
}
}
}
else{
collectionAdapter = collectionAdapterMap.get(adapterKey);
}
}
return collectionAdapter;
}
@Override
public Workspace asWorkspaceElement(RequestContext rc) {
return new FOMWorkspace(myConfig.getTitle());
}
@Override
public Collection<CollectionInfo> getCollections(RequestContext rc) {
return (Collection) Collections.unmodifiableCollection(collectionAdapterMap.values());
}
@Override
public String getTitle(RequestContext rc) {
return myConfig.getTitle();
}
}
| true | true | public TargetAwareAbstractCollectionAdapter getAnsweringAdapter(RequestContext rc) {
final String feedSpec = rc.getTarget().getParameter(TargetResolverField.FEED.toString());
TargetAwareAbstractCollectionAdapter collectionAdapter = null;
if(!StringUtils.isBlank(feedSpec)) {
final String adapterKey = new StringBuilder().append("/")
.append(rc.getTarget().getParameter(TargetResolverField.WORKSPACE.toString()))
.append("/")
.append(feedSpec).toString();
if(false) {
Set<Entry<String, TargetAwareAbstractCollectionAdapter>> adapterEntries = collectionAdapterMap.entrySet();
for(Entry<String, TargetAwareAbstractCollectionAdapter> adapterEntry : adapterEntries) {
if(adapterKey.matches(adapterEntry.getKey())) {
collectionAdapter = adapterEntry.getValue();
break;
}
}
}
else{
collectionAdapter = collectionAdapterMap.get(adapterKey);
}
}
return collectionAdapter;
}
| public TargetAwareAbstractCollectionAdapter getAnsweringAdapter(RequestContext rc) {
final String feedSpec = rc.getTarget().getParameter(TargetResolverField.FEED.toString());
TargetAwareAbstractCollectionAdapter collectionAdapter = null;
if(!StringUtils.isBlank(feedSpec)) {
final String adapterKey = new StringBuilder().append("/")
.append(rc.getTarget().getParameter(TargetResolverField.WORKSPACE.toString()))
.append("/")
.append(feedSpec).toString();
if(myConfig.isEnableRegexFeeds()) {
Set<Entry<String, TargetAwareAbstractCollectionAdapter>> adapterEntries = collectionAdapterMap.entrySet();
for(Entry<String, TargetAwareAbstractCollectionAdapter> adapterEntry : adapterEntries) {
if(adapterKey.matches(adapterEntry.getKey())) {
collectionAdapter = adapterEntry.getValue();
break;
}
}
}
else{
collectionAdapter = collectionAdapterMap.get(adapterKey);
}
}
return collectionAdapter;
}
|
diff --git a/amibe/src/org/jcae/mesh/amibe/algos3d/AbstractAlgoHalfEdge.java b/amibe/src/org/jcae/mesh/amibe/algos3d/AbstractAlgoHalfEdge.java
index d0960935..e4bc4457 100644
--- a/amibe/src/org/jcae/mesh/amibe/algos3d/AbstractAlgoHalfEdge.java
+++ b/amibe/src/org/jcae/mesh/amibe/algos3d/AbstractAlgoHalfEdge.java
@@ -1,315 +1,315 @@
/* jCAE stand for Java Computer Aided Engineering. Features are : Small CAD
modeler, Finite element mesher, Plugin architecture.
Copyright (C) 2006 by EADS CRC
Copyright (C) 2007 by EADS France
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public
License along with this library; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package org.jcae.mesh.amibe.algos3d;
import org.jcae.mesh.amibe.ds.Mesh;
import org.jcae.mesh.amibe.ds.HalfEdge;
import org.jcae.mesh.amibe.ds.Triangle;
import org.jcae.mesh.amibe.ds.AbstractHalfEdge;
import org.jcae.mesh.amibe.ds.Vertex;
import org.jcae.mesh.amibe.util.QSortedTree;
import org.jcae.mesh.amibe.util.PAVLSortedTree;
import java.util.Stack;
import java.util.Map;
import java.util.Iterator;
import java.io.ObjectOutputStream;
import java.io.FileOutputStream;
import java.io.ObjectInputStream;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import org.apache.log4j.Logger;
public abstract class AbstractAlgoHalfEdge
{
protected Mesh mesh;
protected int nrFinal = 0;
protected int nrTriangles = 0;
protected double tolerance = 0.0;
protected int processed = 0;
protected int swapped = 0;
protected int notProcessed = 0;
protected int notInTree = 0;
protected QSortedTree tree = new PAVLSortedTree();
protected abstract void preProcessAllHalfEdges();
protected abstract void postProcessAllHalfEdges();
protected abstract boolean canProcessEdge(HalfEdge e);
protected abstract HalfEdge processEdge(HalfEdge e);
protected abstract double cost(HalfEdge e);
protected abstract Logger thisLogger();
private static final String dumpFile = "/tmp/jcae.dump";
public AbstractAlgoHalfEdge(Mesh m, Map options)
{
mesh = m;
}
public void compute()
{
thisLogger().info("Run "+getClass().getName());
preProcessAllHalfEdges();
thisLogger().info("Compute initial tree");
computeTree();
postComputeTree();
thisLogger().info("Initial number of triangles: "+countInnerTriangles(mesh));
processAllHalfEdges();
thisLogger().info("Final number of triangles: "+countInnerTriangles(mesh));
}
public static int countInnerTriangles(Mesh mesh)
{
int ret = 0;
for (Iterator itf = mesh.getTriangles().iterator(); itf.hasNext(); )
{
Triangle f = (Triangle) itf.next();
if (!isSkippedTriangle(f))
ret++;
}
return ret;
}
private void computeTree()
{
// Compute edge cost
nrTriangles = 0;
for (Iterator itf = mesh.getTriangles().iterator(); itf.hasNext(); )
{
Triangle f = (Triangle) itf.next();
if (isSkippedTriangle(f))
continue;
nrTriangles++;
HalfEdge e = (HalfEdge) f.getAbstractHalfEdge();
for (int i = 0; i < 3; i++)
{
e = (HalfEdge) e.next();
if (tree.contains(e.notOriented()))
continue;
addToTree(e);
}
}
}
/**
* Tells whether to skip outer triangle or non-writable triangle.
* @param f triangle to test.
* @return <code>true</code> if this triangle has to be skipped,
* <code>false</code> otherwise.
*/
protected static boolean isSkippedTriangle(Triangle f)
{
return f.isOuter() || !f.isWritable();
}
protected void postComputeTree()
{
}
// This routine is needed by DecimateHalfedge.
protected void preProcessEdge()
{
}
protected void addToTree(HalfEdge e)
{
if (!e.origin().isReadable() || !e.destination().isReadable())
return;
double val = cost(e);
// If an edge will not be processed because of its cost, it is
// better to not put it in the tree. One drawback though is
// that tree.size() is not equal to the total number of edges,
// and output displayed by postProcessAllHalfEdges() may thus
// not be very useful.
if (nrFinal != 0 || val <= tolerance)
tree.insert(e.notOriented(), val);
}
private boolean processAllHalfEdges()
{
boolean noSwap = false;
Stack stackNotProcessed = new Stack();
double cost = -1.0;
while (!tree.isEmpty() && nrTriangles > nrFinal)
{
preProcessEdge();
HalfEdge current = null;
Iterator itt = tree.iterator();
if ((processed % 10000) == 0)
- thisLogger().info("Edges processed: "+processed+" "+tree.size()+" "+notProcessed);
+ thisLogger().info("Edges processed: "+processed);
while (itt.hasNext())
{
QSortedTree.Node q = (QSortedTree.Node) itt.next();
current = (HalfEdge) q.getData();
cost = q.getValue();
if (nrFinal == 0 && cost > tolerance)
break;
if (canProcessEdge(current))
break;
if (thisLogger().isDebugEnabled())
thisLogger().debug("Edge not processed: "+current);
notProcessed++;
// Add a penalty to edges which could not have been
// processed. This has to be done outside this loop,
// because PAVLSortedTree instances must not be modified
// when walked through.
if (nrFinal == 0)
{
stackNotProcessed.push(current);
if (tolerance > 0.0)
stackNotProcessed.push(new Double(cost+0.7*(tolerance - cost)));
else
// tolerance = cost = 0
stackNotProcessed.push(new Double(1.0));
}
else
{
stackNotProcessed.push(current);
double penalty = tree.getRootValue()*0.7;
if (penalty == 0.0)
penalty = 1.0;
stackNotProcessed.push(new Double(cost+penalty));
}
current = null;
}
if ((nrFinal == 0 && cost > tolerance) || current == null)
break;
// Update costs for edges which were not contracted
while (stackNotProcessed.size() > 0)
{
double newCost = ((Double) stackNotProcessed.pop()).doubleValue();
HalfEdge f = (HalfEdge) stackNotProcessed.pop();
assert f == f.notOriented();
tree.update(f, newCost);
}
current = processEdge(current);
processed++;
if (noSwap)
continue;
if (current.hasAttributes(AbstractHalfEdge.OUTER | AbstractHalfEdge.BOUNDARY | AbstractHalfEdge.NONMANIFOLD))
continue;
// Check if edges can be swapped
Vertex o = current.origin();
while(true)
{
if (current.checkSwap3D(0.95) >= 0.0)
{
// Swap edge
for (int i = 0; i < 3; i++)
{
current = (HalfEdge) current.next();
if (!tree.remove(current.notOriented()))
notInTree++;
assert !tree.contains(current.notOriented());
}
HalfEdge sym = (HalfEdge) current.sym();
for (int i = 0; i < 2; i++)
{
sym = (HalfEdge) sym.next();
if (!tree.remove(sym.notOriented()))
notInTree++;
assert !tree.contains(sym.notOriented());
}
Vertex a = current.apex();
current = (HalfEdge) current.swap();
swapped++;
// Now current = (ona)
assert a == current.apex();
for (int i = 0; i < 3; i++)
{
current = (HalfEdge) current.next();
addToTree(current);
}
sym = (HalfEdge) ((HalfEdge) current.next()).sym();
for (int i = 0; i < 2; i++)
{
sym = (HalfEdge) sym.next();
addToTree(sym);
}
}
else
{
current = current.nextApexLoop();
if (current.origin() == o)
break;
}
}
}
postProcessAllHalfEdges();
return processed > 0;
}
protected final void dumpState()
{
ObjectOutputStream out = null;
try
{
out = new ObjectOutputStream(new FileOutputStream(dumpFile));
out.writeObject(mesh);
out.writeObject(tree);
appendDumpState(out);
out.close();
}
catch (Exception ex)
{
ex.printStackTrace();
System.exit(-1);
}
}
protected void appendDumpState(ObjectOutputStream out)
throws IOException
{
}
protected final boolean restoreState()
{
try
{
FileInputStream istream = new FileInputStream(dumpFile);
ObjectInputStream q = new ObjectInputStream(istream);
System.out.println("Loading restored state");
mesh = (Mesh) q.readObject();
tree = (QSortedTree) q.readObject();
appendRestoreState(q);
System.out.println("... Done.");
q.close();
assert mesh.isValid();
}
catch (FileNotFoundException ex)
{
return false;
}
catch (Exception ex)
{
ex.printStackTrace();
System.exit(-1);
}
return true;
}
protected void appendRestoreState(ObjectInputStream q)
throws IOException
{
}
}
| true | true | private boolean processAllHalfEdges()
{
boolean noSwap = false;
Stack stackNotProcessed = new Stack();
double cost = -1.0;
while (!tree.isEmpty() && nrTriangles > nrFinal)
{
preProcessEdge();
HalfEdge current = null;
Iterator itt = tree.iterator();
if ((processed % 10000) == 0)
thisLogger().info("Edges processed: "+processed+" "+tree.size()+" "+notProcessed);
while (itt.hasNext())
{
QSortedTree.Node q = (QSortedTree.Node) itt.next();
current = (HalfEdge) q.getData();
cost = q.getValue();
if (nrFinal == 0 && cost > tolerance)
break;
if (canProcessEdge(current))
break;
if (thisLogger().isDebugEnabled())
thisLogger().debug("Edge not processed: "+current);
notProcessed++;
// Add a penalty to edges which could not have been
// processed. This has to be done outside this loop,
// because PAVLSortedTree instances must not be modified
// when walked through.
if (nrFinal == 0)
{
stackNotProcessed.push(current);
if (tolerance > 0.0)
stackNotProcessed.push(new Double(cost+0.7*(tolerance - cost)));
else
// tolerance = cost = 0
stackNotProcessed.push(new Double(1.0));
}
else
{
stackNotProcessed.push(current);
double penalty = tree.getRootValue()*0.7;
if (penalty == 0.0)
penalty = 1.0;
stackNotProcessed.push(new Double(cost+penalty));
}
current = null;
}
if ((nrFinal == 0 && cost > tolerance) || current == null)
break;
// Update costs for edges which were not contracted
while (stackNotProcessed.size() > 0)
{
double newCost = ((Double) stackNotProcessed.pop()).doubleValue();
HalfEdge f = (HalfEdge) stackNotProcessed.pop();
assert f == f.notOriented();
tree.update(f, newCost);
}
current = processEdge(current);
processed++;
if (noSwap)
continue;
if (current.hasAttributes(AbstractHalfEdge.OUTER | AbstractHalfEdge.BOUNDARY | AbstractHalfEdge.NONMANIFOLD))
continue;
// Check if edges can be swapped
Vertex o = current.origin();
while(true)
{
if (current.checkSwap3D(0.95) >= 0.0)
{
// Swap edge
for (int i = 0; i < 3; i++)
{
current = (HalfEdge) current.next();
if (!tree.remove(current.notOriented()))
notInTree++;
assert !tree.contains(current.notOriented());
}
HalfEdge sym = (HalfEdge) current.sym();
for (int i = 0; i < 2; i++)
{
sym = (HalfEdge) sym.next();
if (!tree.remove(sym.notOriented()))
notInTree++;
assert !tree.contains(sym.notOriented());
}
Vertex a = current.apex();
current = (HalfEdge) current.swap();
swapped++;
// Now current = (ona)
assert a == current.apex();
for (int i = 0; i < 3; i++)
{
current = (HalfEdge) current.next();
addToTree(current);
}
sym = (HalfEdge) ((HalfEdge) current.next()).sym();
for (int i = 0; i < 2; i++)
{
sym = (HalfEdge) sym.next();
addToTree(sym);
}
}
else
{
current = current.nextApexLoop();
if (current.origin() == o)
break;
}
}
}
postProcessAllHalfEdges();
return processed > 0;
}
| private boolean processAllHalfEdges()
{
boolean noSwap = false;
Stack stackNotProcessed = new Stack();
double cost = -1.0;
while (!tree.isEmpty() && nrTriangles > nrFinal)
{
preProcessEdge();
HalfEdge current = null;
Iterator itt = tree.iterator();
if ((processed % 10000) == 0)
thisLogger().info("Edges processed: "+processed);
while (itt.hasNext())
{
QSortedTree.Node q = (QSortedTree.Node) itt.next();
current = (HalfEdge) q.getData();
cost = q.getValue();
if (nrFinal == 0 && cost > tolerance)
break;
if (canProcessEdge(current))
break;
if (thisLogger().isDebugEnabled())
thisLogger().debug("Edge not processed: "+current);
notProcessed++;
// Add a penalty to edges which could not have been
// processed. This has to be done outside this loop,
// because PAVLSortedTree instances must not be modified
// when walked through.
if (nrFinal == 0)
{
stackNotProcessed.push(current);
if (tolerance > 0.0)
stackNotProcessed.push(new Double(cost+0.7*(tolerance - cost)));
else
// tolerance = cost = 0
stackNotProcessed.push(new Double(1.0));
}
else
{
stackNotProcessed.push(current);
double penalty = tree.getRootValue()*0.7;
if (penalty == 0.0)
penalty = 1.0;
stackNotProcessed.push(new Double(cost+penalty));
}
current = null;
}
if ((nrFinal == 0 && cost > tolerance) || current == null)
break;
// Update costs for edges which were not contracted
while (stackNotProcessed.size() > 0)
{
double newCost = ((Double) stackNotProcessed.pop()).doubleValue();
HalfEdge f = (HalfEdge) stackNotProcessed.pop();
assert f == f.notOriented();
tree.update(f, newCost);
}
current = processEdge(current);
processed++;
if (noSwap)
continue;
if (current.hasAttributes(AbstractHalfEdge.OUTER | AbstractHalfEdge.BOUNDARY | AbstractHalfEdge.NONMANIFOLD))
continue;
// Check if edges can be swapped
Vertex o = current.origin();
while(true)
{
if (current.checkSwap3D(0.95) >= 0.0)
{
// Swap edge
for (int i = 0; i < 3; i++)
{
current = (HalfEdge) current.next();
if (!tree.remove(current.notOriented()))
notInTree++;
assert !tree.contains(current.notOriented());
}
HalfEdge sym = (HalfEdge) current.sym();
for (int i = 0; i < 2; i++)
{
sym = (HalfEdge) sym.next();
if (!tree.remove(sym.notOriented()))
notInTree++;
assert !tree.contains(sym.notOriented());
}
Vertex a = current.apex();
current = (HalfEdge) current.swap();
swapped++;
// Now current = (ona)
assert a == current.apex();
for (int i = 0; i < 3; i++)
{
current = (HalfEdge) current.next();
addToTree(current);
}
sym = (HalfEdge) ((HalfEdge) current.next()).sym();
for (int i = 0; i < 2; i++)
{
sym = (HalfEdge) sym.next();
addToTree(sym);
}
}
else
{
current = current.nextApexLoop();
if (current.origin() == o)
break;
}
}
}
postProcessAllHalfEdges();
return processed > 0;
}
|
diff --git a/giraph-core/src/main/java/org/apache/giraph/utils/InternalVertexRunner.java b/giraph-core/src/main/java/org/apache/giraph/utils/InternalVertexRunner.java
index 7989483..7e0b955 100644
--- a/giraph-core/src/main/java/org/apache/giraph/utils/InternalVertexRunner.java
+++ b/giraph-core/src/main/java/org/apache/giraph/utils/InternalVertexRunner.java
@@ -1,250 +1,250 @@
/*
* 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.giraph.utils;
import org.apache.giraph.conf.GiraphClasses;
import org.apache.giraph.conf.GiraphConfiguration;
import org.apache.giraph.conf.GiraphConstants;
import org.apache.giraph.job.GiraphJob;
import org.apache.giraph.io.formats.GiraphFileInputFormat;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.zookeeper.server.ServerConfig;
import org.apache.zookeeper.server.ZooKeeperServerMain;
import org.apache.zookeeper.server.quorum.QuorumPeerConfig;
import com.google.common.base.Charsets;
import com.google.common.collect.ImmutableList;
import com.google.common.io.Files;
import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
/**
* A base class for running internal tests on a vertex
*
* Extending classes only have to invoke the run() method to test their vertex.
* All data is written to a local tmp directory that is removed afterwards.
* A local zookeeper instance is started in an extra thread and
* shutdown at the end.
*
* Heavily inspired from Apache Mahout's MahoutTestCase
*/
@SuppressWarnings("unchecked")
public class InternalVertexRunner {
/** ZooKeeper port to use for tests */
public static final int LOCAL_ZOOKEEPER_PORT = 22182;
/** Don't construct */
private InternalVertexRunner() { }
/**
* Attempts to run the vertex internally in the current JVM, reading from and
* writing to a temporary folder on local disk. Will start its own zookeeper
* instance.
*
* @param classes GiraphClasses specifying which types to use
* @param params a map of parameters to add to the hadoop configuration
* @param vertexInputData linewise vertex input data
* @return linewise output data
* @throws Exception if anything goes wrong
*/
public static Iterable<String> run(
GiraphClasses classes,
Map<String, String> params,
String[] vertexInputData) throws Exception {
return run(classes, params, vertexInputData, null);
}
/**
* Attempts to run the vertex internally in the current JVM, reading from and
* writing to a temporary folder on local disk. Will start its own zookeeper
* instance.
*
* @param classes GiraphClasses specifying which types to use
* @param params a map of parameters to add to the hadoop configuration
* @param vertexInputData linewise vertex input data
* @param edgeInputData linewise edge input data
* @return linewise output data
* @throws Exception if anything goes wrong
*/
public static Iterable<String> run(
GiraphClasses classes,
Map<String, String> params,
String[] vertexInputData,
String[] edgeInputData) throws Exception {
File tmpDir = null;
try {
// Prepare input file, output folder and temporary folders
tmpDir = FileUtils.createTestDir(classes.getVertexClass());
File vertexInputFile = null;
File edgeInputFile = null;
if (classes.hasVertexInputFormat()) {
vertexInputFile = FileUtils.createTempFile(tmpDir, "vertices.txt");
}
if (classes.hasEdgeInputFormat()) {
edgeInputFile = FileUtils.createTempFile(tmpDir, "edges.txt");
}
File outputDir = FileUtils.createTempDir(tmpDir, "output");
File zkDir = FileUtils.createTempDir(tmpDir, "_bspZooKeeper");
File zkMgrDir = FileUtils.createTempDir(tmpDir, "_defaultZkManagerDir");
File checkpointsDir = FileUtils.createTempDir(tmpDir, "_checkpoints");
// Write input data to disk
if (classes.hasVertexInputFormat()) {
FileUtils.writeLines(vertexInputFile, vertexInputData);
}
if (classes.hasEdgeInputFormat()) {
FileUtils.writeLines(edgeInputFile, edgeInputData);
}
// Create and configure the job to run the vertex
GiraphJob job = new GiraphJob(classes.getVertexClass().getName());
GiraphConfiguration conf = job.getConfiguration();
conf.setVertexClass(classes.getVertexClass());
conf.setVertexEdgesClass(classes.getVertexEdgesClass());
if (classes.hasVertexInputFormat()) {
conf.setVertexInputFormatClass(classes.getVertexInputFormatClass());
}
if (classes.hasEdgeInputFormat()) {
conf.setEdgeInputFormatClass(classes.getEdgeInputFormatClass());
}
if (classes.hasVertexOutputFormat()) {
conf.setVertexOutputFormatClass(classes.getVertexOutputFormatClass());
}
if (classes.hasWorkerContextClass()) {
conf.setWorkerContextClass(classes.getWorkerContextClass());
}
if (classes.hasPartitionContextClass()) {
- conf.setMasterComputeClass(classes.getPartitionContextClass());
+ conf.setPartitionContextClass(classes.getPartitionContextClass());
}
if (classes.hasCombinerClass()) {
conf.setVertexCombinerClass(classes.getCombinerClass());
}
if (classes.hasMasterComputeClass()) {
conf.setMasterComputeClass(classes.getMasterComputeClass());
}
conf.setWorkerConfiguration(1, 1, 100.0f);
conf.setBoolean(GiraphConstants.SPLIT_MASTER_WORKER, false);
conf.setBoolean(GiraphConstants.LOCAL_TEST_MODE, true);
conf.set(GiraphConstants.ZOOKEEPER_LIST, "localhost:" +
String.valueOf(LOCAL_ZOOKEEPER_PORT));
conf.set(GiraphConstants.ZOOKEEPER_DIR, zkDir.toString());
conf.set(GiraphConstants.ZOOKEEPER_MANAGER_DIRECTORY,
zkMgrDir.toString());
conf.set(GiraphConstants.CHECKPOINT_DIRECTORY, checkpointsDir.toString());
for (Map.Entry<String, String> param : params.entrySet()) {
conf.set(param.getKey(), param.getValue());
}
Job internalJob = job.getInternalJob();
if (classes.hasVertexInputFormat()) {
GiraphFileInputFormat.addVertexInputPath(internalJob.getConfiguration(),
new Path(vertexInputFile.toString()));
}
if (classes.hasEdgeInputFormat()) {
GiraphFileInputFormat.addEdgeInputPath(internalJob.getConfiguration(),
new Path(edgeInputFile.toString()));
}
FileOutputFormat.setOutputPath(job.getInternalJob(),
new Path(outputDir.toString()));
// Configure a local zookeeper instance
Properties zkProperties = configLocalZooKeeper(zkDir);
QuorumPeerConfig qpConfig = new QuorumPeerConfig();
qpConfig.parseProperties(zkProperties);
// Create and run the zookeeper instance
final InternalZooKeeper zookeeper = new InternalZooKeeper();
final ServerConfig zkConfig = new ServerConfig();
zkConfig.readFrom(qpConfig);
ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.execute(new Runnable() {
@Override
public void run() {
try {
zookeeper.runFromConfig(zkConfig);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
});
try {
job.run(true);
} finally {
executorService.shutdown();
zookeeper.end();
}
if (classes.hasVertexOutputFormat()) {
return Files.readLines(new File(outputDir, "part-m-00000"),
Charsets.UTF_8);
} else {
return ImmutableList.of();
}
} finally {
FileUtils.delete(tmpDir);
}
}
/**
* Configuration options for running local ZK.
*
* @param zkDir directory for ZK to hold files in.
* @return Properties configured for local ZK.
*/
private static Properties configLocalZooKeeper(File zkDir) {
Properties zkProperties = new Properties();
zkProperties.setProperty("tickTime", "2000");
zkProperties.setProperty("dataDir", zkDir.getAbsolutePath());
zkProperties.setProperty("clientPort",
String.valueOf(LOCAL_ZOOKEEPER_PORT));
zkProperties.setProperty("maxClientCnxns", "10000");
zkProperties.setProperty("minSessionTimeout", "10000");
zkProperties.setProperty("maxSessionTimeout", "100000");
zkProperties.setProperty("initLimit", "10");
zkProperties.setProperty("syncLimit", "5");
zkProperties.setProperty("snapCount", "50000");
return zkProperties;
}
/**
* Extension of {@link ZooKeeperServerMain} that allows programmatic shutdown
*/
private static class InternalZooKeeper extends ZooKeeperServerMain {
/**
* Shutdown the ZooKeeper instance.
*/
void end() {
shutdown();
}
}
}
| true | true | public static Iterable<String> run(
GiraphClasses classes,
Map<String, String> params,
String[] vertexInputData,
String[] edgeInputData) throws Exception {
File tmpDir = null;
try {
// Prepare input file, output folder and temporary folders
tmpDir = FileUtils.createTestDir(classes.getVertexClass());
File vertexInputFile = null;
File edgeInputFile = null;
if (classes.hasVertexInputFormat()) {
vertexInputFile = FileUtils.createTempFile(tmpDir, "vertices.txt");
}
if (classes.hasEdgeInputFormat()) {
edgeInputFile = FileUtils.createTempFile(tmpDir, "edges.txt");
}
File outputDir = FileUtils.createTempDir(tmpDir, "output");
File zkDir = FileUtils.createTempDir(tmpDir, "_bspZooKeeper");
File zkMgrDir = FileUtils.createTempDir(tmpDir, "_defaultZkManagerDir");
File checkpointsDir = FileUtils.createTempDir(tmpDir, "_checkpoints");
// Write input data to disk
if (classes.hasVertexInputFormat()) {
FileUtils.writeLines(vertexInputFile, vertexInputData);
}
if (classes.hasEdgeInputFormat()) {
FileUtils.writeLines(edgeInputFile, edgeInputData);
}
// Create and configure the job to run the vertex
GiraphJob job = new GiraphJob(classes.getVertexClass().getName());
GiraphConfiguration conf = job.getConfiguration();
conf.setVertexClass(classes.getVertexClass());
conf.setVertexEdgesClass(classes.getVertexEdgesClass());
if (classes.hasVertexInputFormat()) {
conf.setVertexInputFormatClass(classes.getVertexInputFormatClass());
}
if (classes.hasEdgeInputFormat()) {
conf.setEdgeInputFormatClass(classes.getEdgeInputFormatClass());
}
if (classes.hasVertexOutputFormat()) {
conf.setVertexOutputFormatClass(classes.getVertexOutputFormatClass());
}
if (classes.hasWorkerContextClass()) {
conf.setWorkerContextClass(classes.getWorkerContextClass());
}
if (classes.hasPartitionContextClass()) {
conf.setMasterComputeClass(classes.getPartitionContextClass());
}
if (classes.hasCombinerClass()) {
conf.setVertexCombinerClass(classes.getCombinerClass());
}
if (classes.hasMasterComputeClass()) {
conf.setMasterComputeClass(classes.getMasterComputeClass());
}
conf.setWorkerConfiguration(1, 1, 100.0f);
conf.setBoolean(GiraphConstants.SPLIT_MASTER_WORKER, false);
conf.setBoolean(GiraphConstants.LOCAL_TEST_MODE, true);
conf.set(GiraphConstants.ZOOKEEPER_LIST, "localhost:" +
String.valueOf(LOCAL_ZOOKEEPER_PORT));
conf.set(GiraphConstants.ZOOKEEPER_DIR, zkDir.toString());
conf.set(GiraphConstants.ZOOKEEPER_MANAGER_DIRECTORY,
zkMgrDir.toString());
conf.set(GiraphConstants.CHECKPOINT_DIRECTORY, checkpointsDir.toString());
for (Map.Entry<String, String> param : params.entrySet()) {
conf.set(param.getKey(), param.getValue());
}
Job internalJob = job.getInternalJob();
if (classes.hasVertexInputFormat()) {
GiraphFileInputFormat.addVertexInputPath(internalJob.getConfiguration(),
new Path(vertexInputFile.toString()));
}
if (classes.hasEdgeInputFormat()) {
GiraphFileInputFormat.addEdgeInputPath(internalJob.getConfiguration(),
new Path(edgeInputFile.toString()));
}
FileOutputFormat.setOutputPath(job.getInternalJob(),
new Path(outputDir.toString()));
// Configure a local zookeeper instance
Properties zkProperties = configLocalZooKeeper(zkDir);
QuorumPeerConfig qpConfig = new QuorumPeerConfig();
qpConfig.parseProperties(zkProperties);
// Create and run the zookeeper instance
final InternalZooKeeper zookeeper = new InternalZooKeeper();
final ServerConfig zkConfig = new ServerConfig();
zkConfig.readFrom(qpConfig);
ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.execute(new Runnable() {
@Override
public void run() {
try {
zookeeper.runFromConfig(zkConfig);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
});
try {
job.run(true);
} finally {
executorService.shutdown();
zookeeper.end();
}
if (classes.hasVertexOutputFormat()) {
return Files.readLines(new File(outputDir, "part-m-00000"),
Charsets.UTF_8);
} else {
return ImmutableList.of();
}
} finally {
FileUtils.delete(tmpDir);
}
}
| public static Iterable<String> run(
GiraphClasses classes,
Map<String, String> params,
String[] vertexInputData,
String[] edgeInputData) throws Exception {
File tmpDir = null;
try {
// Prepare input file, output folder and temporary folders
tmpDir = FileUtils.createTestDir(classes.getVertexClass());
File vertexInputFile = null;
File edgeInputFile = null;
if (classes.hasVertexInputFormat()) {
vertexInputFile = FileUtils.createTempFile(tmpDir, "vertices.txt");
}
if (classes.hasEdgeInputFormat()) {
edgeInputFile = FileUtils.createTempFile(tmpDir, "edges.txt");
}
File outputDir = FileUtils.createTempDir(tmpDir, "output");
File zkDir = FileUtils.createTempDir(tmpDir, "_bspZooKeeper");
File zkMgrDir = FileUtils.createTempDir(tmpDir, "_defaultZkManagerDir");
File checkpointsDir = FileUtils.createTempDir(tmpDir, "_checkpoints");
// Write input data to disk
if (classes.hasVertexInputFormat()) {
FileUtils.writeLines(vertexInputFile, vertexInputData);
}
if (classes.hasEdgeInputFormat()) {
FileUtils.writeLines(edgeInputFile, edgeInputData);
}
// Create and configure the job to run the vertex
GiraphJob job = new GiraphJob(classes.getVertexClass().getName());
GiraphConfiguration conf = job.getConfiguration();
conf.setVertexClass(classes.getVertexClass());
conf.setVertexEdgesClass(classes.getVertexEdgesClass());
if (classes.hasVertexInputFormat()) {
conf.setVertexInputFormatClass(classes.getVertexInputFormatClass());
}
if (classes.hasEdgeInputFormat()) {
conf.setEdgeInputFormatClass(classes.getEdgeInputFormatClass());
}
if (classes.hasVertexOutputFormat()) {
conf.setVertexOutputFormatClass(classes.getVertexOutputFormatClass());
}
if (classes.hasWorkerContextClass()) {
conf.setWorkerContextClass(classes.getWorkerContextClass());
}
if (classes.hasPartitionContextClass()) {
conf.setPartitionContextClass(classes.getPartitionContextClass());
}
if (classes.hasCombinerClass()) {
conf.setVertexCombinerClass(classes.getCombinerClass());
}
if (classes.hasMasterComputeClass()) {
conf.setMasterComputeClass(classes.getMasterComputeClass());
}
conf.setWorkerConfiguration(1, 1, 100.0f);
conf.setBoolean(GiraphConstants.SPLIT_MASTER_WORKER, false);
conf.setBoolean(GiraphConstants.LOCAL_TEST_MODE, true);
conf.set(GiraphConstants.ZOOKEEPER_LIST, "localhost:" +
String.valueOf(LOCAL_ZOOKEEPER_PORT));
conf.set(GiraphConstants.ZOOKEEPER_DIR, zkDir.toString());
conf.set(GiraphConstants.ZOOKEEPER_MANAGER_DIRECTORY,
zkMgrDir.toString());
conf.set(GiraphConstants.CHECKPOINT_DIRECTORY, checkpointsDir.toString());
for (Map.Entry<String, String> param : params.entrySet()) {
conf.set(param.getKey(), param.getValue());
}
Job internalJob = job.getInternalJob();
if (classes.hasVertexInputFormat()) {
GiraphFileInputFormat.addVertexInputPath(internalJob.getConfiguration(),
new Path(vertexInputFile.toString()));
}
if (classes.hasEdgeInputFormat()) {
GiraphFileInputFormat.addEdgeInputPath(internalJob.getConfiguration(),
new Path(edgeInputFile.toString()));
}
FileOutputFormat.setOutputPath(job.getInternalJob(),
new Path(outputDir.toString()));
// Configure a local zookeeper instance
Properties zkProperties = configLocalZooKeeper(zkDir);
QuorumPeerConfig qpConfig = new QuorumPeerConfig();
qpConfig.parseProperties(zkProperties);
// Create and run the zookeeper instance
final InternalZooKeeper zookeeper = new InternalZooKeeper();
final ServerConfig zkConfig = new ServerConfig();
zkConfig.readFrom(qpConfig);
ExecutorService executorService = Executors.newSingleThreadExecutor();
executorService.execute(new Runnable() {
@Override
public void run() {
try {
zookeeper.runFromConfig(zkConfig);
} catch (IOException e) {
throw new RuntimeException(e);
}
}
});
try {
job.run(true);
} finally {
executorService.shutdown();
zookeeper.end();
}
if (classes.hasVertexOutputFormat()) {
return Files.readLines(new File(outputDir, "part-m-00000"),
Charsets.UTF_8);
} else {
return ImmutableList.of();
}
} finally {
FileUtils.delete(tmpDir);
}
}
|
diff --git a/src/web/org/openmrs/web/dwr/RelationshipListItem.java b/src/web/org/openmrs/web/dwr/RelationshipListItem.java
index c8c88c1d..4d3be02b 100644
--- a/src/web/org/openmrs/web/dwr/RelationshipListItem.java
+++ b/src/web/org/openmrs/web/dwr/RelationshipListItem.java
@@ -1,137 +1,135 @@
/**
* The contents of this file are subject to the OpenMRS Public License
* Version 1.0 (the "License"); you may not use this file except in
* compliance with the License. You may obtain a copy of the License at
* http://license.openmrs.org
*
* Software distributed under the License is distributed on an "AS IS"
* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the
* License for the specific language governing rights and limitations
* under the License.
*
* Copyright (C) OpenMRS, LLC. All Rights Reserved.
*/
package org.openmrs.web.dwr;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.openmrs.Patient;
import org.openmrs.Person;
import org.openmrs.Relationship;
import org.openmrs.api.context.Context;
public class RelationshipListItem {
protected final Log log = LogFactory.getLog(getClass());
private Integer relationshipId;
private String personA;
private String personB;
private String aIsToB;
private String bIsToA;
private Integer personAId;
private Integer personBId;
private String personAType;
private String personBType;
public RelationshipListItem() { }
public RelationshipListItem(Relationship r) {
relationshipId = r.getRelationshipId();
aIsToB = r.getRelationshipType().getaIsToB();
bIsToA = r.getRelationshipType().getbIsToA();
Person p = r.getPersonA();
personA = p.getPersonName().toString();
personAId = p.getPersonId();
try {
- Patient pat = Context.getPatientService().getPatient(p.getPersonId());
- personAType = pat != null ? "Patient" : "User";
+ personAType = p.isPatient() ? "Patient" : "User";
} catch (Exception ex) { personAType = "User"; }
p = r.getPersonB();
personB = p.getPersonName().toString();
personBId = p.getPersonId();
try {
- Patient pat = Context.getPatientService().getPatient(p.getPersonId());
- personBType = pat != null ? "Patient" : "User";
+ personBType = p.isPatient() ? "Patient" : "User";
} catch (Exception ex) { personAType = "User"; }
}
public String toString() {
return relationshipId + "," + personA + "," + personB + "," + aIsToB + "," + bIsToA + "," + personAId + "," + personBId;
}
public String getPersonA() {
return personA;
}
public void setPersonA(String fromName) {
this.personA = fromName;
}
public Integer getPersonAId() {
return personAId;
}
public void setPersonAId(Integer fromPersonId) {
this.personAId = fromPersonId;
}
public Integer getRelationshipId() {
return relationshipId;
}
public void setRelationshipId(Integer relationshipId) {
this.relationshipId = relationshipId;
}
public String getPersonB() {
return personB;
}
public void setPersonB(String toName) {
this.personB = toName;
}
public Integer getPersonBId() {
return personBId;
}
public void setPersonBId(Integer toPersonId) {
this.personBId = toPersonId;
}
public String getaIsToB() {
return aIsToB;
}
public void setaIsToB(String isToB) {
aIsToB = isToB;
}
public String getbIsToA() {
return bIsToA;
}
public void setbIsToA(String isToA) {
bIsToA = isToA;
}
public String getPersonAType() {
return personAType;
}
public void setPersonAType(String personAType) {
this.personAType = personAType;
}
public String getPersonBType() {
return personBType;
}
public void setPersonBType(String personBType) {
this.personBType = personBType;
}
}
| false | true | public RelationshipListItem(Relationship r) {
relationshipId = r.getRelationshipId();
aIsToB = r.getRelationshipType().getaIsToB();
bIsToA = r.getRelationshipType().getbIsToA();
Person p = r.getPersonA();
personA = p.getPersonName().toString();
personAId = p.getPersonId();
try {
Patient pat = Context.getPatientService().getPatient(p.getPersonId());
personAType = pat != null ? "Patient" : "User";
} catch (Exception ex) { personAType = "User"; }
p = r.getPersonB();
personB = p.getPersonName().toString();
personBId = p.getPersonId();
try {
Patient pat = Context.getPatientService().getPatient(p.getPersonId());
personBType = pat != null ? "Patient" : "User";
} catch (Exception ex) { personAType = "User"; }
}
| public RelationshipListItem(Relationship r) {
relationshipId = r.getRelationshipId();
aIsToB = r.getRelationshipType().getaIsToB();
bIsToA = r.getRelationshipType().getbIsToA();
Person p = r.getPersonA();
personA = p.getPersonName().toString();
personAId = p.getPersonId();
try {
personAType = p.isPatient() ? "Patient" : "User";
} catch (Exception ex) { personAType = "User"; }
p = r.getPersonB();
personB = p.getPersonName().toString();
personBId = p.getPersonId();
try {
personBType = p.isPatient() ? "Patient" : "User";
} catch (Exception ex) { personAType = "User"; }
}
|
diff --git a/flexoserver/flexoexternalbuilders/src/main/java/org/openflexo/builders/utils/FlexoBuilderProjectReferenceLoader.java b/flexoserver/flexoexternalbuilders/src/main/java/org/openflexo/builders/utils/FlexoBuilderProjectReferenceLoader.java
index c2077e0f6..f70624919 100644
--- a/flexoserver/flexoexternalbuilders/src/main/java/org/openflexo/builders/utils/FlexoBuilderProjectReferenceLoader.java
+++ b/flexoserver/flexoexternalbuilders/src/main/java/org/openflexo/builders/utils/FlexoBuilderProjectReferenceLoader.java
@@ -1,226 +1,227 @@
package org.openflexo.builders.utils;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.ProtocolException;
import java.net.URL;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.zip.ZipException;
import org.apache.commons.io.IOUtils;
import org.openflexo.builders.FlexoExternalMain;
import org.openflexo.foundation.FlexoEditor;
import org.openflexo.foundation.rm.FlexoProject;
import org.openflexo.foundation.rm.FlexoProject.FlexoProjectReferenceLoader;
import org.openflexo.foundation.rm.FlexoProjectReference;
import org.openflexo.foundation.utils.ProjectInitializerException;
import org.openflexo.foundation.utils.ProjectLoadingCancelledException;
import org.openflexo.module.ProjectLoader;
import org.openflexo.toolbox.FileUtils;
import org.openflexo.toolbox.ZipUtils;
public class FlexoBuilderProjectReferenceLoader implements FlexoProjectReferenceLoader {
private String serverURL;
private String login;
private String password;
private final FlexoExternalMain externalMain;
private final ProjectLoader projectLoader;
public FlexoBuilderProjectReferenceLoader(FlexoExternalMain externalMain, ProjectLoader projectLoader, String serverURL, String login,
String password) {
super();
this.externalMain = externalMain;
this.projectLoader = projectLoader;
this.serverURL = serverURL;
this.login = login;
this.password = password;
}
@Override
public FlexoProject loadProject(FlexoProjectReference reference, boolean silentlyOnly) {
FlexoEditor editor = projectLoader.editorForProjectURIAndRevision(reference.getURI(), reference.getRevision());
if (editor != null) {
return editor.getProject();
}
if (serverURL != null && login != null && password != null) {
Map<String, String> param = new HashMap<String, String>();
param.put("login", login);
param.put("password", password);
param.put("uri", reference.getURI());
param.put("revision", String.valueOf(reference.getRevision()));
+ param.put("greaterOrEqual", "true");
StringBuilder paramsAsString = new StringBuilder();
if (param != null && param.size() > 0) {
boolean first = true;
for (Entry<String, String> e : param.entrySet()) {
paramsAsString.append(first ? "" : "&");
try {
paramsAsString.append(URLEncoder.encode(e.getKey(), "UTF-8")).append("=")
.append(URLEncoder.encode(e.getValue(), "UTF-8"));
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
first = false;
}
}
// Create a URL for the desired page
URL url;
try {
url = new URL(serverURL);
} catch (MalformedURLException e) {
e.printStackTrace();
externalMain.reportMessage("Unable to load " + reference.getName() + " " + reference.getVersion()
+ " because server URL seems misconfigured: '" + serverURL + "'" + ".\n(" + e.getMessage() + ")");
return null;
}
HttpURLConnection conn;
try {
conn = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
e.printStackTrace();
externalMain.reportMessage("Unable to load " + reference.getName() + " " + reference.getVersion()
+ " because worker cannot access server URL '" + url.toString() + "'" + ".\n(" + e.getMessage() + ")");
return null;
}
try {
conn.setRequestMethod("POST");
} catch (ProtocolException e) {
e.printStackTrace();
// Should never happen
}
conn.setDoOutput(true);
OutputStreamWriter wr;
try {
wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(paramsAsString.toString());
wr.flush();
} catch (IOException e) {
e.printStackTrace();
externalMain.reportMessage("Unable to load " + reference.getName() + " " + reference.getVersion()
+ " because worker cannot open server URL '" + url.toString() + "'" + ".\n(" + e.getMessage() + ")");
return null;
}
// Read all the text returned by the server
int httpStatus;
try {
httpStatus = conn.getResponseCode();
} catch (IOException e) {
e.printStackTrace();
externalMain.reportMessage("Unable to load " + reference.getName() + " " + reference.getVersion()
+ " because worker could not read HTTP response code for server URL '" + url.toString() + "'.\n(" + e.getMessage()
+ ")");
return null;
}
InputStream inputStream;
if (httpStatus < 400) {
try {
inputStream = conn.getInputStream();
} catch (IOException e) {
e.printStackTrace();
externalMain.reportMessage("Unable to load " + reference.getName() + " " + reference.getVersion()
+ " because worker could not read data for server URL '" + url.toString() + "'.\n(" + e.getMessage() + ")"
+ "\nStatus: " + httpStatus);
return null;
}
String base = "Projects/" + reference.getName() + "_" + reference.getVersion();
File file = new File(externalMain.getWorkingDir(), base + ".zip");
int i = 0;
while (file.exists()) {
file = new File(externalMain.getWorkingDir(), base + "-" + i++ + ".zip");
}
file.getParentFile().mkdirs();
try {
FileUtils.saveToFile(file, inputStream);
} catch (IOException e) {
e.printStackTrace();
}
base = "ExtractedProjects/" + reference.getName() + "_" + reference.getVersion();
File extractionDirectory = new File(externalMain.getWorkingDir(), base);
i = 0;
while (extractionDirectory.exists()) {
extractionDirectory = new File(externalMain.getWorkingDir(), base + "-" + i++);
}
extractionDirectory.mkdirs();
try {
ZipUtils.unzip(file, extractionDirectory);
} catch (ZipException e) {
e.printStackTrace();
externalMain.reportMessage("Unable to load " + reference.getName() + " " + reference.getVersion()
+ " because worker could not read the zip file returned by server URL '" + url.toString() + "'.\n("
+ e.getMessage() + ")");
return null;
} catch (IOException e) {
e.printStackTrace();
externalMain.reportMessage("Unable to load " + reference.getName() + " " + reference.getVersion()
+ " because worker could not extract the zip file returned by server URL '" + url.toString()
+ "' to the directory " + extractionDirectory.getAbsolutePath() + ".\n(" + e.getMessage() + ")");
return null;
}
File projectDirectory = FlexoExternalMain.searchProjectDirectory(extractionDirectory);
if (projectDirectory == null) {
externalMain.reportMessage("Unable to load " + reference.getName() + " " + reference.getVersion()
+ " because worker could not find a project in the directory " + extractionDirectory.getAbsolutePath() + ".");
return null;
}
try {
editor = projectLoader.loadProject(projectDirectory, true);
} catch (ProjectLoadingCancelledException e) {
e.printStackTrace();
externalMain.reportMessage("Unable to load " + reference.getName() + " " + reference.getVersion()
+ " because project loading was cancelled for directory " + projectDirectory.getAbsolutePath() + ".\n("
+ e.getMessage() + ")");
return null;
} catch (ProjectInitializerException e) {
e.printStackTrace();
externalMain.reportMessage("Unable to load " + reference.getName() + " " + reference.getVersion()
+ " because project loading failed for directory " + projectDirectory.getAbsolutePath() + ".\n("
+ e.getMessage() + ")");
return null;
}
if (editor != null) {
return editor.getProject();
} else {
externalMain.reportMessage("Unable to load project " + reference.getName() + " " + reference.getVersion()
+ " located at " + projectDirectory.getAbsolutePath() + ".");
return null;
}
} else {
inputStream = conn.getErrorStream();
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
String str;
StringBuilder reply = new StringBuilder();
try {
while ((str = in.readLine()) != null) {
reply.append(str).append("\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
IOUtils.closeQuietly(wr);
IOUtils.closeQuietly(in);
}
externalMain.reportMessage("Unable to load " + reference.getName() + " " + reference.getVersion()
+ " because an error occured for server URL '" + url.toString() + "'" + ".\nStatus: " + httpStatus + "\n"
+ reply.toString());
return null;
}
} else {
externalMain.reportMessage("Unable to load " + reference.getName() + " " + reference.getVersion()
+ " because information and credentials are incomplete (server URL=" + serverURL + " login="
+ (login != null ? "OK" : "null") + " password=" + (password != null ? "OK" : "null"));
return null;
}
}
}
| true | true | public FlexoProject loadProject(FlexoProjectReference reference, boolean silentlyOnly) {
FlexoEditor editor = projectLoader.editorForProjectURIAndRevision(reference.getURI(), reference.getRevision());
if (editor != null) {
return editor.getProject();
}
if (serverURL != null && login != null && password != null) {
Map<String, String> param = new HashMap<String, String>();
param.put("login", login);
param.put("password", password);
param.put("uri", reference.getURI());
param.put("revision", String.valueOf(reference.getRevision()));
StringBuilder paramsAsString = new StringBuilder();
if (param != null && param.size() > 0) {
boolean first = true;
for (Entry<String, String> e : param.entrySet()) {
paramsAsString.append(first ? "" : "&");
try {
paramsAsString.append(URLEncoder.encode(e.getKey(), "UTF-8")).append("=")
.append(URLEncoder.encode(e.getValue(), "UTF-8"));
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
first = false;
}
}
// Create a URL for the desired page
URL url;
try {
url = new URL(serverURL);
} catch (MalformedURLException e) {
e.printStackTrace();
externalMain.reportMessage("Unable to load " + reference.getName() + " " + reference.getVersion()
+ " because server URL seems misconfigured: '" + serverURL + "'" + ".\n(" + e.getMessage() + ")");
return null;
}
HttpURLConnection conn;
try {
conn = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
e.printStackTrace();
externalMain.reportMessage("Unable to load " + reference.getName() + " " + reference.getVersion()
+ " because worker cannot access server URL '" + url.toString() + "'" + ".\n(" + e.getMessage() + ")");
return null;
}
try {
conn.setRequestMethod("POST");
} catch (ProtocolException e) {
e.printStackTrace();
// Should never happen
}
conn.setDoOutput(true);
OutputStreamWriter wr;
try {
wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(paramsAsString.toString());
wr.flush();
} catch (IOException e) {
e.printStackTrace();
externalMain.reportMessage("Unable to load " + reference.getName() + " " + reference.getVersion()
+ " because worker cannot open server URL '" + url.toString() + "'" + ".\n(" + e.getMessage() + ")");
return null;
}
// Read all the text returned by the server
int httpStatus;
try {
httpStatus = conn.getResponseCode();
} catch (IOException e) {
e.printStackTrace();
externalMain.reportMessage("Unable to load " + reference.getName() + " " + reference.getVersion()
+ " because worker could not read HTTP response code for server URL '" + url.toString() + "'.\n(" + e.getMessage()
+ ")");
return null;
}
InputStream inputStream;
if (httpStatus < 400) {
try {
inputStream = conn.getInputStream();
} catch (IOException e) {
e.printStackTrace();
externalMain.reportMessage("Unable to load " + reference.getName() + " " + reference.getVersion()
+ " because worker could not read data for server URL '" + url.toString() + "'.\n(" + e.getMessage() + ")"
+ "\nStatus: " + httpStatus);
return null;
}
String base = "Projects/" + reference.getName() + "_" + reference.getVersion();
File file = new File(externalMain.getWorkingDir(), base + ".zip");
int i = 0;
while (file.exists()) {
file = new File(externalMain.getWorkingDir(), base + "-" + i++ + ".zip");
}
file.getParentFile().mkdirs();
try {
FileUtils.saveToFile(file, inputStream);
} catch (IOException e) {
e.printStackTrace();
}
base = "ExtractedProjects/" + reference.getName() + "_" + reference.getVersion();
File extractionDirectory = new File(externalMain.getWorkingDir(), base);
i = 0;
while (extractionDirectory.exists()) {
extractionDirectory = new File(externalMain.getWorkingDir(), base + "-" + i++);
}
extractionDirectory.mkdirs();
try {
ZipUtils.unzip(file, extractionDirectory);
} catch (ZipException e) {
e.printStackTrace();
externalMain.reportMessage("Unable to load " + reference.getName() + " " + reference.getVersion()
+ " because worker could not read the zip file returned by server URL '" + url.toString() + "'.\n("
+ e.getMessage() + ")");
return null;
} catch (IOException e) {
e.printStackTrace();
externalMain.reportMessage("Unable to load " + reference.getName() + " " + reference.getVersion()
+ " because worker could not extract the zip file returned by server URL '" + url.toString()
+ "' to the directory " + extractionDirectory.getAbsolutePath() + ".\n(" + e.getMessage() + ")");
return null;
}
File projectDirectory = FlexoExternalMain.searchProjectDirectory(extractionDirectory);
if (projectDirectory == null) {
externalMain.reportMessage("Unable to load " + reference.getName() + " " + reference.getVersion()
+ " because worker could not find a project in the directory " + extractionDirectory.getAbsolutePath() + ".");
return null;
}
try {
editor = projectLoader.loadProject(projectDirectory, true);
} catch (ProjectLoadingCancelledException e) {
e.printStackTrace();
externalMain.reportMessage("Unable to load " + reference.getName() + " " + reference.getVersion()
+ " because project loading was cancelled for directory " + projectDirectory.getAbsolutePath() + ".\n("
+ e.getMessage() + ")");
return null;
} catch (ProjectInitializerException e) {
e.printStackTrace();
externalMain.reportMessage("Unable to load " + reference.getName() + " " + reference.getVersion()
+ " because project loading failed for directory " + projectDirectory.getAbsolutePath() + ".\n("
+ e.getMessage() + ")");
return null;
}
if (editor != null) {
return editor.getProject();
} else {
externalMain.reportMessage("Unable to load project " + reference.getName() + " " + reference.getVersion()
+ " located at " + projectDirectory.getAbsolutePath() + ".");
return null;
}
} else {
inputStream = conn.getErrorStream();
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
String str;
StringBuilder reply = new StringBuilder();
try {
while ((str = in.readLine()) != null) {
reply.append(str).append("\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
IOUtils.closeQuietly(wr);
IOUtils.closeQuietly(in);
}
externalMain.reportMessage("Unable to load " + reference.getName() + " " + reference.getVersion()
+ " because an error occured for server URL '" + url.toString() + "'" + ".\nStatus: " + httpStatus + "\n"
+ reply.toString());
return null;
}
} else {
externalMain.reportMessage("Unable to load " + reference.getName() + " " + reference.getVersion()
+ " because information and credentials are incomplete (server URL=" + serverURL + " login="
+ (login != null ? "OK" : "null") + " password=" + (password != null ? "OK" : "null"));
return null;
}
}
| public FlexoProject loadProject(FlexoProjectReference reference, boolean silentlyOnly) {
FlexoEditor editor = projectLoader.editorForProjectURIAndRevision(reference.getURI(), reference.getRevision());
if (editor != null) {
return editor.getProject();
}
if (serverURL != null && login != null && password != null) {
Map<String, String> param = new HashMap<String, String>();
param.put("login", login);
param.put("password", password);
param.put("uri", reference.getURI());
param.put("revision", String.valueOf(reference.getRevision()));
param.put("greaterOrEqual", "true");
StringBuilder paramsAsString = new StringBuilder();
if (param != null && param.size() > 0) {
boolean first = true;
for (Entry<String, String> e : param.entrySet()) {
paramsAsString.append(first ? "" : "&");
try {
paramsAsString.append(URLEncoder.encode(e.getKey(), "UTF-8")).append("=")
.append(URLEncoder.encode(e.getValue(), "UTF-8"));
} catch (UnsupportedEncodingException e1) {
e1.printStackTrace();
}
first = false;
}
}
// Create a URL for the desired page
URL url;
try {
url = new URL(serverURL);
} catch (MalformedURLException e) {
e.printStackTrace();
externalMain.reportMessage("Unable to load " + reference.getName() + " " + reference.getVersion()
+ " because server URL seems misconfigured: '" + serverURL + "'" + ".\n(" + e.getMessage() + ")");
return null;
}
HttpURLConnection conn;
try {
conn = (HttpURLConnection) url.openConnection();
} catch (IOException e) {
e.printStackTrace();
externalMain.reportMessage("Unable to load " + reference.getName() + " " + reference.getVersion()
+ " because worker cannot access server URL '" + url.toString() + "'" + ".\n(" + e.getMessage() + ")");
return null;
}
try {
conn.setRequestMethod("POST");
} catch (ProtocolException e) {
e.printStackTrace();
// Should never happen
}
conn.setDoOutput(true);
OutputStreamWriter wr;
try {
wr = new OutputStreamWriter(conn.getOutputStream());
wr.write(paramsAsString.toString());
wr.flush();
} catch (IOException e) {
e.printStackTrace();
externalMain.reportMessage("Unable to load " + reference.getName() + " " + reference.getVersion()
+ " because worker cannot open server URL '" + url.toString() + "'" + ".\n(" + e.getMessage() + ")");
return null;
}
// Read all the text returned by the server
int httpStatus;
try {
httpStatus = conn.getResponseCode();
} catch (IOException e) {
e.printStackTrace();
externalMain.reportMessage("Unable to load " + reference.getName() + " " + reference.getVersion()
+ " because worker could not read HTTP response code for server URL '" + url.toString() + "'.\n(" + e.getMessage()
+ ")");
return null;
}
InputStream inputStream;
if (httpStatus < 400) {
try {
inputStream = conn.getInputStream();
} catch (IOException e) {
e.printStackTrace();
externalMain.reportMessage("Unable to load " + reference.getName() + " " + reference.getVersion()
+ " because worker could not read data for server URL '" + url.toString() + "'.\n(" + e.getMessage() + ")"
+ "\nStatus: " + httpStatus);
return null;
}
String base = "Projects/" + reference.getName() + "_" + reference.getVersion();
File file = new File(externalMain.getWorkingDir(), base + ".zip");
int i = 0;
while (file.exists()) {
file = new File(externalMain.getWorkingDir(), base + "-" + i++ + ".zip");
}
file.getParentFile().mkdirs();
try {
FileUtils.saveToFile(file, inputStream);
} catch (IOException e) {
e.printStackTrace();
}
base = "ExtractedProjects/" + reference.getName() + "_" + reference.getVersion();
File extractionDirectory = new File(externalMain.getWorkingDir(), base);
i = 0;
while (extractionDirectory.exists()) {
extractionDirectory = new File(externalMain.getWorkingDir(), base + "-" + i++);
}
extractionDirectory.mkdirs();
try {
ZipUtils.unzip(file, extractionDirectory);
} catch (ZipException e) {
e.printStackTrace();
externalMain.reportMessage("Unable to load " + reference.getName() + " " + reference.getVersion()
+ " because worker could not read the zip file returned by server URL '" + url.toString() + "'.\n("
+ e.getMessage() + ")");
return null;
} catch (IOException e) {
e.printStackTrace();
externalMain.reportMessage("Unable to load " + reference.getName() + " " + reference.getVersion()
+ " because worker could not extract the zip file returned by server URL '" + url.toString()
+ "' to the directory " + extractionDirectory.getAbsolutePath() + ".\n(" + e.getMessage() + ")");
return null;
}
File projectDirectory = FlexoExternalMain.searchProjectDirectory(extractionDirectory);
if (projectDirectory == null) {
externalMain.reportMessage("Unable to load " + reference.getName() + " " + reference.getVersion()
+ " because worker could not find a project in the directory " + extractionDirectory.getAbsolutePath() + ".");
return null;
}
try {
editor = projectLoader.loadProject(projectDirectory, true);
} catch (ProjectLoadingCancelledException e) {
e.printStackTrace();
externalMain.reportMessage("Unable to load " + reference.getName() + " " + reference.getVersion()
+ " because project loading was cancelled for directory " + projectDirectory.getAbsolutePath() + ".\n("
+ e.getMessage() + ")");
return null;
} catch (ProjectInitializerException e) {
e.printStackTrace();
externalMain.reportMessage("Unable to load " + reference.getName() + " " + reference.getVersion()
+ " because project loading failed for directory " + projectDirectory.getAbsolutePath() + ".\n("
+ e.getMessage() + ")");
return null;
}
if (editor != null) {
return editor.getProject();
} else {
externalMain.reportMessage("Unable to load project " + reference.getName() + " " + reference.getVersion()
+ " located at " + projectDirectory.getAbsolutePath() + ".");
return null;
}
} else {
inputStream = conn.getErrorStream();
BufferedReader in = new BufferedReader(new InputStreamReader(inputStream));
String str;
StringBuilder reply = new StringBuilder();
try {
while ((str = in.readLine()) != null) {
reply.append(str).append("\n");
}
} catch (IOException e) {
e.printStackTrace();
} finally {
IOUtils.closeQuietly(wr);
IOUtils.closeQuietly(in);
}
externalMain.reportMessage("Unable to load " + reference.getName() + " " + reference.getVersion()
+ " because an error occured for server URL '" + url.toString() + "'" + ".\nStatus: " + httpStatus + "\n"
+ reply.toString());
return null;
}
} else {
externalMain.reportMessage("Unable to load " + reference.getName() + " " + reference.getVersion()
+ " because information and credentials are incomplete (server URL=" + serverURL + " login="
+ (login != null ? "OK" : "null") + " password=" + (password != null ? "OK" : "null"));
return null;
}
}
|
diff --git a/src/soot/javaToJimple/PolyglotMethodSource.java b/src/soot/javaToJimple/PolyglotMethodSource.java
index 3b566ea9..46f7d29e 100644
--- a/src/soot/javaToJimple/PolyglotMethodSource.java
+++ b/src/soot/javaToJimple/PolyglotMethodSource.java
@@ -1,240 +1,240 @@
/* Soot - a J*va Optimization Framework
* Copyright (C) 2004 Jennifer Lhotak
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the
* Free Software Foundation, Inc., 59 Temple Place - Suite 330,
* Boston, MA 02111-1307, USA.
*/
package soot.javaToJimple;
import java.util.*;
import soot.*;
public class PolyglotMethodSource implements MethodSource {
private polyglot.ast.Block block;
private List formals;
private ArrayList fieldInits;
private ArrayList staticFieldInits;
private ArrayList initializerBlocks;
private ArrayList staticInitializerBlocks;
private soot.Local outerClassThisInit;
private boolean hasAssert = false;
private ArrayList finalsList;
private HashMap newToOuterMap;
private AbstractJimpleBodyBuilder ajbb;
public PolyglotMethodSource(){
this.block = null;
this.formals = null;
}
public PolyglotMethodSource(polyglot.ast.Block block, List formals){
this.block = block;
this.formals = formals;
}
public soot.Body getBody(soot.SootMethod sm, String phaseName) {
//JimpleBodyBuilder jbb = new JimpleBodyBuilder();
soot.jimple.JimpleBody jb = ajbb.createJimpleBody(block, formals, sm);
PackManager.v().getPack("jj").apply(jb);
return jb;
}
public void setJBB(AbstractJimpleBodyBuilder ajbb){
this.ajbb = ajbb;
}
public void setFieldInits(ArrayList fieldInits){
this.fieldInits = fieldInits;
}
public void setStaticFieldInits(ArrayList staticFieldInits){
this.staticFieldInits = staticFieldInits;
}
public ArrayList getFieldInits() {
return fieldInits;
}
public ArrayList getStaticFieldInits() {
return staticFieldInits;
}
public void setStaticInitializerBlocks(ArrayList staticInits) {
staticInitializerBlocks = staticInits;
}
public void setInitializerBlocks(ArrayList inits) {
initializerBlocks = inits;
}
public ArrayList getStaticInitializerBlocks() {
return staticInitializerBlocks;
}
public ArrayList getInitializerBlocks() {
return initializerBlocks;
}
public void setOuterClassThisInit(soot.Local l) {
outerClassThisInit = l;
}
public soot.Local getOuterClassThisInit(){
return outerClassThisInit;
}
public boolean hasAssert(){
return hasAssert;
}
public void hasAssert(boolean val){
hasAssert = val;
}
public void addAssertInits(soot.Body body){
// if class is inner get desired assertion status from outer most class
soot.SootClass assertStatusClass = body.getMethod().getDeclaringClass();
HashMap innerMap = soot.javaToJimple.InitialResolver.v().getInnerClassInfoMap();
while ((innerMap != null) && (innerMap.containsKey(assertStatusClass))){
assertStatusClass = ((InnerClassInfo)innerMap.get(assertStatusClass)).getOuterClass();
}
// field ref
soot.SootFieldRef field = soot.Scene.v().makeFieldRef(assertStatusClass, "class$"+assertStatusClass.getName(), soot.RefType.v("java.lang.Class"), true);
soot.Local fieldLocal = soot.jimple.Jimple.v().newLocal("$r0", soot.RefType.v("java.lang.Class"));
body.getLocals().add(fieldLocal);
soot.jimple.FieldRef fieldRef = soot.jimple.Jimple.v().newStaticFieldRef(field);
soot.jimple.AssignStmt fieldAssignStmt = soot.jimple.Jimple.v().newAssignStmt(fieldLocal, fieldRef);
body.getUnits().add(fieldAssignStmt);
// if field not null
soot.jimple.ConditionExpr cond = soot.jimple.Jimple.v().newNeExpr(fieldLocal, soot.jimple.NullConstant.v());
soot.jimple.NopStmt nop1 = soot.jimple.Jimple.v().newNopStmt();
soot.jimple.IfStmt ifStmt = soot.jimple.Jimple.v().newIfStmt(cond, nop1);
body.getUnits().add(ifStmt);
// if alternative
soot.Local invokeLocal = soot.jimple.Jimple.v().newLocal("$r1", soot.RefType.v("java.lang.Class"));
body.getLocals().add(invokeLocal);
ArrayList paramTypes = new ArrayList();
paramTypes.add(soot.RefType.v("java.lang.String"));
soot.SootMethodRef methodToInvoke = soot.Scene.v().makeMethodRef(assertStatusClass, "class$", paramTypes, soot.RefType.v("java.lang.Class"), true);
ArrayList params = new ArrayList();
params.add(soot.jimple.StringConstant.v(assertStatusClass.getName()));
soot.jimple.StaticInvokeExpr invoke = soot.jimple.Jimple.v().newStaticInvokeExpr(methodToInvoke, params);
soot.jimple.AssignStmt invokeAssign = soot.jimple.Jimple.v().newAssignStmt(invokeLocal, invoke);
body.getUnits().add(invokeAssign);
// field ref assign
soot.jimple.AssignStmt fieldRefAssign = soot.jimple.Jimple.v().newAssignStmt(fieldRef, invokeLocal);
body.getUnits().add(fieldRefAssign);
soot.jimple.NopStmt nop2 = soot.jimple.Jimple.v().newNopStmt();
soot.jimple.GotoStmt goto1 = soot.jimple.Jimple.v().newGotoStmt(nop2);
body.getUnits().add(goto1);
// add nop1 - and if consequence
body.getUnits().add(nop1);
soot.jimple.AssignStmt fieldRefAssign2 = soot.jimple.Jimple.v().newAssignStmt(invokeLocal, fieldRef);
body.getUnits().add(fieldRefAssign2);
body.getUnits().add(nop2);
// boolean tests
soot.Local boolLocal1 = soot.jimple.Jimple.v().newLocal("$z0", soot.BooleanType.v());
body.getLocals().add(boolLocal1);
soot.Local boolLocal2 = soot.jimple.Jimple.v().newLocal("$z1", soot.BooleanType.v());
body.getLocals().add(boolLocal2);
// virtual invoke
- soot.SootMethodRef vMethodToInvoke = Scene.v().makeMethodRef(soot.Scene.v().getSootClass("java.lang.Class"), "desiredAssertionStatus", new ArrayList(), soot.BooleanType.v(), true);
+ soot.SootMethodRef vMethodToInvoke = Scene.v().makeMethodRef(soot.Scene.v().getSootClass("java.lang.Class"), "desiredAssertionStatus", new ArrayList(), soot.BooleanType.v(), false);
soot.jimple.VirtualInvokeExpr vInvoke = soot.jimple.Jimple.v().newVirtualInvokeExpr(invokeLocal, vMethodToInvoke, new ArrayList());
soot.jimple.AssignStmt testAssign = soot.jimple.Jimple.v().newAssignStmt(boolLocal1, vInvoke);
body.getUnits().add(testAssign);
// if
soot.jimple.ConditionExpr cond2 = soot.jimple.Jimple.v().newNeExpr(boolLocal1, soot.jimple.IntConstant.v(0));
soot.jimple.NopStmt nop3 = soot.jimple.Jimple.v().newNopStmt();
soot.jimple.IfStmt ifStmt2 = soot.jimple.Jimple.v().newIfStmt(cond2, nop3);
body.getUnits().add(ifStmt2);
// alternative
soot.jimple.AssignStmt altAssign = soot.jimple.Jimple.v().newAssignStmt(boolLocal2, soot.jimple.IntConstant.v(1));
body.getUnits().add(altAssign);
soot.jimple.NopStmt nop4 = soot.jimple.Jimple.v().newNopStmt();
soot.jimple.GotoStmt goto2 = soot.jimple.Jimple.v().newGotoStmt(nop4);
body.getUnits().add(goto2);
body.getUnits().add(nop3);
soot.jimple.AssignStmt conAssign = soot.jimple.Jimple.v().newAssignStmt(boolLocal2, soot.jimple.IntConstant.v(0));
body.getUnits().add(conAssign);
body.getUnits().add(nop4);
// field assign
soot.SootFieldRef fieldD = Scene.v().makeFieldRef(body.getMethod().getDeclaringClass(), "$assertionsDisabled", soot.BooleanType.v(), true);
soot.jimple.FieldRef fieldRefD = soot.jimple.Jimple.v().newStaticFieldRef(fieldD);
soot.jimple.AssignStmt fAssign = soot.jimple.Jimple.v().newAssignStmt(fieldRefD, boolLocal2);
body.getUnits().add(fAssign);
}
public void setFinalsList(ArrayList list){
finalsList = list;
}
public ArrayList getFinalsList(){
return finalsList;
}
public void setNewToOuterMap(HashMap map){
newToOuterMap = map;
}
public HashMap getNewToOuterMap(){
return newToOuterMap;
}
}
| true | true | public void addAssertInits(soot.Body body){
// if class is inner get desired assertion status from outer most class
soot.SootClass assertStatusClass = body.getMethod().getDeclaringClass();
HashMap innerMap = soot.javaToJimple.InitialResolver.v().getInnerClassInfoMap();
while ((innerMap != null) && (innerMap.containsKey(assertStatusClass))){
assertStatusClass = ((InnerClassInfo)innerMap.get(assertStatusClass)).getOuterClass();
}
// field ref
soot.SootFieldRef field = soot.Scene.v().makeFieldRef(assertStatusClass, "class$"+assertStatusClass.getName(), soot.RefType.v("java.lang.Class"), true);
soot.Local fieldLocal = soot.jimple.Jimple.v().newLocal("$r0", soot.RefType.v("java.lang.Class"));
body.getLocals().add(fieldLocal);
soot.jimple.FieldRef fieldRef = soot.jimple.Jimple.v().newStaticFieldRef(field);
soot.jimple.AssignStmt fieldAssignStmt = soot.jimple.Jimple.v().newAssignStmt(fieldLocal, fieldRef);
body.getUnits().add(fieldAssignStmt);
// if field not null
soot.jimple.ConditionExpr cond = soot.jimple.Jimple.v().newNeExpr(fieldLocal, soot.jimple.NullConstant.v());
soot.jimple.NopStmt nop1 = soot.jimple.Jimple.v().newNopStmt();
soot.jimple.IfStmt ifStmt = soot.jimple.Jimple.v().newIfStmt(cond, nop1);
body.getUnits().add(ifStmt);
// if alternative
soot.Local invokeLocal = soot.jimple.Jimple.v().newLocal("$r1", soot.RefType.v("java.lang.Class"));
body.getLocals().add(invokeLocal);
ArrayList paramTypes = new ArrayList();
paramTypes.add(soot.RefType.v("java.lang.String"));
soot.SootMethodRef methodToInvoke = soot.Scene.v().makeMethodRef(assertStatusClass, "class$", paramTypes, soot.RefType.v("java.lang.Class"), true);
ArrayList params = new ArrayList();
params.add(soot.jimple.StringConstant.v(assertStatusClass.getName()));
soot.jimple.StaticInvokeExpr invoke = soot.jimple.Jimple.v().newStaticInvokeExpr(methodToInvoke, params);
soot.jimple.AssignStmt invokeAssign = soot.jimple.Jimple.v().newAssignStmt(invokeLocal, invoke);
body.getUnits().add(invokeAssign);
// field ref assign
soot.jimple.AssignStmt fieldRefAssign = soot.jimple.Jimple.v().newAssignStmt(fieldRef, invokeLocal);
body.getUnits().add(fieldRefAssign);
soot.jimple.NopStmt nop2 = soot.jimple.Jimple.v().newNopStmt();
soot.jimple.GotoStmt goto1 = soot.jimple.Jimple.v().newGotoStmt(nop2);
body.getUnits().add(goto1);
// add nop1 - and if consequence
body.getUnits().add(nop1);
soot.jimple.AssignStmt fieldRefAssign2 = soot.jimple.Jimple.v().newAssignStmt(invokeLocal, fieldRef);
body.getUnits().add(fieldRefAssign2);
body.getUnits().add(nop2);
// boolean tests
soot.Local boolLocal1 = soot.jimple.Jimple.v().newLocal("$z0", soot.BooleanType.v());
body.getLocals().add(boolLocal1);
soot.Local boolLocal2 = soot.jimple.Jimple.v().newLocal("$z1", soot.BooleanType.v());
body.getLocals().add(boolLocal2);
// virtual invoke
soot.SootMethodRef vMethodToInvoke = Scene.v().makeMethodRef(soot.Scene.v().getSootClass("java.lang.Class"), "desiredAssertionStatus", new ArrayList(), soot.BooleanType.v(), true);
soot.jimple.VirtualInvokeExpr vInvoke = soot.jimple.Jimple.v().newVirtualInvokeExpr(invokeLocal, vMethodToInvoke, new ArrayList());
soot.jimple.AssignStmt testAssign = soot.jimple.Jimple.v().newAssignStmt(boolLocal1, vInvoke);
body.getUnits().add(testAssign);
// if
soot.jimple.ConditionExpr cond2 = soot.jimple.Jimple.v().newNeExpr(boolLocal1, soot.jimple.IntConstant.v(0));
soot.jimple.NopStmt nop3 = soot.jimple.Jimple.v().newNopStmt();
soot.jimple.IfStmt ifStmt2 = soot.jimple.Jimple.v().newIfStmt(cond2, nop3);
body.getUnits().add(ifStmt2);
// alternative
soot.jimple.AssignStmt altAssign = soot.jimple.Jimple.v().newAssignStmt(boolLocal2, soot.jimple.IntConstant.v(1));
body.getUnits().add(altAssign);
soot.jimple.NopStmt nop4 = soot.jimple.Jimple.v().newNopStmt();
soot.jimple.GotoStmt goto2 = soot.jimple.Jimple.v().newGotoStmt(nop4);
body.getUnits().add(goto2);
body.getUnits().add(nop3);
soot.jimple.AssignStmt conAssign = soot.jimple.Jimple.v().newAssignStmt(boolLocal2, soot.jimple.IntConstant.v(0));
body.getUnits().add(conAssign);
body.getUnits().add(nop4);
// field assign
soot.SootFieldRef fieldD = Scene.v().makeFieldRef(body.getMethod().getDeclaringClass(), "$assertionsDisabled", soot.BooleanType.v(), true);
soot.jimple.FieldRef fieldRefD = soot.jimple.Jimple.v().newStaticFieldRef(fieldD);
soot.jimple.AssignStmt fAssign = soot.jimple.Jimple.v().newAssignStmt(fieldRefD, boolLocal2);
body.getUnits().add(fAssign);
}
| public void addAssertInits(soot.Body body){
// if class is inner get desired assertion status from outer most class
soot.SootClass assertStatusClass = body.getMethod().getDeclaringClass();
HashMap innerMap = soot.javaToJimple.InitialResolver.v().getInnerClassInfoMap();
while ((innerMap != null) && (innerMap.containsKey(assertStatusClass))){
assertStatusClass = ((InnerClassInfo)innerMap.get(assertStatusClass)).getOuterClass();
}
// field ref
soot.SootFieldRef field = soot.Scene.v().makeFieldRef(assertStatusClass, "class$"+assertStatusClass.getName(), soot.RefType.v("java.lang.Class"), true);
soot.Local fieldLocal = soot.jimple.Jimple.v().newLocal("$r0", soot.RefType.v("java.lang.Class"));
body.getLocals().add(fieldLocal);
soot.jimple.FieldRef fieldRef = soot.jimple.Jimple.v().newStaticFieldRef(field);
soot.jimple.AssignStmt fieldAssignStmt = soot.jimple.Jimple.v().newAssignStmt(fieldLocal, fieldRef);
body.getUnits().add(fieldAssignStmt);
// if field not null
soot.jimple.ConditionExpr cond = soot.jimple.Jimple.v().newNeExpr(fieldLocal, soot.jimple.NullConstant.v());
soot.jimple.NopStmt nop1 = soot.jimple.Jimple.v().newNopStmt();
soot.jimple.IfStmt ifStmt = soot.jimple.Jimple.v().newIfStmt(cond, nop1);
body.getUnits().add(ifStmt);
// if alternative
soot.Local invokeLocal = soot.jimple.Jimple.v().newLocal("$r1", soot.RefType.v("java.lang.Class"));
body.getLocals().add(invokeLocal);
ArrayList paramTypes = new ArrayList();
paramTypes.add(soot.RefType.v("java.lang.String"));
soot.SootMethodRef methodToInvoke = soot.Scene.v().makeMethodRef(assertStatusClass, "class$", paramTypes, soot.RefType.v("java.lang.Class"), true);
ArrayList params = new ArrayList();
params.add(soot.jimple.StringConstant.v(assertStatusClass.getName()));
soot.jimple.StaticInvokeExpr invoke = soot.jimple.Jimple.v().newStaticInvokeExpr(methodToInvoke, params);
soot.jimple.AssignStmt invokeAssign = soot.jimple.Jimple.v().newAssignStmt(invokeLocal, invoke);
body.getUnits().add(invokeAssign);
// field ref assign
soot.jimple.AssignStmt fieldRefAssign = soot.jimple.Jimple.v().newAssignStmt(fieldRef, invokeLocal);
body.getUnits().add(fieldRefAssign);
soot.jimple.NopStmt nop2 = soot.jimple.Jimple.v().newNopStmt();
soot.jimple.GotoStmt goto1 = soot.jimple.Jimple.v().newGotoStmt(nop2);
body.getUnits().add(goto1);
// add nop1 - and if consequence
body.getUnits().add(nop1);
soot.jimple.AssignStmt fieldRefAssign2 = soot.jimple.Jimple.v().newAssignStmt(invokeLocal, fieldRef);
body.getUnits().add(fieldRefAssign2);
body.getUnits().add(nop2);
// boolean tests
soot.Local boolLocal1 = soot.jimple.Jimple.v().newLocal("$z0", soot.BooleanType.v());
body.getLocals().add(boolLocal1);
soot.Local boolLocal2 = soot.jimple.Jimple.v().newLocal("$z1", soot.BooleanType.v());
body.getLocals().add(boolLocal2);
// virtual invoke
soot.SootMethodRef vMethodToInvoke = Scene.v().makeMethodRef(soot.Scene.v().getSootClass("java.lang.Class"), "desiredAssertionStatus", new ArrayList(), soot.BooleanType.v(), false);
soot.jimple.VirtualInvokeExpr vInvoke = soot.jimple.Jimple.v().newVirtualInvokeExpr(invokeLocal, vMethodToInvoke, new ArrayList());
soot.jimple.AssignStmt testAssign = soot.jimple.Jimple.v().newAssignStmt(boolLocal1, vInvoke);
body.getUnits().add(testAssign);
// if
soot.jimple.ConditionExpr cond2 = soot.jimple.Jimple.v().newNeExpr(boolLocal1, soot.jimple.IntConstant.v(0));
soot.jimple.NopStmt nop3 = soot.jimple.Jimple.v().newNopStmt();
soot.jimple.IfStmt ifStmt2 = soot.jimple.Jimple.v().newIfStmt(cond2, nop3);
body.getUnits().add(ifStmt2);
// alternative
soot.jimple.AssignStmt altAssign = soot.jimple.Jimple.v().newAssignStmt(boolLocal2, soot.jimple.IntConstant.v(1));
body.getUnits().add(altAssign);
soot.jimple.NopStmt nop4 = soot.jimple.Jimple.v().newNopStmt();
soot.jimple.GotoStmt goto2 = soot.jimple.Jimple.v().newGotoStmt(nop4);
body.getUnits().add(goto2);
body.getUnits().add(nop3);
soot.jimple.AssignStmt conAssign = soot.jimple.Jimple.v().newAssignStmt(boolLocal2, soot.jimple.IntConstant.v(0));
body.getUnits().add(conAssign);
body.getUnits().add(nop4);
// field assign
soot.SootFieldRef fieldD = Scene.v().makeFieldRef(body.getMethod().getDeclaringClass(), "$assertionsDisabled", soot.BooleanType.v(), true);
soot.jimple.FieldRef fieldRefD = soot.jimple.Jimple.v().newStaticFieldRef(fieldD);
soot.jimple.AssignStmt fAssign = soot.jimple.Jimple.v().newAssignStmt(fieldRefD, boolLocal2);
body.getUnits().add(fAssign);
}
|
diff --git a/org.eclipse.mylyn.tasks.core/src/org/eclipse/mylyn/internal/tasks/core/ScheduledTaskContainer.java b/org.eclipse.mylyn.tasks.core/src/org/eclipse/mylyn/internal/tasks/core/ScheduledTaskContainer.java
index af7a2126a..f1db7796d 100644
--- a/org.eclipse.mylyn.tasks.core/src/org/eclipse/mylyn/internal/tasks/core/ScheduledTaskContainer.java
+++ b/org.eclipse.mylyn.tasks.core/src/org/eclipse/mylyn/internal/tasks/core/ScheduledTaskContainer.java
@@ -1,286 +1,286 @@
/*******************************************************************************
* Copyright (c) 2004, 2010 Tasktop Technologies and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Tasktop Technologies - initial API and implementation
*******************************************************************************/
package org.eclipse.mylyn.internal.tasks.core;
import java.util.Calendar;
import java.util.Collection;
import java.util.HashSet;
import java.util.Set;
import org.eclipse.mylyn.tasks.core.IRepositoryElement;
import org.eclipse.mylyn.tasks.core.ITask;
/**
* @author Rob Elves
* @author Mik Kersten
*/
public class ScheduledTaskContainer extends AbstractTaskContainer {
private final TaskActivityManager activityManager;
private final String summary;
private final DateRange range;
public ScheduledTaskContainer(TaskActivityManager activityManager, DateRange range, String summary) {
super(summary == null ? range.toString(false) : summary);
this.activityManager = activityManager;
this.range = range;
if (summary == null) {
this.summary = range.toString(false);
} else {
this.summary = summary;
}
}
public ScheduledTaskContainer(TaskActivityManager taskActivityManager, DateRange day) {
this(taskActivityManager, day, null);
}
public boolean isFuture() {
return !isPresent() && range.getStartDate().after(Calendar.getInstance());
}
public boolean isPresent() {
return range.getStartDate().before(Calendar.getInstance()) && range.getEndDate().after(Calendar.getInstance());
}
// public boolean isWeekDay() {
// return TaskActivityUtil.getCurrentWeek().isCurrentWeekDay(range);
// }
// public boolean isToday() {
// if (range instanceof DayDateRange) {
// return ((DayDateRange) range).isToday();
// }
// return false;
// }
// public Collection<ITask> getChildren() {
// Set<ITask> children = new HashSet<ITask>();
// Calendar beginning = TaskActivityUtil.getCalendar();
// beginning.setTimeInMillis(0);
// if (isFloating() && !isFuture()) {
// for (ITask task : activityManager.getScheduledTasks(rangebeginning, getEndDate())) {
// if (task.internalIsFloatingScheduledDate()) {
// children.add(task);
// }
// }
// } else if (isPresent()) {
// // add all due/overdue
// Calendar end = TaskActivityUtil.getCalendar();
// end.set(5000, 12, 1);
// for (ITask task : activityManager.getDueTasks(beginning, getEndDate())) {
// if (activityManager.isOwnedByUser(task)) {
// children.add(task);
// }
// }
//
// // add all scheduled/overscheduled
// for (ITask task : activityManager.getScheduledTasks(beginning, getEndDate())) {
// if (!task.internalIsFloatingScheduledDate() && !task.isCompleted()) {
// children.add(task);
// }
// }
//
// // if not scheduled or due in future, and is active, place in today bin
// ITask activeTask = activityManager.getActiveTask();
// if (activeTask != null && !children.contains(activeTask)) {
// Set<ITask> futureScheduled = activityManager.getScheduledTasks(getStartDate(), end);
// for (ITask task : activityManager.getDueTasks(getStartDate(), end)) {
// if (activityManager.isOwnedByUser(task)) {
// futureScheduled.add(task);
// }
// }
// if (!futureScheduled.contains(activeTask)) {
// children.add(activeTask);
// }
// }
// } else if (isFuture()) {
// children.addAll(activityManager.getScheduledTasks(getStartDate(), getEndDate()));
// for (ITask task : activityManager.getDueTasks(getStartDate(), getEndDate())) {
// if (activityManager.isOwnedByUser(task)) {
// children.add(task);
// }
// }
// } else {
// children.addAll(activityManager.getActiveTasks(range.getStartDate(), range.getEndDate()));
// }
// return children;
// }
@Override
public Collection<ITask> getChildren() {
// TODO: Cache this information until the next modification to pertinent data
Set<ITask> children = new HashSet<ITask>();
Calendar cal = TaskActivityUtil.getCalendar();
// All tasks scheduled for this date range
for (ITask task : activityManager.getScheduledTasks(range)) {
if (!task.isCompleted() || isCompletedToday(task)) {
if (isDueBeforeScheduled(task) && activityManager.isOwnedByUser(task)) {
continue;
}
if (isThisWeekBin() && isScheduledForAWeek(task)) {
// is due this week
if (task.getDueDate() != null) {
cal.setTime(task.getDueDate());
- if (range.includes(cal)) {
+ if (range.includes(cal) && activityManager.isOwnedByUser(task)) {
continue;
}
}
addChild(children, task);
}
addChild(children, task);
}
}
// Add due tasks if not the This Week container, and not scheduled for earlier date
if (!(range instanceof WeekDateRange && ((WeekDateRange) range).isPresent())) {
for (ITask task : getTasksDueThisWeek()) {
if (isScheduledBeforeDue(task)) {
continue;
}
if (activityManager.isOwnedByUser(task)) {
addChild(children, task);
}
}
}
// All over due/scheduled tasks are present in the Today folder
if (isTodayBin()) {
for (ITask task : activityManager.getOverScheduledTasks()) {
if (isScheduledForADay(task)) {
addChild(children, task);
}
}
for (ITask task : activityManager.getOverDueTasks()) {
addChild(children, task);
}
// if not scheduled or due in future, and is active, place in today bin
ITask activeTask = activityManager.getActiveTask();
if (activeTask != null && !children.contains(activeTask)) {
addChild(children, activeTask);
}
}
if (range instanceof WeekDateRange && ((WeekDateRange) range).isThisWeek()) {
for (ITask task : activityManager.getOverScheduledTasks()) {
if (isScheduledForAWeek(task)) {
addChild(children, task);
}
}
}
return children;
}
private boolean isTodayBin() {
return range instanceof DayDateRange && ((DayDateRange) range).isPresent();
}
private boolean isThisWeekBin() {
return range instanceof WeekDateRange && ((WeekDateRange) range).isThisWeek();
}
private Set<ITask> getTasksDueThisWeek() {
return activityManager.getDueTasks(range.getStartDate(), range.getEndDate());
}
private boolean isScheduledForAWeek(ITask task) {
return task instanceof AbstractTask && ((AbstractTask) task).getScheduledForDate() instanceof WeekDateRange;
}
private boolean isDueBeforeScheduled(ITask task) {
return task.getDueDate() != null
&& task.getDueDate().before(((AbstractTask) task).getScheduledForDate().getStartDate().getTime());
}
private boolean isScheduledForADay(ITask task) {
return task instanceof AbstractTask && !(((AbstractTask) task).getScheduledForDate() instanceof WeekDateRange);
}
private boolean isScheduledBeforeDue(ITask task) {
return ((AbstractTask) task).getScheduledForDate() != null
&& ((AbstractTask) task).getScheduledForDate().before(range.getStartDate());
}
private boolean isCompletedToday(ITask task) {
return (task.isCompleted() && TaskActivityUtil.getDayOf(task.getCompletionDate()).isPresent());
}
private void addChild(Set<ITask> collection, ITask task) {
// if (task.getSynchronizationState().isOutgoing()) {
// return;
// }
collection.add(task);
}
@Override
public String getSummary() {
if (summary != null) {
return summary;
}
return range.toString();
}
@Override
public String getHandleIdentifier() {
return summary;
}
@Override
public String getPriority() {
return ""; //$NON-NLS-1$
}
@Override
public String getUrl() {
return ""; //$NON-NLS-1$
}
@Override
public int compareTo(IRepositoryElement element) {
if (element instanceof ScheduledTaskContainer) {
ScheduledTaskContainer container = ((ScheduledTaskContainer) element);
return range.compareTo(container.getDateRange());
}
return 0;
}
public DateRange getDateRange() {
return range;
}
public Calendar getEnd() {
return range.getEndDate();
}
public Calendar getStart() {
return range.getStartDate();
}
public boolean includes(Calendar pastWeeksTaskStart) {
return range.includes(pastWeeksTaskStart);
}
}
| true | true | public Collection<ITask> getChildren() {
// TODO: Cache this information until the next modification to pertinent data
Set<ITask> children = new HashSet<ITask>();
Calendar cal = TaskActivityUtil.getCalendar();
// All tasks scheduled for this date range
for (ITask task : activityManager.getScheduledTasks(range)) {
if (!task.isCompleted() || isCompletedToday(task)) {
if (isDueBeforeScheduled(task) && activityManager.isOwnedByUser(task)) {
continue;
}
if (isThisWeekBin() && isScheduledForAWeek(task)) {
// is due this week
if (task.getDueDate() != null) {
cal.setTime(task.getDueDate());
if (range.includes(cal)) {
continue;
}
}
addChild(children, task);
}
addChild(children, task);
}
}
// Add due tasks if not the This Week container, and not scheduled for earlier date
if (!(range instanceof WeekDateRange && ((WeekDateRange) range).isPresent())) {
for (ITask task : getTasksDueThisWeek()) {
if (isScheduledBeforeDue(task)) {
continue;
}
if (activityManager.isOwnedByUser(task)) {
addChild(children, task);
}
}
}
// All over due/scheduled tasks are present in the Today folder
if (isTodayBin()) {
for (ITask task : activityManager.getOverScheduledTasks()) {
if (isScheduledForADay(task)) {
addChild(children, task);
}
}
for (ITask task : activityManager.getOverDueTasks()) {
addChild(children, task);
}
// if not scheduled or due in future, and is active, place in today bin
ITask activeTask = activityManager.getActiveTask();
if (activeTask != null && !children.contains(activeTask)) {
addChild(children, activeTask);
}
}
if (range instanceof WeekDateRange && ((WeekDateRange) range).isThisWeek()) {
for (ITask task : activityManager.getOverScheduledTasks()) {
if (isScheduledForAWeek(task)) {
addChild(children, task);
}
}
}
return children;
}
| public Collection<ITask> getChildren() {
// TODO: Cache this information until the next modification to pertinent data
Set<ITask> children = new HashSet<ITask>();
Calendar cal = TaskActivityUtil.getCalendar();
// All tasks scheduled for this date range
for (ITask task : activityManager.getScheduledTasks(range)) {
if (!task.isCompleted() || isCompletedToday(task)) {
if (isDueBeforeScheduled(task) && activityManager.isOwnedByUser(task)) {
continue;
}
if (isThisWeekBin() && isScheduledForAWeek(task)) {
// is due this week
if (task.getDueDate() != null) {
cal.setTime(task.getDueDate());
if (range.includes(cal) && activityManager.isOwnedByUser(task)) {
continue;
}
}
addChild(children, task);
}
addChild(children, task);
}
}
// Add due tasks if not the This Week container, and not scheduled for earlier date
if (!(range instanceof WeekDateRange && ((WeekDateRange) range).isPresent())) {
for (ITask task : getTasksDueThisWeek()) {
if (isScheduledBeforeDue(task)) {
continue;
}
if (activityManager.isOwnedByUser(task)) {
addChild(children, task);
}
}
}
// All over due/scheduled tasks are present in the Today folder
if (isTodayBin()) {
for (ITask task : activityManager.getOverScheduledTasks()) {
if (isScheduledForADay(task)) {
addChild(children, task);
}
}
for (ITask task : activityManager.getOverDueTasks()) {
addChild(children, task);
}
// if not scheduled or due in future, and is active, place in today bin
ITask activeTask = activityManager.getActiveTask();
if (activeTask != null && !children.contains(activeTask)) {
addChild(children, activeTask);
}
}
if (range instanceof WeekDateRange && ((WeekDateRange) range).isThisWeek()) {
for (ITask task : activityManager.getOverScheduledTasks()) {
if (isScheduledForAWeek(task)) {
addChild(children, task);
}
}
}
return children;
}
|
diff --git a/ngrinder-controller/src/main/java/org/ngrinder/chart/controller/MonitorController.java b/ngrinder-controller/src/main/java/org/ngrinder/chart/controller/MonitorController.java
index 4582d604..b9ce0f32 100644
--- a/ngrinder-controller/src/main/java/org/ngrinder/chart/controller/MonitorController.java
+++ b/ngrinder-controller/src/main/java/org/ngrinder/chart/controller/MonitorController.java
@@ -1,248 +1,248 @@
/*
* Copyright (C) 2012 - 2012 NHN Corporation
* All rights reserved.
*
* This file is part of The nGrinder software distribution. Refer to
* the file LICENSE which is part of The nGrinder distribution for
* licensing details. The nGrinder distribution is available on the
* Internet at http://nhnopensource.org/ngrinder
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDERS OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,
* INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*/
package org.ngrinder.chart.controller;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.math.NumberUtils;
import org.ngrinder.chart.services.MonitorService;
import org.ngrinder.common.controller.NGrinderBaseController;
import org.ngrinder.common.util.JSONUtil;
import org.ngrinder.monitor.controller.model.JavaDataModel;
import org.ngrinder.monitor.controller.model.SystemDataModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* Class description.
*
* @author Mavlarn
* @since
*/
@Controller
@RequestMapping("/monitor")
public class MonitorController extends NGrinderBaseController {
@SuppressWarnings("unused")
private static final Logger LOG = LoggerFactory.getLogger(MonitorController.class);
private static final String DATE_FORMAT = "yyyyMMddHHmmss";
private static final DateFormat df = new SimpleDateFormat(DATE_FORMAT);
@Autowired
private MonitorService monitorService;
/**
* get chart data(like tps, vuser) of test
*
* @param model
* @param chartTypes
* is some chart type combined wit ',', eg. "tps,errors,vusers".
* @return
*/
@RequestMapping("/chart")
public @ResponseBody
String getChartData(ModelMap model, @RequestParam(required = false) String[] chartTypes) {
return null;
}
/**
* get monitor data of agents
*
* @param model
* @param ip
* @param startTime
* @param finishTime
* @param imgWidth
* @return
*/
@RequestMapping("/getMonitorData")
public @ResponseBody
String getMonitorData(ModelMap model, @RequestParam String ip, @RequestParam(required = false) Date startTime,
@RequestParam(required = false) Date finishTime, @RequestParam int imgWidth) {
if (null == finishTime) {
finishTime = new Date();
}
if (null == startTime) {
startTime = new Date(finishTime.getTime() - 30 * 1000);
}
DateFormat df = new SimpleDateFormat(DATE_FORMAT);
long st = NumberUtils.toLong(df.format(startTime));
long et = NumberUtils.toLong(df.format(finishTime));
Map<String, Object> rtnMap = new HashMap<String, Object>(7);
this.getMonitorDataJava(rtnMap, ip, st, et, imgWidth);
this.getMonitorDataSystem(rtnMap, ip, st, et, imgWidth);
rtnMap.put(JSON_SUCCESS, true);
rtnMap.put("startTime", startTime);
return JSONUtil.toJson(rtnMap);
}
/**
* get java monitor data of agents
*
* @param model
* @param ip
* @param startTime
* @param finishTime
* @param imgWidth
* @return
*/
@RequestMapping("/getMonitorDataJava")
public @ResponseBody
String getMonitorDataJava(ModelMap model, @RequestParam String ip, @RequestParam(required = false) Date startTime,
@RequestParam(required = false) Date finishTime, @RequestParam int imgWidth) {
if (null == finishTime) {
finishTime = new Date();
}
if (null == startTime) {
startTime = new Date(finishTime.getTime() - 30 * 1000);
}
DateFormat df = new SimpleDateFormat(DATE_FORMAT);
long st = NumberUtils.toLong(df.format(startTime));
long et = NumberUtils.toLong(df.format(finishTime));
Map<String, Object> rtnMap = new HashMap<String, Object>(5);
this.getMonitorDataJava(rtnMap, ip, st, et, imgWidth);
rtnMap.put(JSON_SUCCESS, true);
return JSONUtil.toJson(rtnMap);
}
/**
* get system monitor data of agents
*
* @param model
* @param ip
* @param startTime
* @param finishTime
* @param imgWidth
* @return
*/
@RequestMapping("/getMonitorDataSystem")
public @ResponseBody
String getMonitorDataSystem(ModelMap model, @RequestParam String ip,
@RequestParam(required = false) Date startTime, @RequestParam(required = false) Date finishTime,
@RequestParam int imgWidth) {
if (null == finishTime) {
finishTime = new Date();
}
if (null == startTime) {
startTime = new Date(finishTime.getTime() - 30 * 1000);
}
long st = NumberUtils.toLong(df.format(startTime));
long et = NumberUtils.toLong(df.format(finishTime));
Map<String, Object> rtnMap = new HashMap<String, Object>(3);
this.getMonitorDataSystem(rtnMap, ip, st, et, imgWidth);
rtnMap.put(JSON_SUCCESS, true);
return JSONUtil.toJson(rtnMap);
}
private void getMonitorDataJava(Map<String, Object> rtnMap, String ip, long startTime, long finishTime, int imgWidth) {
List<JavaDataModel> javaMonitorData = monitorService.getJavaMonitorData(ip, startTime, finishTime);
- int pointCount = imgWidth / 10;
+ int pointCount = imgWidth / 10; // TODO: The imgWidth should be checked if it is less then 0, AND also pointCount should not be 0. (refer to org.ngrinder.perftest.service.PerfTestService)
int lineObject, current, interval = 0;
List<Object> heapMemoryData = new ArrayList<Object>(pointCount);
List<Object> nonHeapMemoryData = new ArrayList<Object>(pointCount);
List<Object> threadCountData = new ArrayList<Object>(pointCount);
List<Object> jvmCpuData = new ArrayList<Object>(pointCount);
if (null != javaMonitorData && !javaMonitorData.isEmpty()) {
current = 0;
lineObject = javaMonitorData.size();
- interval = lineObject / pointCount;
+ interval = lineObject / pointCount; // TODO: The pointCount should not be 0. (refer to org.ngrinder.perftest.service.PerfTestService)
// TODO should get average data
for (JavaDataModel jdm : javaMonitorData) {
if (0 == current) {
heapMemoryData.add(jdm.getHeapUsedMemory());
nonHeapMemoryData.add(jdm.getNonHeapUsedMemory());
threadCountData.add(jdm.getThreadCount());
jvmCpuData.add(jdm.getCpuUsedPercentage() * 100);
}
if (++current >= interval) {
current = 0;
}
}
}
rtnMap.put("heap_memory", heapMemoryData);
rtnMap.put("non_heap_memory", nonHeapMemoryData);
rtnMap.put("thread_count", threadCountData);
rtnMap.put("jvm_cpu", jvmCpuData);
rtnMap.put("interval", interval);
}
private void getMonitorDataSystem(Map<String, Object> rtnMap, String ip, long startTime, long finishTime,
int imgWidth) {
List<SystemDataModel> systemMonitorData = monitorService.getSystemMonitorData(ip, startTime, finishTime);
int pointCount = imgWidth / 10;
int lineObject, current, interval = 0;
List<Object> cpuData = new ArrayList<Object>(pointCount);
List<Object> memoryData = new ArrayList<Object>(pointCount);
if (null != systemMonitorData && !systemMonitorData.isEmpty()) {
current = 0;
lineObject = systemMonitorData.size();
interval = lineObject / pointCount;
// TODO should get average data
for (SystemDataModel sdm : systemMonitorData) {
if (0 == current) {
cpuData.add(sdm.getCpuUsedPercentage() * 100);
memoryData.add(sdm.getTotalMemory() - sdm.getFreeMemory());
}
if (++current >= interval) {
current = 0;
}
}
}
rtnMap.put("cpu", cpuData);
rtnMap.put("memory", memoryData);
rtnMap.put("interval", interval);
}
}
| false | true | private void getMonitorDataJava(Map<String, Object> rtnMap, String ip, long startTime, long finishTime, int imgWidth) {
List<JavaDataModel> javaMonitorData = monitorService.getJavaMonitorData(ip, startTime, finishTime);
int pointCount = imgWidth / 10;
int lineObject, current, interval = 0;
List<Object> heapMemoryData = new ArrayList<Object>(pointCount);
List<Object> nonHeapMemoryData = new ArrayList<Object>(pointCount);
List<Object> threadCountData = new ArrayList<Object>(pointCount);
List<Object> jvmCpuData = new ArrayList<Object>(pointCount);
if (null != javaMonitorData && !javaMonitorData.isEmpty()) {
current = 0;
lineObject = javaMonitorData.size();
interval = lineObject / pointCount;
// TODO should get average data
for (JavaDataModel jdm : javaMonitorData) {
if (0 == current) {
heapMemoryData.add(jdm.getHeapUsedMemory());
nonHeapMemoryData.add(jdm.getNonHeapUsedMemory());
threadCountData.add(jdm.getThreadCount());
jvmCpuData.add(jdm.getCpuUsedPercentage() * 100);
}
if (++current >= interval) {
current = 0;
}
}
}
rtnMap.put("heap_memory", heapMemoryData);
rtnMap.put("non_heap_memory", nonHeapMemoryData);
rtnMap.put("thread_count", threadCountData);
rtnMap.put("jvm_cpu", jvmCpuData);
rtnMap.put("interval", interval);
}
| private void getMonitorDataJava(Map<String, Object> rtnMap, String ip, long startTime, long finishTime, int imgWidth) {
List<JavaDataModel> javaMonitorData = monitorService.getJavaMonitorData(ip, startTime, finishTime);
int pointCount = imgWidth / 10; // TODO: The imgWidth should be checked if it is less then 0, AND also pointCount should not be 0. (refer to org.ngrinder.perftest.service.PerfTestService)
int lineObject, current, interval = 0;
List<Object> heapMemoryData = new ArrayList<Object>(pointCount);
List<Object> nonHeapMemoryData = new ArrayList<Object>(pointCount);
List<Object> threadCountData = new ArrayList<Object>(pointCount);
List<Object> jvmCpuData = new ArrayList<Object>(pointCount);
if (null != javaMonitorData && !javaMonitorData.isEmpty()) {
current = 0;
lineObject = javaMonitorData.size();
interval = lineObject / pointCount; // TODO: The pointCount should not be 0. (refer to org.ngrinder.perftest.service.PerfTestService)
// TODO should get average data
for (JavaDataModel jdm : javaMonitorData) {
if (0 == current) {
heapMemoryData.add(jdm.getHeapUsedMemory());
nonHeapMemoryData.add(jdm.getNonHeapUsedMemory());
threadCountData.add(jdm.getThreadCount());
jvmCpuData.add(jdm.getCpuUsedPercentage() * 100);
}
if (++current >= interval) {
current = 0;
}
}
}
rtnMap.put("heap_memory", heapMemoryData);
rtnMap.put("non_heap_memory", nonHeapMemoryData);
rtnMap.put("thread_count", threadCountData);
rtnMap.put("jvm_cpu", jvmCpuData);
rtnMap.put("interval", interval);
}
|
diff --git a/src/main/java/edu/rit/asksg/web/ConversationController.java b/src/main/java/edu/rit/asksg/web/ConversationController.java
index 837b369..9f7092e 100755
--- a/src/main/java/edu/rit/asksg/web/ConversationController.java
+++ b/src/main/java/edu/rit/asksg/web/ConversationController.java
@@ -1,179 +1,179 @@
package edu.rit.asksg.web;
import edu.rit.asksg.common.Log;
import edu.rit.asksg.dataio.ScheduledPocessor;
import edu.rit.asksg.domain.Conversation;
import edu.rit.asksg.domain.Email;
import edu.rit.asksg.domain.Facebook;
import edu.rit.asksg.domain.Message;
import edu.rit.asksg.domain.Reddit;
import edu.rit.asksg.domain.Service;
import edu.rit.asksg.domain.SocialSubscription;
import edu.rit.asksg.domain.Twilio;
import edu.rit.asksg.domain.Twitter;
import edu.rit.asksg.domain.config.EmailConfig;
import edu.rit.asksg.domain.config.ProviderConfig;
import edu.rit.asksg.domain.config.SpringSocialConfig;
import edu.rit.asksg.domain.config.TwilioConfig;
import edu.rit.asksg.service.ProviderService;
import org.slf4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.roo.addon.web.mvc.controller.json.RooWebJson;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
@RooWebJson(jsonObject = Conversation.class)
@Controller
@RequestMapping("/conversations")
public class ConversationController {
@Log
private Logger logger;
@Autowired
ProviderService providerService;
@Autowired
ScheduledPocessor scheduledPocessor;
@RequestMapping(value = "/seed")
public ResponseEntity<String> seed() {
bootstrapProviders();
Conversation c = new Conversation();
Message m1 = new Message();
m1.setAuthor("Socrates");
m1.setContent("For the unexamined life is not worth living");
Message m2 = new Message();
m2.setAuthor("Tyrion Lannister");
m2.setContent("Sorcery is the sauce fools spoon over failure to hide the flavor of the their own incompetence");
Set<Message> messages = new HashSet<Message>();
messages.add(m1);
messages.add(m2);
c.setMessages(messages);
Service twilioprovider = providerService.findServiceByTypeAndIdentifierEquals(Twilio.class, "37321");
c.setService(twilioprovider);
conversationService.saveConversation(c);
pullContent();
HttpHeaders headers = new HttpHeaders();
headers.add("content_type", "text/plain");
return new ResponseEntity<String>("your seed has been spread", headers, HttpStatus.OK);
}
private void bootstrapProviders() {
- final Service twiloprovider = providerService.findServiceByTypeAndIdentifierEquals(Twilio.class, "5852865275");
+ final Service twiloprovider = providerService.findServiceByTypeAndIdentifierEquals(Twilio.class, "+15852865275");
if (twiloprovider == null) {
Service twilio = new Twilio();
TwilioConfig twilioconfig = new TwilioConfig();
- twilioconfig.setIdentifier("5852865275");
- twilioconfig.setPhoneNumber("5852865275");
+ twilioconfig.setIdentifier("+15852865275");
+ twilioconfig.setPhoneNumber("+15852865275");
twilioconfig.setUsername("AC932da9adfecf700aba37dba458fc9621");
twilioconfig.setAuthenticationToken("9cda6e23aa46651c9759492b625e3f35");
twilio.setConfig(twilioconfig);
providerService.saveService(twilio);
}
final Service emailProvider = providerService.findServiceByTypeAndIdentifierEquals(Email.class, "ritasksg");
if (emailProvider == null) {
Service email = new Email();
EmailConfig emailConfig = new EmailConfig();
emailConfig.setIdentifier("ritasksg");
emailConfig.setUsername("[email protected]");
emailConfig.setPassword("allHailSpring");
email.setConfig(emailConfig);
providerService.saveService(email);
}
final Service twitterProvider = providerService.findServiceByTypeAndIdentifierEquals(Twitter.class, "wY0Aft0Gz410RtOqOHd7Q");
if (twitterProvider == null) {
Service twitter = new Twitter();
SpringSocialConfig twitterConfig = new SpringSocialConfig();
twitterConfig.setIdentifier("wY0Aft0Gz410RtOqOHd7Q");
twitterConfig.setConsumerKey("wY0Aft0Gz410RtOqOHd7Q");
twitterConfig.setConsumerSecret("rMxrTP9nqPzwU6UHIQufKR23be4w4NHIqY7VbwfzU");
twitterConfig.setAccessToken("15724679-FUz0huThLIpEzm66QySG7exllaV1CWV9VqXxXeTOw");
twitterConfig.setAccessTokenSecret("rFTEFz8tNX71V2nCo6pDtF38LhDEfO2f692xxzQxaA");
twitter.setConfig(twitterConfig);
SocialSubscription ritsg = new SocialSubscription();
ritsg.setHandle("RIT_SG");
SocialSubscription ritHash = new SocialSubscription();
ritHash.setHandle("#RIT");
Set<SocialSubscription> subscriptions = new HashSet<SocialSubscription>();
subscriptions.add(ritsg);
subscriptions.add(ritHash);
twitterConfig.setSubscriptions(subscriptions);
providerService.saveService(twitter);
}
final Service facebookProvider = providerService.findServiceByTypeAndIdentifierEquals(Facebook.class, "asksgfbapp");
if (facebookProvider == null) {
Service facebook = new Facebook();
SpringSocialConfig fbConfig = new SpringSocialConfig();
fbConfig.setIdentifier("asksgfbapp");
facebook.setConfig(fbConfig);
}
final Service redditProvider = providerService.findServiceByTypeAndIdentifierEquals(Reddit.class, "rit");
if (redditProvider == null) {
Service reddit = new Reddit();
ProviderConfig config = new ProviderConfig();
config.setIdentifier("rit");
reddit.setConfig(config);
SocialSubscription java = new SocialSubscription();
java.setHandle("java");
Set<SocialSubscription> subscriptions = new HashSet<SocialSubscription>();
subscriptions.add(java);
config.setSubscriptions(subscriptions);
providerService.saveService(reddit);
}
}
@RequestMapping(value = "/tweet")
public ResponseEntity<String> twats() {
Service twitter = providerService.findServiceByTypeAndIdentifierEquals(Twitter.class, "wY0Aft0Gz410RtOqOHd7Q");
List<Conversation> twats = twitter.getNewContent();
for (Conversation c : twats) {
//conversationService.saveConversation(c);
}
HttpHeaders headers = new HttpHeaders();
headers.add("content_type", "text/plain");
return new ResponseEntity<String>("Show me your tweets!", headers, HttpStatus.OK);
}
protected void pullContent() {
scheduledPocessor.executeRefresh();
scheduledPocessor.executeSubscriptions();
}
}
| false | true | private void bootstrapProviders() {
final Service twiloprovider = providerService.findServiceByTypeAndIdentifierEquals(Twilio.class, "5852865275");
if (twiloprovider == null) {
Service twilio = new Twilio();
TwilioConfig twilioconfig = new TwilioConfig();
twilioconfig.setIdentifier("5852865275");
twilioconfig.setPhoneNumber("5852865275");
twilioconfig.setUsername("AC932da9adfecf700aba37dba458fc9621");
twilioconfig.setAuthenticationToken("9cda6e23aa46651c9759492b625e3f35");
twilio.setConfig(twilioconfig);
providerService.saveService(twilio);
}
final Service emailProvider = providerService.findServiceByTypeAndIdentifierEquals(Email.class, "ritasksg");
if (emailProvider == null) {
Service email = new Email();
EmailConfig emailConfig = new EmailConfig();
emailConfig.setIdentifier("ritasksg");
emailConfig.setUsername("[email protected]");
emailConfig.setPassword("allHailSpring");
email.setConfig(emailConfig);
providerService.saveService(email);
}
final Service twitterProvider = providerService.findServiceByTypeAndIdentifierEquals(Twitter.class, "wY0Aft0Gz410RtOqOHd7Q");
if (twitterProvider == null) {
Service twitter = new Twitter();
SpringSocialConfig twitterConfig = new SpringSocialConfig();
twitterConfig.setIdentifier("wY0Aft0Gz410RtOqOHd7Q");
twitterConfig.setConsumerKey("wY0Aft0Gz410RtOqOHd7Q");
twitterConfig.setConsumerSecret("rMxrTP9nqPzwU6UHIQufKR23be4w4NHIqY7VbwfzU");
twitterConfig.setAccessToken("15724679-FUz0huThLIpEzm66QySG7exllaV1CWV9VqXxXeTOw");
twitterConfig.setAccessTokenSecret("rFTEFz8tNX71V2nCo6pDtF38LhDEfO2f692xxzQxaA");
twitter.setConfig(twitterConfig);
SocialSubscription ritsg = new SocialSubscription();
ritsg.setHandle("RIT_SG");
SocialSubscription ritHash = new SocialSubscription();
ritHash.setHandle("#RIT");
Set<SocialSubscription> subscriptions = new HashSet<SocialSubscription>();
subscriptions.add(ritsg);
subscriptions.add(ritHash);
twitterConfig.setSubscriptions(subscriptions);
providerService.saveService(twitter);
}
final Service facebookProvider = providerService.findServiceByTypeAndIdentifierEquals(Facebook.class, "asksgfbapp");
if (facebookProvider == null) {
Service facebook = new Facebook();
SpringSocialConfig fbConfig = new SpringSocialConfig();
fbConfig.setIdentifier("asksgfbapp");
facebook.setConfig(fbConfig);
}
final Service redditProvider = providerService.findServiceByTypeAndIdentifierEquals(Reddit.class, "rit");
if (redditProvider == null) {
Service reddit = new Reddit();
ProviderConfig config = new ProviderConfig();
config.setIdentifier("rit");
reddit.setConfig(config);
SocialSubscription java = new SocialSubscription();
java.setHandle("java");
Set<SocialSubscription> subscriptions = new HashSet<SocialSubscription>();
subscriptions.add(java);
config.setSubscriptions(subscriptions);
providerService.saveService(reddit);
}
}
| private void bootstrapProviders() {
final Service twiloprovider = providerService.findServiceByTypeAndIdentifierEquals(Twilio.class, "+15852865275");
if (twiloprovider == null) {
Service twilio = new Twilio();
TwilioConfig twilioconfig = new TwilioConfig();
twilioconfig.setIdentifier("+15852865275");
twilioconfig.setPhoneNumber("+15852865275");
twilioconfig.setUsername("AC932da9adfecf700aba37dba458fc9621");
twilioconfig.setAuthenticationToken("9cda6e23aa46651c9759492b625e3f35");
twilio.setConfig(twilioconfig);
providerService.saveService(twilio);
}
final Service emailProvider = providerService.findServiceByTypeAndIdentifierEquals(Email.class, "ritasksg");
if (emailProvider == null) {
Service email = new Email();
EmailConfig emailConfig = new EmailConfig();
emailConfig.setIdentifier("ritasksg");
emailConfig.setUsername("[email protected]");
emailConfig.setPassword("allHailSpring");
email.setConfig(emailConfig);
providerService.saveService(email);
}
final Service twitterProvider = providerService.findServiceByTypeAndIdentifierEquals(Twitter.class, "wY0Aft0Gz410RtOqOHd7Q");
if (twitterProvider == null) {
Service twitter = new Twitter();
SpringSocialConfig twitterConfig = new SpringSocialConfig();
twitterConfig.setIdentifier("wY0Aft0Gz410RtOqOHd7Q");
twitterConfig.setConsumerKey("wY0Aft0Gz410RtOqOHd7Q");
twitterConfig.setConsumerSecret("rMxrTP9nqPzwU6UHIQufKR23be4w4NHIqY7VbwfzU");
twitterConfig.setAccessToken("15724679-FUz0huThLIpEzm66QySG7exllaV1CWV9VqXxXeTOw");
twitterConfig.setAccessTokenSecret("rFTEFz8tNX71V2nCo6pDtF38LhDEfO2f692xxzQxaA");
twitter.setConfig(twitterConfig);
SocialSubscription ritsg = new SocialSubscription();
ritsg.setHandle("RIT_SG");
SocialSubscription ritHash = new SocialSubscription();
ritHash.setHandle("#RIT");
Set<SocialSubscription> subscriptions = new HashSet<SocialSubscription>();
subscriptions.add(ritsg);
subscriptions.add(ritHash);
twitterConfig.setSubscriptions(subscriptions);
providerService.saveService(twitter);
}
final Service facebookProvider = providerService.findServiceByTypeAndIdentifierEquals(Facebook.class, "asksgfbapp");
if (facebookProvider == null) {
Service facebook = new Facebook();
SpringSocialConfig fbConfig = new SpringSocialConfig();
fbConfig.setIdentifier("asksgfbapp");
facebook.setConfig(fbConfig);
}
final Service redditProvider = providerService.findServiceByTypeAndIdentifierEquals(Reddit.class, "rit");
if (redditProvider == null) {
Service reddit = new Reddit();
ProviderConfig config = new ProviderConfig();
config.setIdentifier("rit");
reddit.setConfig(config);
SocialSubscription java = new SocialSubscription();
java.setHandle("java");
Set<SocialSubscription> subscriptions = new HashSet<SocialSubscription>();
subscriptions.add(java);
config.setSubscriptions(subscriptions);
providerService.saveService(reddit);
}
}
|
diff --git a/src/org/opensolaris/opengrok/analysis/AnalyzerGuru.java b/src/org/opensolaris/opengrok/analysis/AnalyzerGuru.java
index e97b12cf..9068f82c 100644
--- a/src/org/opensolaris/opengrok/analysis/AnalyzerGuru.java
+++ b/src/org/opensolaris/opengrok/analysis/AnalyzerGuru.java
@@ -1,562 +1,564 @@
/*
* CDDL HEADER START
*
* The contents of this file are subject to the terms of the
* Common Development and Distribution License (the "License").
* You may not use this file except in compliance with the License.
*
* See LICENSE.txt included in this distribution for the specific
* language governing permissions and limitations under the License.
*
* When distributing Covered Code, include this CDDL HEADER in each
* file and include the License file at LICENSE.txt.
* If applicable, add the following below this CDDL HEADER, with the
* fields enclosed by brackets "[]" replaced with your own identifying
* information: Portions Copyright [yyyy] [name of copyright owner]
*
* CDDL HEADER END
*/
/*
* Copyright 2007 Sun Microsystems, Inc. All rights reserved.
* Use is subject to license terms.
*/
package org.opensolaris.opengrok.analysis;
import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStreamWriter;
import java.io.Reader;
import java.io.StringReader;
import java.io.Writer;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.SortedMap;
import java.util.TreeMap;
import org.apache.lucene.analysis.Token;
import org.apache.lucene.analysis.TokenStream;
import org.apache.lucene.document.DateTools;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.Field;
import org.opensolaris.opengrok.analysis.FileAnalyzer.Genre;
import org.opensolaris.opengrok.analysis.archive.BZip2AnalyzerFactory;
import org.opensolaris.opengrok.analysis.archive.GZIPAnalyzerFactory;
import org.opensolaris.opengrok.analysis.archive.TarAnalyzerFactory;
import org.opensolaris.opengrok.analysis.archive.ZipAnalyzerFactory;
import org.opensolaris.opengrok.analysis.c.CAnalyzerFactory;
import org.opensolaris.opengrok.analysis.data.IgnorantAnalyzerFactory;
import org.opensolaris.opengrok.analysis.data.ImageAnalyzerFactory;
import org.opensolaris.opengrok.analysis.document.TroffAnalyzerFactory;
import org.opensolaris.opengrok.analysis.executables.ELFAnalyzerFactory;
import org.opensolaris.opengrok.analysis.executables.JarAnalyzerFactory;
import org.opensolaris.opengrok.analysis.executables.JavaClassAnalyzerFactory;
import org.opensolaris.opengrok.analysis.java.JavaAnalyzerFactory;
import org.opensolaris.opengrok.analysis.lisp.LispAnalyzerFactory;
import org.opensolaris.opengrok.analysis.plain.PlainAnalyzerFactory;
import org.opensolaris.opengrok.analysis.plain.XMLAnalyzerFactory;
import org.opensolaris.opengrok.analysis.sh.ShAnalyzerFactory;
import org.opensolaris.opengrok.analysis.sql.SQLAnalyzerFactory;
import org.opensolaris.opengrok.analysis.tcl.TclAnalyzerFactory;
import org.opensolaris.opengrok.configuration.Project;
import org.opensolaris.opengrok.history.Annotation;
import org.opensolaris.opengrok.history.HistoryGuru;
import org.opensolaris.opengrok.history.HistoryReader;
import org.opensolaris.opengrok.web.Util;
/**
* Manages and porvides Analyzers as needed. Please see
* <a href="http://www.opensolaris.org/os/project/opengrok/manual/internals/">
* this</a> page for a great description of the purpose of the AnalyzerGuru.
*
* Created on September 22, 2005
* @author Chandan
*/
public class AnalyzerGuru {
/** The default {@code FileAnalyzerFactory} instance. */
private static final FileAnalyzerFactory
DEFAULT_ANALYZER_FACTORY = new FileAnalyzerFactory();
/** Map from file extensions to analyzer factories. */
private static final Map<String, FileAnalyzerFactory>
ext = new HashMap<String, FileAnalyzerFactory>();
// TODO: have a comparator
/** Map from magic strings to analyzer factories. */
private static final SortedMap<String, FileAnalyzerFactory>
magics = new TreeMap<String, FileAnalyzerFactory>();
/**
* List of matcher objects which can be used to determine which analyzer
* factory to use.
*/
private static final List<FileAnalyzerFactory.Matcher>
matchers = new ArrayList<FileAnalyzerFactory.Matcher>();
/** List of all registered {@code FileAnalyzerFactory} instances. */
private static final List<FileAnalyzerFactory>
factories = new ArrayList<FileAnalyzerFactory>();
/*
* If you write your own analyzer please register it here
*/
static {
FileAnalyzerFactory[] analyzers = {
DEFAULT_ANALYZER_FACTORY,
new IgnorantAnalyzerFactory(),
new BZip2AnalyzerFactory(),
new XMLAnalyzerFactory(),
new TroffAnalyzerFactory(),
new ELFAnalyzerFactory(),
new JavaClassAnalyzerFactory(),
new ImageAnalyzerFactory(),
JarAnalyzerFactory.DEFAULT_INSTANCE,
ZipAnalyzerFactory.DEFAULT_INSTANCE,
new TarAnalyzerFactory(),
new CAnalyzerFactory(),
new ShAnalyzerFactory(),
PlainAnalyzerFactory.DEFAULT_INSTANCE,
new GZIPAnalyzerFactory(),
new JavaAnalyzerFactory(),
new LispAnalyzerFactory(),
new TclAnalyzerFactory(),
new SQLAnalyzerFactory(),
};
for (FileAnalyzerFactory analyzer : analyzers) {
registerAnalyzer(analyzer);
}
}
/**
* Register a {@code FileAnalyzerFactory} instance.
*/
private static void registerAnalyzer(FileAnalyzerFactory factory) {
for (String suffix : factory.getSuffixes()) {
FileAnalyzerFactory old = ext.put(suffix, factory);
assert old == null :
"suffix '" + suffix + "' used in multiple analyzers";
}
for (String magic : factory.getMagicStrings()) {
FileAnalyzerFactory old = magics.put(magic, factory);
assert old == null :
"magic '" + magic + "' used in multiple analyzers";
}
matchers.addAll(factory.getMatchers());
factories.add(factory);
}
/**
* Instruct the AnalyzerGuru to use a given analyzer for a given
* file extension.
* @param extension the file-extension to add
* @param factory a factory which creates
* the analyzer to use for the given extension
* (if you pass null as the analyzer, you will disable
* the analyzer used for that extension)
*/
public static void addExtension(String extension,
FileAnalyzerFactory factory) {
if (factory == null) {
ext.remove(extension);
} else {
ext.put(extension, factory);
}
}
/**
* Get the default Analyzer.
*/
public static FileAnalyzer getAnalyzer() {
return DEFAULT_ANALYZER_FACTORY.getAnalyzer();
}
/**
* Get an analyzer suited to analyze a file. This function will reuse
* analyzers since they are costly.
*
* @param in Input stream containing data to be analyzed
* @param file Name of the file to be analyzed
* @return An analyzer suited for that file content
* @throws java.io.IOException If an error occurs while accessing the
* data in the input stream.
*/
public static FileAnalyzer getAnalyzer(InputStream in, String file) throws IOException {
FileAnalyzerFactory factory = find(in, file);
if (factory == null) {
return getAnalyzer();
}
return factory.getAnalyzer();
}
/**
* Create a Lucene document and fill in the required fields
* @param file The file to index
* @param in The data to generate the index for
* @param path Where the file is located (from source root)
* @return The Lucene document to add to the index database
* @throws java.io.IOException If an exception occurs while collecting the
* datas
*/
public Document getDocument(File file, InputStream in, String path,
FileAnalyzer fa) throws IOException {
Document doc = new Document();
String date = DateTools.timeToString(file.lastModified(), DateTools.Resolution.MILLISECOND);
doc.add(new Field("u", Util.uid(path, date), Field.Store.YES, Field.Index.UN_TOKENIZED));
doc.add(new Field("fullpath", file.getAbsolutePath(), Field.Store.YES, Field.Index.TOKENIZED));
try {
HistoryReader hr = HistoryGuru.getInstance().getHistoryReader(file);
if (hr != null) {
doc.add(new Field("hist", hr));
// date = hr.getLastCommentDate() //RFE
}
} catch (IOException e) {
e.printStackTrace();
}
doc.add(new Field("date", date, Field.Store.YES, Field.Index.UN_TOKENIZED));
if (path != null) {
doc.add(new Field("path", path, Field.Store.YES, Field.Index.TOKENIZED));
Project project = Project.getProject(path);
if (project != null) {
doc.add(new Field("project", project.getPath(), Field.Store.YES, Field.Index.TOKENIZED));
}
}
if (fa != null) {
try {
Genre g = fa.getGenre();
if (g == Genre.PLAIN) {
doc.add(new Field("t", "p", Field.Store.YES, Field.Index.UN_TOKENIZED));
} else if (g == Genre.XREFABLE) {
doc.add(new Field("t", "x", Field.Store.YES, Field.Index.UN_TOKENIZED));
} else if (g == Genre.HTML) {
doc.add(new Field("t", "h", Field.Store.YES, Field.Index.UN_TOKENIZED));
}
fa.analyze(doc, in);
} catch (Exception e) {
// Ignoring any errors while analysing
}
}
doc.removeField("fullpath");
return doc;
}
/**
* Get the content type for a named file.
*
* @param in The input stream we want to get the content type for (if
* we cannot determine the content type by the filename)
* @param file The name of the file
* @return The contentType suitable for printing to response.setContentType() or null
* if the factory was not found
* @throws java.io.IOException If an error occurs while accessing the input
* stream.
*/
public static String getContentType(InputStream in, String file) throws IOException {
FileAnalyzerFactory factory = find(in, file);
String type = null;
if (factory != null) {
type = factory.getContentType();
}
return type;
}
/**
* Write a browsable version of the file
*
* @param factory The analyzer factory for this filetype
* @param in The input stream containing the data
* @param out Where to write the result
* @param annotation Annotation information for the file
* @param project Project the file belongs to
* @throws java.io.IOException If an error occurs while creating the
* output
*/
public static void writeXref(FileAnalyzerFactory factory, InputStream in,
Writer out, Annotation annotation, Project project)
throws IOException
{
factory.writeXref(in, out, annotation, project);
}
/**
* Get the genre of a file
*
* @param file The file to inpect
* @return The genre suitable to decide how to display the file
*/
public static Genre getGenre(String file) {
return getGenre(find(file));
}
/**
* Get the genre of a bulk of data
*
* @param in A stream containing the data
* @return The genre suitable to decide how to display the file
* @throws java.io.IOException If an error occurs while getting the content
*/
public static Genre getGenre(InputStream in) throws IOException {
return getGenre(find(in));
}
/**
* Get the genre for a named class (this is most likely an analyzer)
* @param factory the analyzer factory to get the genre for
* @return The genre of this class (null if not found)
*/
public static Genre getGenre(FileAnalyzerFactory factory) {
if (factory != null) {
return factory.getGenre();
}
return null;
}
/**
* Find a {@code FileAnalyzerFactory} with the specified class name. If one
* doesn't exist, create one and register it.
*
* @param factoryClassName name of the factory class
* @return a file analyzer factory
*
* @throws ClassNotFoundException if there is no class with that name
* @throws ClassCastException if the class is not a subclass of {@code
* FileAnalyzerFactory}
* @throws IllegalAccessException if the constructor cannot be accessed
* @throws InstantiationException if the class cannot be instantiated
*/
public static FileAnalyzerFactory findFactory(String factoryClassName)
throws ClassNotFoundException, IllegalAccessException,
InstantiationException
{
return findFactory(Class.forName(factoryClassName));
}
/**
* Find a {@code FileAnalyzerFactory} which is an instance of the specified
* class. If one doesn't exist, create one and register it.
*
* @param factoryClass the factory class
* @return a file analyzer factory
*
* @throws ClassCastException if the class is not a subclass of {@code
* FileAnalyzerFactory}
* @throws IllegalAccessException if the constructor cannot be accessed
* @throws InstantiationException if the class cannot be instantiated
*/
private static FileAnalyzerFactory findFactory(Class factoryClass)
throws InstantiationException, IllegalAccessException
{
for (FileAnalyzerFactory f : factories) {
if (f.getClass() == factoryClass) {
return f;
}
}
FileAnalyzerFactory f =
(FileAnalyzerFactory) factoryClass.newInstance();
registerAnalyzer(f);
return f;
}
/**
* Finds a suitable analyser class for file name. If the analyzer cannot
* be determined by the file extension, try to look at the data in the
* InputStream to find a suitable analyzer.
*
* Use if you just want to find file type.
*
*
* @param in The input stream containing the data
* @param file The file name to get the analyzer for
* @return the analyzer factory to use
* @throws java.io.IOException If a problem occurs while reading the data
*/
public static FileAnalyzerFactory find(InputStream in, String file)
throws IOException
{
FileAnalyzerFactory factory = find(file);
if (factory != null) {
return factory;
}
return find(in);
}
/**
* Finds a suitable analyser class for file name.
*
* @param file The file name to get the analyzer for
* @return the analyzer factory to use
*/
public static FileAnalyzerFactory find(String file) {
int i = 0;
if ((i = file.lastIndexOf('/')) > 0 || (i = file.lastIndexOf('\\')) > 0) {
if (i + 1 < file.length()) {
file = file.substring(i + 1);
}
}
file = file.toUpperCase();
int dotpos = file.lastIndexOf('.');
if (dotpos >= 0) {
FileAnalyzerFactory factory =
ext.get(file.substring(dotpos + 1).toUpperCase());
if (factory != null) {
return factory;
}
}
// file doesn't have any of the extensions we know
return null;
}
/**
* Finds a suitable analyser class for the data in this stream
*
* @param in The stream containing the data to analyze
* @return the analyzer factory to use
* @throws java.io.IOException if an error occurs while reading data from
* the stream
*/
public static FileAnalyzerFactory find(InputStream in) throws IOException {
in.mark(8);
byte[] content = new byte[8];
int len = in.read(content);
in.reset();
if (len < 4) {
return null;
}
FileAnalyzerFactory factory = find(content);
if (factory != null) {
return factory;
}
for (FileAnalyzerFactory.Matcher matcher : matchers) {
FileAnalyzerFactory fac = matcher.isMagic(content, in);
if (fac != null) {
return fac;
}
}
return null;
}
/**
* Finds a suitable analyser class for a magic signature
*
* @param signature the magic signature look up
* @return the analyzer factory to use
*/
public static FileAnalyzerFactory find(byte[] signature) {
char[] chars = new char[signature.length > 8 ? 8 : signature.length];
for (int i = 0; i < chars.length; i++) {
chars[i] = (char) (0xFF & signature[i]);
}
return findMagic(new String(chars));
}
/**
* Get an analyzer by looking up the "magic signature"
* @param signature the signature to look up
* @return the analyzer factory to handle data with this signature
*/
public static FileAnalyzerFactory findMagic(String signature) {
FileAnalyzerFactory a = magics.get(signature);
if (a == null) {
String sigWithoutBOM = stripBOM(signature);
for (Map.Entry<String, FileAnalyzerFactory> entry :
magics.entrySet()) {
if (signature.startsWith(entry.getKey())) {
return entry.getValue();
}
// See if text files have the magic sequence if we remove the
// byte-order marker
if (sigWithoutBOM != null &&
entry.getValue().getGenre() == Genre.PLAIN &&
sigWithoutBOM.startsWith(entry.getKey())) {
return entry.getValue();
}
}
}
return a;
}
/** Byte-order markers. */
private static final String[] BOMS = {
new String(new char[] { 0xEF, 0xBB, 0xBF }), // UTF-8 BOM
new String(new char[] { 0xFE, 0xFF }), // UTF-16BE BOM
new String(new char[] { 0xFF, 0xFE }), // UTF-16LE BOM
};
/**
* Strip away the byte-order marker from the string, if it has one.
*
* @param str the string to remove the BOM from
* @return a string without the byte-order marker, or <code>null</code> if
* the string doesn't start with a BOM
*/
private static String stripBOM(String str) {
for (String bom : BOMS) {
if (str.startsWith(bom)) {
return str.substring(bom.length());
}
}
return null;
}
- public static void main(String[] args) throws Exception {
+ public static void main(String[] args) {
AnalyzerGuru af = new AnalyzerGuru();
System.out.println("<pre wrap=true>");
for (String arg : args) {
try {
- FileAnalyzerFactory an = AnalyzerGuru.find(arg);
File f = new File(arg);
BufferedInputStream in = new BufferedInputStream(new FileInputStream(f));
FileAnalyzer fa = AnalyzerGuru.getAnalyzer(in, arg);
System.out.println("\nANALYZER = " + fa);
Document doc = af.getDocument(f, in, arg, fa);
System.out.println("\nDOCUMENT = " + doc);
Iterator iterator = doc.getFields().iterator();
while (iterator.hasNext()) {
org.apache.lucene.document.Field field = (org.apache.lucene.document.Field) iterator.next();
if (field.isTokenized()) {
Reader r = field.readerValue();
if (r == null) {
r = new StringReader(field.stringValue());
}
TokenStream ts = fa.tokenStream(field.name(), r);
System.out.println("\nFIELD = " + field.name() + " TOKEN STREAM = " + ts.getClass().getName());
Token t;
while ((t = ts.next()) != null) {
System.out.print(t.termText());
System.out.print(' ');
}
System.out.println();
}
if (field.isStored()) {
System.out.println("\nFIELD = " + field.name());
if (field.readerValue() == null) {
System.out.println(field.stringValue());
} else {
System.out.println("STORING THE READER");
}
}
}
System.out.println("Writing XREF--------------");
Writer out = new OutputStreamWriter(System.out);
fa.writeXref(out);
out.flush();
- } catch (Exception e) {
+ } catch (IOException e) {
System.err.println("ERROR: " + e.getMessage());
e.printStackTrace();
+ } catch (RuntimeException e) {
+ System.err.println("RUNTIME ERROR: " + e.getMessage());
+ e.printStackTrace();
}
}
}
}
| false | true | public static void main(String[] args) throws Exception {
AnalyzerGuru af = new AnalyzerGuru();
System.out.println("<pre wrap=true>");
for (String arg : args) {
try {
FileAnalyzerFactory an = AnalyzerGuru.find(arg);
File f = new File(arg);
BufferedInputStream in = new BufferedInputStream(new FileInputStream(f));
FileAnalyzer fa = AnalyzerGuru.getAnalyzer(in, arg);
System.out.println("\nANALYZER = " + fa);
Document doc = af.getDocument(f, in, arg, fa);
System.out.println("\nDOCUMENT = " + doc);
Iterator iterator = doc.getFields().iterator();
while (iterator.hasNext()) {
org.apache.lucene.document.Field field = (org.apache.lucene.document.Field) iterator.next();
if (field.isTokenized()) {
Reader r = field.readerValue();
if (r == null) {
r = new StringReader(field.stringValue());
}
TokenStream ts = fa.tokenStream(field.name(), r);
System.out.println("\nFIELD = " + field.name() + " TOKEN STREAM = " + ts.getClass().getName());
Token t;
while ((t = ts.next()) != null) {
System.out.print(t.termText());
System.out.print(' ');
}
System.out.println();
}
if (field.isStored()) {
System.out.println("\nFIELD = " + field.name());
if (field.readerValue() == null) {
System.out.println(field.stringValue());
} else {
System.out.println("STORING THE READER");
}
}
}
System.out.println("Writing XREF--------------");
Writer out = new OutputStreamWriter(System.out);
fa.writeXref(out);
out.flush();
} catch (Exception e) {
System.err.println("ERROR: " + e.getMessage());
e.printStackTrace();
}
}
}
| public static void main(String[] args) {
AnalyzerGuru af = new AnalyzerGuru();
System.out.println("<pre wrap=true>");
for (String arg : args) {
try {
File f = new File(arg);
BufferedInputStream in = new BufferedInputStream(new FileInputStream(f));
FileAnalyzer fa = AnalyzerGuru.getAnalyzer(in, arg);
System.out.println("\nANALYZER = " + fa);
Document doc = af.getDocument(f, in, arg, fa);
System.out.println("\nDOCUMENT = " + doc);
Iterator iterator = doc.getFields().iterator();
while (iterator.hasNext()) {
org.apache.lucene.document.Field field = (org.apache.lucene.document.Field) iterator.next();
if (field.isTokenized()) {
Reader r = field.readerValue();
if (r == null) {
r = new StringReader(field.stringValue());
}
TokenStream ts = fa.tokenStream(field.name(), r);
System.out.println("\nFIELD = " + field.name() + " TOKEN STREAM = " + ts.getClass().getName());
Token t;
while ((t = ts.next()) != null) {
System.out.print(t.termText());
System.out.print(' ');
}
System.out.println();
}
if (field.isStored()) {
System.out.println("\nFIELD = " + field.name());
if (field.readerValue() == null) {
System.out.println(field.stringValue());
} else {
System.out.println("STORING THE READER");
}
}
}
System.out.println("Writing XREF--------------");
Writer out = new OutputStreamWriter(System.out);
fa.writeXref(out);
out.flush();
} catch (IOException e) {
System.err.println("ERROR: " + e.getMessage());
e.printStackTrace();
} catch (RuntimeException e) {
System.err.println("RUNTIME ERROR: " + e.getMessage());
e.printStackTrace();
}
}
}
|
diff --git a/src/main/java/sfs/async/handler/http/reader/HTTPMessageReader.java b/src/main/java/sfs/async/handler/http/reader/HTTPMessageReader.java
index 57a463e..1bd8d55 100644
--- a/src/main/java/sfs/async/handler/http/reader/HTTPMessageReader.java
+++ b/src/main/java/sfs/async/handler/http/reader/HTTPMessageReader.java
@@ -1,242 +1,243 @@
package sfs.async.handler.http.reader;
import java.util.Arrays;
import sfs.header.http.HeaderEntry;
import sfs.header.http.ending.Ending;
import sfs.header.http.separator.Colon;
import sfs.header.http.separator.SemiColon;
import sfs.mime.Mime;
import sfs.request.http.RequestMessage;
import sfs.stat.message.ContentDisposition;
import sfs.stat.message.DataType;
import sfs.stat.message.MessageStat;
import sfs.util.string.StringUtil;
public class HTTPMessageReader extends AbstractHTTPReader {
private final RequestMessage requestMessage;
private final String CHUNKED_KEY = "chunked";
private final String CHUNKED_END_KEY = Ending.CRLF + "0" + Ending.CRLF + Ending.CRLF;
private final String TRANSFER_ENCODING_HEADER_KEY = HeaderEntry.TRANSFER_ENCODING.toString() + ": " + CHUNKED_KEY
+ Ending.CRLF;
private final String CONTENT_LENGTH_HEADER_KEY = HeaderEntry.CONTENT_LENGTH.toString() + ": ";
private final String BOUNDARY_KEY = "boundary=";
private final String CONTENT_DISPOSITION_KEY = "Content-Disposition: ";
private final String NAME_KEY = "name=";
private final String FILENAME_KEY = "filename=";
private final String FORM_DATA_KEY = "form-data;";
private final String ATTACHMENT_KEY = "attachment;";
public HTTPMessageReader() {
super();
requestMessage = new RequestMessage();
}
public HTTPMessageReader(int bufferCapacity) {
super( bufferCapacity );
requestMessage = new RequestMessage();
}
@Override
public boolean findEndOfMessage(String message, MessageStat messageStat) {
if ( messageStat.isHeaderHasBeenSet() ) {
// sets request header to messageStat.
messageStat.checkAndSetHeaderAndBoundary( BOUNDARY_KEY, requestMessage );
if ( messageStat.getMessageBodyType().equals( HeaderEntry.CONTENT_LENGTH.toString() ) ) {
messageStat.setMessage( messageStat.getMessage() + message );
messageStat.setLength( messageStat.getLength() + message.length() );
messageStat.setMessageBodyLength( messageStat.getMessageBodyLength() - message.length() );
checkAndSetContentDisposition( messageStat );
if ( !messageStat.isContentDispositionSet() && messageStat.getMessageBodyLength() == 0 ) {
messageStat.setMessageBodyLength( messageStat.getLength() - messageStat.getMessageBodyStartIndex() );
messageStat.checkAndSetHeader( requestMessage );
messageStat.setEndOfMessage( true );
return true;
}
return false;
}
else if ( messageStat.getMessageBodyType().equals( "chunked" ) ) {
// TODO chunked type to read message body here.
checkAndSetContentDisposition( messageStat );
}
}
messageStat.setMessage( messageStat.getMessage() + message );
messageStat.setLength( messageStat.getMessage().length() );
int separatorIndex = StringUtil.searchLastIndexOfByMB( messageStat.getMessage(), Ending.CRLF.toString()
+ Ending.CRLF.toString() );
if ( separatorIndex == -1 ) {
return false;
}
int contentHeaderIndex = StringUtil.searchLastIndexOfByMB( messageStat.getMessage(), CONTENT_LENGTH_HEADER_KEY );
int chunkedHeaderIndex = StringUtil.searchLastIndexOfByMB( messageStat.getMessage(),
TRANSFER_ENCODING_HEADER_KEY );
if ( ( contentHeaderIndex == -1 ) && ( chunkedHeaderIndex == -1 ) ) {
// no message body attached
messageStat.checkAndSetHeader( requestMessage );
+ messageStat.setHeaderHasBeenSet( true );
messageStat.setMessageBodyLength( 0 );
messageStat.setMessageBodyContained( false );
messageStat.setEndOfMessage( true );
return true;
}
messageStat.setMessageBodyContained( true );
messageStat.setMessageBodyStartIndex( separatorIndex + 1 );
messageStat.setHeaderHasBeenSet( true );
if ( contentHeaderIndex != -1 ) {
messageStat.setMessageBodyType( HeaderEntry.CONTENT_LENGTH.toString() );
int contentLengthIndex = StringUtil.searchFirstIndexOfByMB( messageStat.getMessage(),
Ending.CRLF.toString(), contentHeaderIndex );
messageStat.setMessageBodyLength( Integer.parseInt( String.valueOf( Arrays.copyOfRange( messageStat
.getMessage().toCharArray(), contentHeaderIndex + 1, contentLengthIndex ) ) )
- ( messageStat.getLength() - messageStat.getMessageBodyStartIndex() ) );
if ( messageStat.getMessageBodyLength() == 0 ) {
messageStat.setMessageBodyLength( messageStat.getLength() - messageStat.getMessageBodyStartIndex() );
checkAndSetContentDisposition( messageStat );
messageStat.setEndOfMessage( true );
return true;
}
}
if ( chunkedHeaderIndex != -1 ) {
messageStat.setMessageBodyType( CHUNKED_KEY );
// TODO can increase the starting point from messageStat.getMessageBodyStartIndex().
if ( StringUtil.searchFirstIndexOfByMB( messageStat.getMessage(), CHUNKED_END_KEY,
messageStat.getMessageBodyStartIndex() ) != -1 ) {
// found the end of chunked, \CR\LF0\CR\LF\CR\LF
checkAndSetContentDisposition( messageStat );
messageStat.setEndOfMessage( true );
return true;
}
}
return false;
}
/**
* Checks and sets ContentDisposition to the specified MessageStat.
*
* @param messageStat
* Used to check and set ContentDiposition.
*/
private void checkAndSetContentDisposition(MessageStat messageStat) {
// sets request header to messageStat.
messageStat.checkAndSetHeaderAndBoundary( BOUNDARY_KEY, requestMessage );
if ( !messageStat.isFileUploadable() ) {
return;
}
// checks content-disposition key
if ( !messageStat.isContentDispositionHasBeenSet() ) {
messageStat.setCurrentContentDispositionIndex( StringUtil.searchLastIndexOfByMB( messageStat.getMessage(),
messageStat.getBoundary() + Ending.CRLF + CONTENT_DISPOSITION_KEY,
messageStat.getMessageBodyStartIndex() ) );
}
else {
messageStat.setCurrentContentDispositionIndex( StringUtil.searchLastIndexOfByMB( messageStat.getMessage(),
messageStat.getBoundary() + Ending.CRLF + CONTENT_DISPOSITION_KEY,
messageStat.getCurrentContentDispositionIndex() ) );
}
// found content-disposition key
if ( messageStat.getCurrentContentDispositionIndex() != -1 && !messageStat.isContentDispositionSet() ) {
// set the index for content-disposition key content
messageStat.setCurrentContentStartIndex( StringUtil.searchFirstIndexOfByMB( messageStat.getMessage(),
Ending.CRLF.toString(), messageStat.getCurrentContentDispositionIndex() + 1 ) + 2 );
if ( messageStat.getCurrentContentStartIndex() != -1 ) {
ContentDisposition added = getContentDispositionKey(
messageStat,
messageStat.getMessage().substring( messageStat.getCurrentContentDispositionIndex() + 1,
messageStat.getCurrentContentStartIndex() - 2 ) );
// set the index for content-disposition content
messageStat.setCurrentContentDispositionIndex( StringUtil.searchFirstIndexOfByMB(
messageStat.getMessage(), Ending.CRLF.toString(), messageStat.getCurrentContentStartIndex() ) );
// set the content from form value.
if ( messageStat.getCurrentContentDispositionIndex() != -1 ) {
added.setFieldValue( messageStat.getMessage().substring( messageStat.getCurrentContentStartIndex(),
messageStat.getCurrentContentDispositionIndex() ) );
messageStat.addContentDisposition( added );
// reached the end of message
if ( messageStat.isEndOfMessage( messageStat.getCurrentContentDispositionIndex(), 2 ) ) {
messageStat.setContentDispositionSet( true );
}
else {
checkAndSetContentDisposition( messageStat );
}
}
}
}
}
/**
* Gets ContentDisposition object out of the parameter, str.
*
* @param messageStat
* Used to store extracted ContentDisposition.
* @param str
* Extraction of ContetnDisposition is taken place.
* @return Newly created ContentDisposition object.
*/
private ContentDisposition getContentDispositionKey(MessageStat messageStat, String str) {
ContentDisposition contentDisposition = new ContentDisposition();
String[] each = str.split( " " );
int index = -1;
for ( int i = 0; i < each.length; i++ ) {
if ( i == 0 ) {
if ( StringUtil.startsWith( each[0], FORM_DATA_KEY ) > 0 ) {
contentDisposition.setDataType( DataType.FORM_DATA );
}
else if ( StringUtil.startsWith( each[0], ATTACHMENT_KEY ) > 0 ) {
contentDisposition.setDataType( DataType.ATTACHMENT );
}
}
if ( ( index = StringUtil.startsWith( each[i], NAME_KEY ) ) > 0 ) {
if ( each[i].toCharArray()[each[i].length() - 1] == SemiColon.SEMI_COLON ) {
contentDisposition.setFieldName( each[i].substring( index + 1, each[i].length() - 1 ) );
}
else {
contentDisposition.setFieldName( each[i].substring( index + 1 ) );
}
}
else if ( ( index = StringUtil.startsWith( each[i], FILENAME_KEY ) ) > 0 ) {
contentDisposition.setFileName( each[i].substring( index + 1 ) );
}
else if ( ( index = StringUtil.startsWith( each[i], HeaderEntry.CONTENT_TYPE.toString() + Colon.COLON ) ) > 0 ) {
contentDisposition.setContentType( (Mime) Mime.MIMES.get( each[i + 1] ) );
break;
}
}
return contentDisposition;
}
}
| true | true | public boolean findEndOfMessage(String message, MessageStat messageStat) {
if ( messageStat.isHeaderHasBeenSet() ) {
// sets request header to messageStat.
messageStat.checkAndSetHeaderAndBoundary( BOUNDARY_KEY, requestMessage );
if ( messageStat.getMessageBodyType().equals( HeaderEntry.CONTENT_LENGTH.toString() ) ) {
messageStat.setMessage( messageStat.getMessage() + message );
messageStat.setLength( messageStat.getLength() + message.length() );
messageStat.setMessageBodyLength( messageStat.getMessageBodyLength() - message.length() );
checkAndSetContentDisposition( messageStat );
if ( !messageStat.isContentDispositionSet() && messageStat.getMessageBodyLength() == 0 ) {
messageStat.setMessageBodyLength( messageStat.getLength() - messageStat.getMessageBodyStartIndex() );
messageStat.checkAndSetHeader( requestMessage );
messageStat.setEndOfMessage( true );
return true;
}
return false;
}
else if ( messageStat.getMessageBodyType().equals( "chunked" ) ) {
// TODO chunked type to read message body here.
checkAndSetContentDisposition( messageStat );
}
}
messageStat.setMessage( messageStat.getMessage() + message );
messageStat.setLength( messageStat.getMessage().length() );
int separatorIndex = StringUtil.searchLastIndexOfByMB( messageStat.getMessage(), Ending.CRLF.toString()
+ Ending.CRLF.toString() );
if ( separatorIndex == -1 ) {
return false;
}
int contentHeaderIndex = StringUtil.searchLastIndexOfByMB( messageStat.getMessage(), CONTENT_LENGTH_HEADER_KEY );
int chunkedHeaderIndex = StringUtil.searchLastIndexOfByMB( messageStat.getMessage(),
TRANSFER_ENCODING_HEADER_KEY );
if ( ( contentHeaderIndex == -1 ) && ( chunkedHeaderIndex == -1 ) ) {
// no message body attached
messageStat.checkAndSetHeader( requestMessage );
messageStat.setMessageBodyLength( 0 );
messageStat.setMessageBodyContained( false );
messageStat.setEndOfMessage( true );
return true;
}
messageStat.setMessageBodyContained( true );
messageStat.setMessageBodyStartIndex( separatorIndex + 1 );
messageStat.setHeaderHasBeenSet( true );
if ( contentHeaderIndex != -1 ) {
messageStat.setMessageBodyType( HeaderEntry.CONTENT_LENGTH.toString() );
int contentLengthIndex = StringUtil.searchFirstIndexOfByMB( messageStat.getMessage(),
Ending.CRLF.toString(), contentHeaderIndex );
messageStat.setMessageBodyLength( Integer.parseInt( String.valueOf( Arrays.copyOfRange( messageStat
.getMessage().toCharArray(), contentHeaderIndex + 1, contentLengthIndex ) ) )
- ( messageStat.getLength() - messageStat.getMessageBodyStartIndex() ) );
if ( messageStat.getMessageBodyLength() == 0 ) {
messageStat.setMessageBodyLength( messageStat.getLength() - messageStat.getMessageBodyStartIndex() );
checkAndSetContentDisposition( messageStat );
messageStat.setEndOfMessage( true );
return true;
}
}
if ( chunkedHeaderIndex != -1 ) {
messageStat.setMessageBodyType( CHUNKED_KEY );
// TODO can increase the starting point from messageStat.getMessageBodyStartIndex().
if ( StringUtil.searchFirstIndexOfByMB( messageStat.getMessage(), CHUNKED_END_KEY,
messageStat.getMessageBodyStartIndex() ) != -1 ) {
// found the end of chunked, \CR\LF0\CR\LF\CR\LF
checkAndSetContentDisposition( messageStat );
messageStat.setEndOfMessage( true );
return true;
}
}
return false;
}
| public boolean findEndOfMessage(String message, MessageStat messageStat) {
if ( messageStat.isHeaderHasBeenSet() ) {
// sets request header to messageStat.
messageStat.checkAndSetHeaderAndBoundary( BOUNDARY_KEY, requestMessage );
if ( messageStat.getMessageBodyType().equals( HeaderEntry.CONTENT_LENGTH.toString() ) ) {
messageStat.setMessage( messageStat.getMessage() + message );
messageStat.setLength( messageStat.getLength() + message.length() );
messageStat.setMessageBodyLength( messageStat.getMessageBodyLength() - message.length() );
checkAndSetContentDisposition( messageStat );
if ( !messageStat.isContentDispositionSet() && messageStat.getMessageBodyLength() == 0 ) {
messageStat.setMessageBodyLength( messageStat.getLength() - messageStat.getMessageBodyStartIndex() );
messageStat.checkAndSetHeader( requestMessage );
messageStat.setEndOfMessage( true );
return true;
}
return false;
}
else if ( messageStat.getMessageBodyType().equals( "chunked" ) ) {
// TODO chunked type to read message body here.
checkAndSetContentDisposition( messageStat );
}
}
messageStat.setMessage( messageStat.getMessage() + message );
messageStat.setLength( messageStat.getMessage().length() );
int separatorIndex = StringUtil.searchLastIndexOfByMB( messageStat.getMessage(), Ending.CRLF.toString()
+ Ending.CRLF.toString() );
if ( separatorIndex == -1 ) {
return false;
}
int contentHeaderIndex = StringUtil.searchLastIndexOfByMB( messageStat.getMessage(), CONTENT_LENGTH_HEADER_KEY );
int chunkedHeaderIndex = StringUtil.searchLastIndexOfByMB( messageStat.getMessage(),
TRANSFER_ENCODING_HEADER_KEY );
if ( ( contentHeaderIndex == -1 ) && ( chunkedHeaderIndex == -1 ) ) {
// no message body attached
messageStat.checkAndSetHeader( requestMessage );
messageStat.setHeaderHasBeenSet( true );
messageStat.setMessageBodyLength( 0 );
messageStat.setMessageBodyContained( false );
messageStat.setEndOfMessage( true );
return true;
}
messageStat.setMessageBodyContained( true );
messageStat.setMessageBodyStartIndex( separatorIndex + 1 );
messageStat.setHeaderHasBeenSet( true );
if ( contentHeaderIndex != -1 ) {
messageStat.setMessageBodyType( HeaderEntry.CONTENT_LENGTH.toString() );
int contentLengthIndex = StringUtil.searchFirstIndexOfByMB( messageStat.getMessage(),
Ending.CRLF.toString(), contentHeaderIndex );
messageStat.setMessageBodyLength( Integer.parseInt( String.valueOf( Arrays.copyOfRange( messageStat
.getMessage().toCharArray(), contentHeaderIndex + 1, contentLengthIndex ) ) )
- ( messageStat.getLength() - messageStat.getMessageBodyStartIndex() ) );
if ( messageStat.getMessageBodyLength() == 0 ) {
messageStat.setMessageBodyLength( messageStat.getLength() - messageStat.getMessageBodyStartIndex() );
checkAndSetContentDisposition( messageStat );
messageStat.setEndOfMessage( true );
return true;
}
}
if ( chunkedHeaderIndex != -1 ) {
messageStat.setMessageBodyType( CHUNKED_KEY );
// TODO can increase the starting point from messageStat.getMessageBodyStartIndex().
if ( StringUtil.searchFirstIndexOfByMB( messageStat.getMessage(), CHUNKED_END_KEY,
messageStat.getMessageBodyStartIndex() ) != -1 ) {
// found the end of chunked, \CR\LF0\CR\LF\CR\LF
checkAndSetContentDisposition( messageStat );
messageStat.setEndOfMessage( true );
return true;
}
}
return false;
}
|
diff --git a/src/java/fedora/server/security/ResourceAttributeFinderModule.java b/src/java/fedora/server/security/ResourceAttributeFinderModule.java
index 9c9f23771..fc960f68e 100755
--- a/src/java/fedora/server/security/ResourceAttributeFinderModule.java
+++ b/src/java/fedora/server/security/ResourceAttributeFinderModule.java
@@ -1,349 +1,349 @@
package fedora.server.security;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.Date;
import com.sun.xacml.EvaluationCtx;
import com.sun.xacml.attr.AttributeDesignator;
import com.sun.xacml.attr.StringAttribute;
import com.sun.xacml.cond.EvaluationResult;
import org.apache.log4j.Logger;
import fedora.common.Constants;
import fedora.server.ReadOnlyContext;
import fedora.server.Server;
import fedora.server.errors.ServerException;
import fedora.server.storage.DOManager;
import fedora.server.storage.DOReader;
import fedora.server.storage.types.Datastream;
import fedora.server.utilities.DateUtility;
/**
* @author [email protected]
*/
class ResourceAttributeFinderModule extends AttributeFinderModule {
/** Logger for this class. */
private static final Logger LOG = Logger.getLogger(
ResourceAttributeFinderModule.class.getName());
protected boolean canHandleAdhoc() {
return false;
}
static private final ResourceAttributeFinderModule singleton = new ResourceAttributeFinderModule();
private ResourceAttributeFinderModule() {
super();
try {
registerAttribute(Constants.OBJECT.STATE.uri, Constants.OBJECT.STATE.datatype);
registerAttribute(Constants.OBJECT.OBJECT_TYPE.uri, Constants.OBJECT.OBJECT_TYPE.datatype);
registerAttribute(Constants.OBJECT.OWNER.uri, Constants.OBJECT.OWNER.datatype);
registerAttribute(Constants.OBJECT.CONTENT_MODEL.uri, Constants.OBJECT.CONTENT_MODEL.datatype);
registerAttribute(Constants.OBJECT.CREATED_DATETIME.uri, Constants.OBJECT.CREATED_DATETIME.datatype);
registerAttribute(Constants.OBJECT.LAST_MODIFIED_DATETIME.uri, Constants.OBJECT.LAST_MODIFIED_DATETIME.datatype);
registerAttribute(Constants.DATASTREAM.STATE.uri, Constants.DATASTREAM.STATE.datatype);
registerAttribute(Constants.DATASTREAM.CONTROL_GROUP.uri, Constants.DATASTREAM.CONTROL_GROUP.datatype);
registerAttribute(Constants.DATASTREAM.CREATED_DATETIME.uri, Constants.DATASTREAM.CREATED_DATETIME.datatype);
registerAttribute(Constants.DATASTREAM.INFO_TYPE.uri, Constants.DATASTREAM.INFO_TYPE.datatype);
registerAttribute(Constants.DATASTREAM.LOCATION_TYPE.uri, Constants.DATASTREAM.LOCATION_TYPE.datatype);
registerAttribute(Constants.DATASTREAM.MIME_TYPE.uri, Constants.DATASTREAM.MIME_TYPE.datatype);
registerAttribute(Constants.DATASTREAM.CONTENT_LENGTH.uri, Constants.DATASTREAM.CONTENT_LENGTH.datatype);
registerAttribute(Constants.DATASTREAM.FORMAT_URI.uri, Constants.DATASTREAM.FORMAT_URI.datatype);
registerAttribute(Constants.DATASTREAM.LOCATION.uri, Constants.DATASTREAM.LOCATION.datatype);
registerSupportedDesignatorType(AttributeDesignator.RESOURCE_TARGET);
setInstantiatedOk(true);
} catch (URISyntaxException e1) {
setInstantiatedOk(false);
}
}
static public final ResourceAttributeFinderModule getInstance() {
return singleton;
}
private DOManager doManager = null;
protected void setDOManager(DOManager doManager) {
if (this.doManager == null) {
this.doManager = doManager;
}
}
private final String getResourceId(EvaluationCtx context) {
URI resourceIdType = null;
URI resourceIdId = null;
try {
resourceIdType = new URI(StringAttribute.identifier);
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
resourceIdId = new URI(EvaluationCtx.RESOURCE_ID);
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
EvaluationResult attribute = context.getResourceAttribute(resourceIdType, resourceIdId, null);
Object element = getAttributeFromEvaluationResult(attribute);
if (element == null) {
LOG.debug("ResourceAttributeFinder:findAttribute" + " exit on " + "can't get resource-id on request callback");
return null;
}
if (! (element instanceof StringAttribute)) {
LOG.debug("ResourceAttributeFinder:findAttribute" + " exit on " + "couldn't get resource-id from xacml request " + "non-string returned");
return null;
}
String resourceId = ((StringAttribute) element).getValue();
if (resourceId == null) {
LOG.debug("ResourceAttributeFinder:findAttribute" + " exit on " + "null resource-id");
return null;
}
if (! validResourceId(resourceId)) {
LOG.debug("ResourceAttributeFinder:findAttribute" + " exit on " + "invalid resource-id");
return null;
}
return resourceId;
}
private final boolean validResourceId(String resourceId) {
if (resourceId == null)
return false;
// "" is a valid resource id, for it represents a don't-care condition
if (" ".equals(resourceId))
return false;
return true;
}
private final String getDatastreamId(EvaluationCtx context) {
URI datastreamIdUri = null;
try {
datastreamIdUri = new URI(Constants.DATASTREAM.ID.uri);
} catch (URISyntaxException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
EvaluationResult attribute = context.getResourceAttribute(STRING_ATTRIBUTE_URI, datastreamIdUri, null);
Object element = getAttributeFromEvaluationResult(attribute);
if (element == null) {
LOG.debug("getDatastreamId: " + " exit on " + "can't get resource-id on request callback");
return null;
}
if (! (element instanceof StringAttribute)) {
LOG.debug("getDatastreamId: " + " exit on " + "couldn't get resource-id from xacml request " + "non-string returned");
return null;
}
String datastreamId = ((StringAttribute) element).getValue();
if (datastreamId == null) {
LOG.debug("getDatastreamId: " + " exit on " + "null resource-id");
return null;
}
if (! validDatastreamId(datastreamId)) {
LOG.debug("getDatastreamId: " + " exit on " + "invalid resource-id");
return null;
}
return datastreamId;
}
private final boolean validDatastreamId(String datastreamId) {
if (datastreamId == null)
return false;
// "" is a valid resource id, for it represents a don't-care condition
if (" ".equals(datastreamId))
return false;
return true;
}
protected final Object getAttributeLocally(int designatorType, String attributeId, URI resourceCategory, EvaluationCtx context) {
long getAttributeStartTime = System.currentTimeMillis();
try {
String pid = getPid(context);
if ("".equals(pid)) {
LOG.debug("no pid");
return null;
}
LOG.debug("getResourceAttribute, pid=" + pid);
DOReader reader = null;
try {
LOG.debug("pid="+pid);
reader = doManager.getReader(Server.USE_CACHE, ReadOnlyContext.EMPTY, pid);
} catch (ServerException e) {
LOG.debug("couldn't get object reader");
return null;
}
String[] values = null;
if (Constants.OBJECT.STATE.uri.equals(attributeId)) {
try {
values = new String[1];
values[0] = reader.GetObjectState();
LOG.debug("got " + Constants.OBJECT.STATE.uri + "=" + values[0]);
} catch (ServerException e) {
LOG.debug("failed getting " + Constants.OBJECT.STATE.uri);
return null;
}
} else if (Constants.OBJECT.OBJECT_TYPE.uri.equals(attributeId)) {
try {
values = new String[1];
- values[0] = reader.getOwnerId();
+ values[0] = reader.getFedoraObjectType();
LOG.debug("got " + Constants.OBJECT.OBJECT_TYPE.uri + "=" + values[0]);
} catch (ServerException e) {
LOG.debug("failed getting " + Constants.OBJECT.OBJECT_TYPE.uri);
return null;
}
} else if (Constants.OBJECT.OWNER.uri.equals(attributeId)) {
try {
values = new String[1];
values[0] = reader.getOwnerId();
LOG.debug("got " + Constants.OBJECT.OWNER.uri + "=" + values[0]);
} catch (ServerException e) {
LOG.debug("failed getting " + Constants.OBJECT.OWNER.uri);
return null;
}
} else if (Constants.OBJECT.CONTENT_MODEL.uri.equals(attributeId)) {
try {
values = new String[1];
values[0] = reader.getContentModelId();
LOG.debug("got " + Constants.OBJECT.CONTENT_MODEL.uri + "=" + values[0]);
} catch (ServerException e) {
LOG.debug("failed getting " + Constants.OBJECT.CONTENT_MODEL.uri);
return null;
}
} else if (Constants.OBJECT.CREATED_DATETIME.uri.equals(attributeId)) {
try {
values = new String[1];
values[0] = DateUtility.convertDateToString(reader.getCreateDate());
LOG.debug("got " + Constants.OBJECT.CREATED_DATETIME.uri + "=" + values[0]);
} catch (ServerException e) {
LOG.debug("failed getting " + Constants.OBJECT.CREATED_DATETIME.uri);
return null;
}
} else if (Constants.OBJECT.LAST_MODIFIED_DATETIME.uri.equals(attributeId)) {
try {
values = new String[1];
values[0] = DateUtility.convertDateToString(reader.getLastModDate());
LOG.debug("got " + Constants.OBJECT.LAST_MODIFIED_DATETIME.uri + "=" + values[0]);
} catch (ServerException e) {
LOG.debug("failed getting " + Constants.OBJECT.LAST_MODIFIED_DATETIME.uri);
return null;
}
} else if ((Constants.DATASTREAM.STATE.uri.equals(attributeId))
|| (Constants.DATASTREAM.CONTROL_GROUP.uri.equals(attributeId))
|| (Constants.DATASTREAM.FORMAT_URI.uri.equals(attributeId))
|| (Constants.DATASTREAM.CREATED_DATETIME.uri.equals(attributeId))
|| (Constants.DATASTREAM.INFO_TYPE.uri.equals(attributeId))
|| (Constants.DATASTREAM.LOCATION.uri.equals(attributeId))
|| (Constants.DATASTREAM.LOCATION_TYPE.uri.equals(attributeId))
|| (Constants.DATASTREAM.MIME_TYPE.uri.equals(attributeId))
|| (Constants.DATASTREAM.CONTENT_LENGTH.uri.equals(attributeId)) ) {
String datastreamId = getDatastreamId(context);
if ("".equals(datastreamId)) {
LOG.debug("no datastreamId");
return null;
}
LOG.debug("datastreamId=" + datastreamId);
Datastream datastream;
try {
datastream = reader.GetDatastream(datastreamId, new Date()); //right import (above)?
} catch (ServerException e) {
LOG.debug("couldn't get datastream");
return null;
}
if (datastream == null) {
LOG.debug("got null datastream");
return null;
}
if (Constants.DATASTREAM.STATE.uri.equals(attributeId)) {
values = new String[1];
values[0] = datastream.DSState;
} else if (Constants.DATASTREAM.CONTROL_GROUP.uri.equals(attributeId)) {
values = new String[1];
values[0] = datastream.DSControlGrp;
} else if (Constants.DATASTREAM.FORMAT_URI.uri.equals(attributeId)) {
values = new String[1];
values[0] = datastream.DSFormatURI;
} else if (Constants.DATASTREAM.CREATED_DATETIME.uri.equals(attributeId)) {
values = new String[1];
values[0] = DateUtility.convertDateToString(datastream.DSCreateDT);
} else if (Constants.DATASTREAM.INFO_TYPE.uri.equals(attributeId)) {
values = new String[1];
values[0] = datastream.DSInfoType;
} else if (Constants.DATASTREAM.LOCATION.uri.equals(attributeId)) {
values = new String[1];
values[0] = datastream.DSLocation;
} else if (Constants.DATASTREAM.LOCATION_TYPE.uri.equals(attributeId)) {
values = new String[1];
values[0] = datastream.DSLocationType;
} else if (Constants.DATASTREAM.MIME_TYPE.uri.equals(attributeId)) {
values = new String[1];
values[0] = datastream.DSMIME;
} else if (Constants.DATASTREAM.CONTENT_LENGTH.uri.equals(attributeId)) {
values = new String[1];
values[0] = Long.toString(datastream.DSSize);
} else {
LOG.debug("looking for unknown resource attribute=" + attributeId);
}
} else {
LOG.debug("looking for unknown resource attribute=" + attributeId);
}
return values;
} finally {
long dur = System.currentTimeMillis() - getAttributeStartTime;
LOG.debug("Locally getting the '" + attributeId + "' attribute for this resource took " + dur + "ms.");
}
}
private final String getPid(EvaluationCtx context) {
URI resourceIdType = null;
URI resourceIdId = null;
try {
resourceIdType = new URI(StringAttribute.identifier);
resourceIdId = new URI(Constants.OBJECT.PID.uri);
} catch (URISyntaxException e) {
LOG.error("Bad URI syntax", e);
}
EvaluationResult attribute = context.getResourceAttribute(resourceIdType, resourceIdId, null);
Object element = getAttributeFromEvaluationResult(attribute);
if (element == null) {
LOG.debug("PolicyFinderModule:getPid" + " exit on " + "can't get contextId on request callback");
return null;
}
if (! (element instanceof StringAttribute)) {
LOG.debug("PolicyFinderModule:getPid" + " exit on " + "couldn't get contextId from xacml request " + "non-string returned");
return null;
}
String pid = ((StringAttribute) element).getValue();
if (pid == null) {
LOG.debug("PolicyFinderModule:getPid" + " exit on " + "null contextId");
return null;
}
return pid;
}
}
| true | true | protected final Object getAttributeLocally(int designatorType, String attributeId, URI resourceCategory, EvaluationCtx context) {
long getAttributeStartTime = System.currentTimeMillis();
try {
String pid = getPid(context);
if ("".equals(pid)) {
LOG.debug("no pid");
return null;
}
LOG.debug("getResourceAttribute, pid=" + pid);
DOReader reader = null;
try {
LOG.debug("pid="+pid);
reader = doManager.getReader(Server.USE_CACHE, ReadOnlyContext.EMPTY, pid);
} catch (ServerException e) {
LOG.debug("couldn't get object reader");
return null;
}
String[] values = null;
if (Constants.OBJECT.STATE.uri.equals(attributeId)) {
try {
values = new String[1];
values[0] = reader.GetObjectState();
LOG.debug("got " + Constants.OBJECT.STATE.uri + "=" + values[0]);
} catch (ServerException e) {
LOG.debug("failed getting " + Constants.OBJECT.STATE.uri);
return null;
}
} else if (Constants.OBJECT.OBJECT_TYPE.uri.equals(attributeId)) {
try {
values = new String[1];
values[0] = reader.getOwnerId();
LOG.debug("got " + Constants.OBJECT.OBJECT_TYPE.uri + "=" + values[0]);
} catch (ServerException e) {
LOG.debug("failed getting " + Constants.OBJECT.OBJECT_TYPE.uri);
return null;
}
} else if (Constants.OBJECT.OWNER.uri.equals(attributeId)) {
try {
values = new String[1];
values[0] = reader.getOwnerId();
LOG.debug("got " + Constants.OBJECT.OWNER.uri + "=" + values[0]);
} catch (ServerException e) {
LOG.debug("failed getting " + Constants.OBJECT.OWNER.uri);
return null;
}
} else if (Constants.OBJECT.CONTENT_MODEL.uri.equals(attributeId)) {
try {
values = new String[1];
values[0] = reader.getContentModelId();
LOG.debug("got " + Constants.OBJECT.CONTENT_MODEL.uri + "=" + values[0]);
} catch (ServerException e) {
LOG.debug("failed getting " + Constants.OBJECT.CONTENT_MODEL.uri);
return null;
}
} else if (Constants.OBJECT.CREATED_DATETIME.uri.equals(attributeId)) {
try {
values = new String[1];
values[0] = DateUtility.convertDateToString(reader.getCreateDate());
LOG.debug("got " + Constants.OBJECT.CREATED_DATETIME.uri + "=" + values[0]);
} catch (ServerException e) {
LOG.debug("failed getting " + Constants.OBJECT.CREATED_DATETIME.uri);
return null;
}
} else if (Constants.OBJECT.LAST_MODIFIED_DATETIME.uri.equals(attributeId)) {
try {
values = new String[1];
values[0] = DateUtility.convertDateToString(reader.getLastModDate());
LOG.debug("got " + Constants.OBJECT.LAST_MODIFIED_DATETIME.uri + "=" + values[0]);
} catch (ServerException e) {
LOG.debug("failed getting " + Constants.OBJECT.LAST_MODIFIED_DATETIME.uri);
return null;
}
} else if ((Constants.DATASTREAM.STATE.uri.equals(attributeId))
|| (Constants.DATASTREAM.CONTROL_GROUP.uri.equals(attributeId))
|| (Constants.DATASTREAM.FORMAT_URI.uri.equals(attributeId))
|| (Constants.DATASTREAM.CREATED_DATETIME.uri.equals(attributeId))
|| (Constants.DATASTREAM.INFO_TYPE.uri.equals(attributeId))
|| (Constants.DATASTREAM.LOCATION.uri.equals(attributeId))
|| (Constants.DATASTREAM.LOCATION_TYPE.uri.equals(attributeId))
|| (Constants.DATASTREAM.MIME_TYPE.uri.equals(attributeId))
|| (Constants.DATASTREAM.CONTENT_LENGTH.uri.equals(attributeId)) ) {
String datastreamId = getDatastreamId(context);
if ("".equals(datastreamId)) {
LOG.debug("no datastreamId");
return null;
}
LOG.debug("datastreamId=" + datastreamId);
Datastream datastream;
try {
datastream = reader.GetDatastream(datastreamId, new Date()); //right import (above)?
} catch (ServerException e) {
LOG.debug("couldn't get datastream");
return null;
}
if (datastream == null) {
LOG.debug("got null datastream");
return null;
}
if (Constants.DATASTREAM.STATE.uri.equals(attributeId)) {
values = new String[1];
values[0] = datastream.DSState;
} else if (Constants.DATASTREAM.CONTROL_GROUP.uri.equals(attributeId)) {
values = new String[1];
values[0] = datastream.DSControlGrp;
} else if (Constants.DATASTREAM.FORMAT_URI.uri.equals(attributeId)) {
values = new String[1];
values[0] = datastream.DSFormatURI;
} else if (Constants.DATASTREAM.CREATED_DATETIME.uri.equals(attributeId)) {
values = new String[1];
values[0] = DateUtility.convertDateToString(datastream.DSCreateDT);
} else if (Constants.DATASTREAM.INFO_TYPE.uri.equals(attributeId)) {
values = new String[1];
values[0] = datastream.DSInfoType;
} else if (Constants.DATASTREAM.LOCATION.uri.equals(attributeId)) {
values = new String[1];
values[0] = datastream.DSLocation;
} else if (Constants.DATASTREAM.LOCATION_TYPE.uri.equals(attributeId)) {
values = new String[1];
values[0] = datastream.DSLocationType;
} else if (Constants.DATASTREAM.MIME_TYPE.uri.equals(attributeId)) {
values = new String[1];
values[0] = datastream.DSMIME;
} else if (Constants.DATASTREAM.CONTENT_LENGTH.uri.equals(attributeId)) {
values = new String[1];
values[0] = Long.toString(datastream.DSSize);
} else {
LOG.debug("looking for unknown resource attribute=" + attributeId);
}
} else {
LOG.debug("looking for unknown resource attribute=" + attributeId);
}
return values;
} finally {
long dur = System.currentTimeMillis() - getAttributeStartTime;
LOG.debug("Locally getting the '" + attributeId + "' attribute for this resource took " + dur + "ms.");
}
}
| protected final Object getAttributeLocally(int designatorType, String attributeId, URI resourceCategory, EvaluationCtx context) {
long getAttributeStartTime = System.currentTimeMillis();
try {
String pid = getPid(context);
if ("".equals(pid)) {
LOG.debug("no pid");
return null;
}
LOG.debug("getResourceAttribute, pid=" + pid);
DOReader reader = null;
try {
LOG.debug("pid="+pid);
reader = doManager.getReader(Server.USE_CACHE, ReadOnlyContext.EMPTY, pid);
} catch (ServerException e) {
LOG.debug("couldn't get object reader");
return null;
}
String[] values = null;
if (Constants.OBJECT.STATE.uri.equals(attributeId)) {
try {
values = new String[1];
values[0] = reader.GetObjectState();
LOG.debug("got " + Constants.OBJECT.STATE.uri + "=" + values[0]);
} catch (ServerException e) {
LOG.debug("failed getting " + Constants.OBJECT.STATE.uri);
return null;
}
} else if (Constants.OBJECT.OBJECT_TYPE.uri.equals(attributeId)) {
try {
values = new String[1];
values[0] = reader.getFedoraObjectType();
LOG.debug("got " + Constants.OBJECT.OBJECT_TYPE.uri + "=" + values[0]);
} catch (ServerException e) {
LOG.debug("failed getting " + Constants.OBJECT.OBJECT_TYPE.uri);
return null;
}
} else if (Constants.OBJECT.OWNER.uri.equals(attributeId)) {
try {
values = new String[1];
values[0] = reader.getOwnerId();
LOG.debug("got " + Constants.OBJECT.OWNER.uri + "=" + values[0]);
} catch (ServerException e) {
LOG.debug("failed getting " + Constants.OBJECT.OWNER.uri);
return null;
}
} else if (Constants.OBJECT.CONTENT_MODEL.uri.equals(attributeId)) {
try {
values = new String[1];
values[0] = reader.getContentModelId();
LOG.debug("got " + Constants.OBJECT.CONTENT_MODEL.uri + "=" + values[0]);
} catch (ServerException e) {
LOG.debug("failed getting " + Constants.OBJECT.CONTENT_MODEL.uri);
return null;
}
} else if (Constants.OBJECT.CREATED_DATETIME.uri.equals(attributeId)) {
try {
values = new String[1];
values[0] = DateUtility.convertDateToString(reader.getCreateDate());
LOG.debug("got " + Constants.OBJECT.CREATED_DATETIME.uri + "=" + values[0]);
} catch (ServerException e) {
LOG.debug("failed getting " + Constants.OBJECT.CREATED_DATETIME.uri);
return null;
}
} else if (Constants.OBJECT.LAST_MODIFIED_DATETIME.uri.equals(attributeId)) {
try {
values = new String[1];
values[0] = DateUtility.convertDateToString(reader.getLastModDate());
LOG.debug("got " + Constants.OBJECT.LAST_MODIFIED_DATETIME.uri + "=" + values[0]);
} catch (ServerException e) {
LOG.debug("failed getting " + Constants.OBJECT.LAST_MODIFIED_DATETIME.uri);
return null;
}
} else if ((Constants.DATASTREAM.STATE.uri.equals(attributeId))
|| (Constants.DATASTREAM.CONTROL_GROUP.uri.equals(attributeId))
|| (Constants.DATASTREAM.FORMAT_URI.uri.equals(attributeId))
|| (Constants.DATASTREAM.CREATED_DATETIME.uri.equals(attributeId))
|| (Constants.DATASTREAM.INFO_TYPE.uri.equals(attributeId))
|| (Constants.DATASTREAM.LOCATION.uri.equals(attributeId))
|| (Constants.DATASTREAM.LOCATION_TYPE.uri.equals(attributeId))
|| (Constants.DATASTREAM.MIME_TYPE.uri.equals(attributeId))
|| (Constants.DATASTREAM.CONTENT_LENGTH.uri.equals(attributeId)) ) {
String datastreamId = getDatastreamId(context);
if ("".equals(datastreamId)) {
LOG.debug("no datastreamId");
return null;
}
LOG.debug("datastreamId=" + datastreamId);
Datastream datastream;
try {
datastream = reader.GetDatastream(datastreamId, new Date()); //right import (above)?
} catch (ServerException e) {
LOG.debug("couldn't get datastream");
return null;
}
if (datastream == null) {
LOG.debug("got null datastream");
return null;
}
if (Constants.DATASTREAM.STATE.uri.equals(attributeId)) {
values = new String[1];
values[0] = datastream.DSState;
} else if (Constants.DATASTREAM.CONTROL_GROUP.uri.equals(attributeId)) {
values = new String[1];
values[0] = datastream.DSControlGrp;
} else if (Constants.DATASTREAM.FORMAT_URI.uri.equals(attributeId)) {
values = new String[1];
values[0] = datastream.DSFormatURI;
} else if (Constants.DATASTREAM.CREATED_DATETIME.uri.equals(attributeId)) {
values = new String[1];
values[0] = DateUtility.convertDateToString(datastream.DSCreateDT);
} else if (Constants.DATASTREAM.INFO_TYPE.uri.equals(attributeId)) {
values = new String[1];
values[0] = datastream.DSInfoType;
} else if (Constants.DATASTREAM.LOCATION.uri.equals(attributeId)) {
values = new String[1];
values[0] = datastream.DSLocation;
} else if (Constants.DATASTREAM.LOCATION_TYPE.uri.equals(attributeId)) {
values = new String[1];
values[0] = datastream.DSLocationType;
} else if (Constants.DATASTREAM.MIME_TYPE.uri.equals(attributeId)) {
values = new String[1];
values[0] = datastream.DSMIME;
} else if (Constants.DATASTREAM.CONTENT_LENGTH.uri.equals(attributeId)) {
values = new String[1];
values[0] = Long.toString(datastream.DSSize);
} else {
LOG.debug("looking for unknown resource attribute=" + attributeId);
}
} else {
LOG.debug("looking for unknown resource attribute=" + attributeId);
}
return values;
} finally {
long dur = System.currentTimeMillis() - getAttributeStartTime;
LOG.debug("Locally getting the '" + attributeId + "' attribute for this resource took " + dur + "ms.");
}
}
|
diff --git a/plexus-compiler/plexus-compilers/plexus-compiler-javac/src/main/java/org/codehaus/plexus/compiler/javac/JavacCompiler.java b/plexus-compiler/plexus-compilers/plexus-compiler-javac/src/main/java/org/codehaus/plexus/compiler/javac/JavacCompiler.java
index a16e3289..c8ec155e 100644
--- a/plexus-compiler/plexus-compilers/plexus-compiler-javac/src/main/java/org/codehaus/plexus/compiler/javac/JavacCompiler.java
+++ b/plexus-compiler/plexus-compilers/plexus-compiler-javac/src/main/java/org/codehaus/plexus/compiler/javac/JavacCompiler.java
@@ -1,367 +1,368 @@
package org.codehaus.plexus.compiler.javac;
/**
* The MIT License
*
* Copyright (c) 2005, The Codehaus
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is furnished to do
* so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
/**
*
* Copyright 2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import org.codehaus.plexus.compiler.AbstractCompiler;
import org.codehaus.plexus.compiler.CompilerConfiguration;
import org.codehaus.plexus.compiler.CompilerError;
import org.codehaus.plexus.util.StringUtils;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.io.StringReader;
import java.io.StringWriter;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.NoSuchElementException;
import java.util.StringTokenizer;
public class JavacCompiler
extends AbstractCompiler
{
private static final int OUTPUT_BUFFER_SIZE = 1024;
private static final String EOL = System.getProperty( "line.separator" );
public List compile( CompilerConfiguration config )
throws Exception
{
File destinationDir = new File( config.getOutputLocation() );
if ( !destinationDir.exists() )
{
destinationDir.mkdirs();
}
String[] sources = getSourceFiles( config );
if ( sources.length == 0 )
{
return Collections.EMPTY_LIST;
}
- getLogger().info( "Compiling " + sources.length + " source file" + ( sources.length == 1 ? "" : "s" ) + " " +
- "to " + destinationDir.getAbsolutePath() );
+ // TODO: use getLogger() - but for some reason it is null when this is used
+ System.out.println( "Compiling " + sources.length + " source file" + ( sources.length == 1 ? "" : "s" ) + " " +
+ "to " + destinationDir.getAbsolutePath() );
List args = new ArrayList( 100 );
// ----------------------------------------------------------------------
// Build command line arguments list
// ----------------------------------------------------------------------
args.add( "-d" );
args.add( destinationDir.getAbsolutePath() );
List classpathEntries = config.getClasspathEntries();
if ( classpathEntries != null && !classpathEntries.isEmpty() )
{
args.add( "-classpath" );
args.add( getPathString( classpathEntries ) );
}
List sourceLocations = config.getSourceLocations();
if ( sourceLocations != null && !sourceLocations.isEmpty() )
{
args.add( "-sourcepath" );
args.add( getPathString( sourceLocations ) );
}
// ----------------------------------------------------------------------
// Build settings from configuration
// ----------------------------------------------------------------------
if ( config.isDebug() )
{
args.add( "-g" );
}
if ( config.isShowDeprecation() )
{
args.add( "-deprecation" );
// This is required to actually display the deprecation messages
config.setShowWarnings( true );
}
if ( !config.isShowWarnings() )
{
args.add( "-nowarn" );
}
// TODO: this could be much improved
if ( StringUtils.isEmpty( config.getTargetVersion() ) )
{
// Required, or it defaults to the target of your JDK (eg 1.5)
args.add( "-target" );
args.add( "1.1" );
}
else
{
args.add( "-target" );
args.add( config.getTargetVersion() );
}
if ( StringUtils.isEmpty( config.getSourceVersion() ) )
{
// If omitted, later JDKs complain about a 1.1 target
args.add( "-source" );
args.add( "1.3" );
}
else
{
args.add( "-source" );
args.add( config.getSourceVersion() );
}
if ( !StringUtils.isEmpty( config.getSourceEncoding() ) )
{
args.add( "-encoding" );
args.add( config.getSourceEncoding() );
}
// ----------------------------------------------------------------------
// Add all other compiler options verbatim
// ----------------------------------------------------------------------
Map compilerOptions = config.getCompilerOptions();
Iterator it = compilerOptions.entrySet().iterator();
while ( it.hasNext() )
{
Map.Entry entry = (Map.Entry) it.next();
args.add( entry.getKey() );
if ( entry.getValue() != null )
{
args.add( entry.getValue() );
}
}
for ( int i = 0; i < sources.length; i++ )
{
args.add( sources[i] );
}
IsolatedClassLoader cl = new IsolatedClassLoader();
File toolsJar = new File( System.getProperty( "java.home" ), "../lib/tools.jar" );
if ( toolsJar.exists() )
{
cl.addURL( toolsJar.toURL() );
}
Class c;
try
{
c = cl.loadClass( "com.sun.tools.javac.Main" );
}
catch ( ClassNotFoundException e )
{
String message = "Unable to locate the Javac Compiler in:" + EOL + " " + toolsJar + EOL +
"Please ensure you are using JDK 1.4 or above and" + EOL +
"not a JRE (the com.sun.tools.javac.Main class is required)." + EOL +
"In most cases you can change the location of your Java" + EOL +
"installation by setting the JAVA_HOME environment variable.";
return Collections.singletonList( new CompilerError( message, true ) );
}
StringWriter out = new StringWriter();
Method compile = c.getMethod( "compile", new Class[]{String[].class, PrintWriter.class} );
Integer ok = (Integer) compile.invoke( null, new Object[]{args.toArray( new String[0] ), new PrintWriter( out )} );
List messages = parseModernStream( new BufferedReader( new StringReader( out.toString() ) ) );
if ( ok.intValue() != 0 && messages.isEmpty() )
{
// TODO: exception?
messages.add( new CompilerError( "Failure executing javac, " +
"but could not parse the error:" + EOL + EOL + out.toString(), true ) );
}
return messages;
}
protected List parseModernStream( BufferedReader input )
throws IOException
{
List errors = new ArrayList();
String line;
StringBuffer buffer;
while ( true )
{
// cleanup the buffer
buffer = new StringBuffer(); // this is quicker than clearing it
// most errors terminate with the '^' char
do
{
line = input.readLine();
if ( line == null )
{
return errors;
}
// TODO: there should be a better way to parse these
if ( buffer.length() == 0 && line.startsWith( "error: " ) )
{
errors.add( new CompilerError( line, true ) );
}
else if ( buffer.length() == 0 && line.startsWith( "Note: " ) )
{
// skip this one - it is JDK 1.5 telling us that the interface is deprecated.
}
else
{
buffer.append( line );
buffer.append( EOL );
}
}
while ( !line.endsWith( "^" ) );
// add the error bean
errors.add( parseModernError( buffer.toString() ) );
}
}
public static CompilerError parseModernError( String error )
{
StringTokenizer tokens = new StringTokenizer( error, ":" );
boolean isError;
StringBuffer msgBuffer;
try
{
String file = tokens.nextToken();
// When will this happen?
if ( file.length() == 1 )
{
file = new StringBuffer( file ).append( ":" ).append( tokens.nextToken() ).toString();
}
int line = Integer.parseInt( tokens.nextToken() );
msgBuffer = new StringBuffer();
String msg = tokens.nextToken( EOL ).substring( 2 );
String WARNING_PREFIX = "warning: ";
isError = !msg.startsWith( WARNING_PREFIX );
// Remove the 'warning: ' prefix
if ( !isError )
{
msg = msg.substring( WARNING_PREFIX.length() );
}
msgBuffer.append( msg );
msgBuffer.append( EOL );
String context = tokens.nextToken( EOL );
String pointer = tokens.nextToken( EOL );
/*
if ( tokens.hasMoreTokens() )
{
msgBuffer.append( context ); // 'symbol' line
msgBuffer.append( EOL );
msgBuffer.append( pointer ); // 'location' line
msgBuffer.append( EOL );
context = tokens.nextToken( EOL );
pointer = tokens.nextToken( EOL );
}
*/
String message = msgBuffer.toString();
int startcolumn = pointer.indexOf( "^" );
int endcolumn = context.indexOf( " ", startcolumn );
if ( endcolumn == -1 )
{
endcolumn = context.length();
}
return new CompilerError( file, isError, line, startcolumn, line, endcolumn, message );
}
catch ( NoSuchElementException e )
{
e.printStackTrace();
return new CompilerError( "no more tokens - could not parse error message: " + error, true );
}
catch ( NumberFormatException e )
{
return new CompilerError( "could not parse error message: " + error, true );
}
catch ( Exception e )
{
return new CompilerError( "could not parse error message: " + error, true );
}
}
}
| true | true | public List compile( CompilerConfiguration config )
throws Exception
{
File destinationDir = new File( config.getOutputLocation() );
if ( !destinationDir.exists() )
{
destinationDir.mkdirs();
}
String[] sources = getSourceFiles( config );
if ( sources.length == 0 )
{
return Collections.EMPTY_LIST;
}
getLogger().info( "Compiling " + sources.length + " source file" + ( sources.length == 1 ? "" : "s" ) + " " +
"to " + destinationDir.getAbsolutePath() );
List args = new ArrayList( 100 );
// ----------------------------------------------------------------------
// Build command line arguments list
// ----------------------------------------------------------------------
args.add( "-d" );
args.add( destinationDir.getAbsolutePath() );
List classpathEntries = config.getClasspathEntries();
if ( classpathEntries != null && !classpathEntries.isEmpty() )
{
args.add( "-classpath" );
args.add( getPathString( classpathEntries ) );
}
List sourceLocations = config.getSourceLocations();
if ( sourceLocations != null && !sourceLocations.isEmpty() )
{
args.add( "-sourcepath" );
args.add( getPathString( sourceLocations ) );
}
// ----------------------------------------------------------------------
// Build settings from configuration
// ----------------------------------------------------------------------
if ( config.isDebug() )
{
args.add( "-g" );
}
if ( config.isShowDeprecation() )
{
args.add( "-deprecation" );
// This is required to actually display the deprecation messages
config.setShowWarnings( true );
}
if ( !config.isShowWarnings() )
{
args.add( "-nowarn" );
}
// TODO: this could be much improved
if ( StringUtils.isEmpty( config.getTargetVersion() ) )
{
// Required, or it defaults to the target of your JDK (eg 1.5)
args.add( "-target" );
args.add( "1.1" );
}
else
{
args.add( "-target" );
args.add( config.getTargetVersion() );
}
if ( StringUtils.isEmpty( config.getSourceVersion() ) )
{
// If omitted, later JDKs complain about a 1.1 target
args.add( "-source" );
args.add( "1.3" );
}
else
{
args.add( "-source" );
args.add( config.getSourceVersion() );
}
if ( !StringUtils.isEmpty( config.getSourceEncoding() ) )
{
args.add( "-encoding" );
args.add( config.getSourceEncoding() );
}
// ----------------------------------------------------------------------
// Add all other compiler options verbatim
// ----------------------------------------------------------------------
Map compilerOptions = config.getCompilerOptions();
Iterator it = compilerOptions.entrySet().iterator();
while ( it.hasNext() )
{
Map.Entry entry = (Map.Entry) it.next();
args.add( entry.getKey() );
if ( entry.getValue() != null )
{
args.add( entry.getValue() );
}
}
for ( int i = 0; i < sources.length; i++ )
{
args.add( sources[i] );
}
IsolatedClassLoader cl = new IsolatedClassLoader();
File toolsJar = new File( System.getProperty( "java.home" ), "../lib/tools.jar" );
if ( toolsJar.exists() )
{
cl.addURL( toolsJar.toURL() );
}
Class c;
try
{
c = cl.loadClass( "com.sun.tools.javac.Main" );
}
catch ( ClassNotFoundException e )
{
String message = "Unable to locate the Javac Compiler in:" + EOL + " " + toolsJar + EOL +
"Please ensure you are using JDK 1.4 or above and" + EOL +
"not a JRE (the com.sun.tools.javac.Main class is required)." + EOL +
"In most cases you can change the location of your Java" + EOL +
"installation by setting the JAVA_HOME environment variable.";
return Collections.singletonList( new CompilerError( message, true ) );
}
StringWriter out = new StringWriter();
Method compile = c.getMethod( "compile", new Class[]{String[].class, PrintWriter.class} );
Integer ok = (Integer) compile.invoke( null, new Object[]{args.toArray( new String[0] ), new PrintWriter( out )} );
List messages = parseModernStream( new BufferedReader( new StringReader( out.toString() ) ) );
if ( ok.intValue() != 0 && messages.isEmpty() )
{
// TODO: exception?
messages.add( new CompilerError( "Failure executing javac, " +
"but could not parse the error:" + EOL + EOL + out.toString(), true ) );
}
return messages;
}
| public List compile( CompilerConfiguration config )
throws Exception
{
File destinationDir = new File( config.getOutputLocation() );
if ( !destinationDir.exists() )
{
destinationDir.mkdirs();
}
String[] sources = getSourceFiles( config );
if ( sources.length == 0 )
{
return Collections.EMPTY_LIST;
}
// TODO: use getLogger() - but for some reason it is null when this is used
System.out.println( "Compiling " + sources.length + " source file" + ( sources.length == 1 ? "" : "s" ) + " " +
"to " + destinationDir.getAbsolutePath() );
List args = new ArrayList( 100 );
// ----------------------------------------------------------------------
// Build command line arguments list
// ----------------------------------------------------------------------
args.add( "-d" );
args.add( destinationDir.getAbsolutePath() );
List classpathEntries = config.getClasspathEntries();
if ( classpathEntries != null && !classpathEntries.isEmpty() )
{
args.add( "-classpath" );
args.add( getPathString( classpathEntries ) );
}
List sourceLocations = config.getSourceLocations();
if ( sourceLocations != null && !sourceLocations.isEmpty() )
{
args.add( "-sourcepath" );
args.add( getPathString( sourceLocations ) );
}
// ----------------------------------------------------------------------
// Build settings from configuration
// ----------------------------------------------------------------------
if ( config.isDebug() )
{
args.add( "-g" );
}
if ( config.isShowDeprecation() )
{
args.add( "-deprecation" );
// This is required to actually display the deprecation messages
config.setShowWarnings( true );
}
if ( !config.isShowWarnings() )
{
args.add( "-nowarn" );
}
// TODO: this could be much improved
if ( StringUtils.isEmpty( config.getTargetVersion() ) )
{
// Required, or it defaults to the target of your JDK (eg 1.5)
args.add( "-target" );
args.add( "1.1" );
}
else
{
args.add( "-target" );
args.add( config.getTargetVersion() );
}
if ( StringUtils.isEmpty( config.getSourceVersion() ) )
{
// If omitted, later JDKs complain about a 1.1 target
args.add( "-source" );
args.add( "1.3" );
}
else
{
args.add( "-source" );
args.add( config.getSourceVersion() );
}
if ( !StringUtils.isEmpty( config.getSourceEncoding() ) )
{
args.add( "-encoding" );
args.add( config.getSourceEncoding() );
}
// ----------------------------------------------------------------------
// Add all other compiler options verbatim
// ----------------------------------------------------------------------
Map compilerOptions = config.getCompilerOptions();
Iterator it = compilerOptions.entrySet().iterator();
while ( it.hasNext() )
{
Map.Entry entry = (Map.Entry) it.next();
args.add( entry.getKey() );
if ( entry.getValue() != null )
{
args.add( entry.getValue() );
}
}
for ( int i = 0; i < sources.length; i++ )
{
args.add( sources[i] );
}
IsolatedClassLoader cl = new IsolatedClassLoader();
File toolsJar = new File( System.getProperty( "java.home" ), "../lib/tools.jar" );
if ( toolsJar.exists() )
{
cl.addURL( toolsJar.toURL() );
}
Class c;
try
{
c = cl.loadClass( "com.sun.tools.javac.Main" );
}
catch ( ClassNotFoundException e )
{
String message = "Unable to locate the Javac Compiler in:" + EOL + " " + toolsJar + EOL +
"Please ensure you are using JDK 1.4 or above and" + EOL +
"not a JRE (the com.sun.tools.javac.Main class is required)." + EOL +
"In most cases you can change the location of your Java" + EOL +
"installation by setting the JAVA_HOME environment variable.";
return Collections.singletonList( new CompilerError( message, true ) );
}
StringWriter out = new StringWriter();
Method compile = c.getMethod( "compile", new Class[]{String[].class, PrintWriter.class} );
Integer ok = (Integer) compile.invoke( null, new Object[]{args.toArray( new String[0] ), new PrintWriter( out )} );
List messages = parseModernStream( new BufferedReader( new StringReader( out.toString() ) ) );
if ( ok.intValue() != 0 && messages.isEmpty() )
{
// TODO: exception?
messages.add( new CompilerError( "Failure executing javac, " +
"but could not parse the error:" + EOL + EOL + out.toString(), true ) );
}
return messages;
}
|
diff --git a/sdkmanager/libs/sdklib/src/com/android/sdklib/AddOnTarget.java b/sdkmanager/libs/sdklib/src/com/android/sdklib/AddOnTarget.java
index d72cd9430..f5fcf9024 100644
--- a/sdkmanager/libs/sdklib/src/com/android/sdklib/AddOnTarget.java
+++ b/sdkmanager/libs/sdklib/src/com/android/sdklib/AddOnTarget.java
@@ -1,329 +1,329 @@
/*
* 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.sdklib;
import java.io.File;
import java.io.FileFilter;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Map;
import java.util.Map.Entry;
/**
* Represents an add-on target in the SDK.
* An add-on extends a standard {@link PlatformTarget}.
*/
final class AddOnTarget implements IAndroidTarget {
/**
* String to compute hash for add-on targets.
* Format is vendor:name:apiVersion
* */
private final static String ADD_ON_FORMAT = "%s:%s:%s"; //$NON-NLS-1$
private final static class OptionalLibrary implements IOptionalLibrary {
private final String mJarName;
private final String mJarPath;
private final String mName;
private final String mDescription;
OptionalLibrary(String jarName, String jarPath, String name, String description) {
mJarName = jarName;
mJarPath = jarPath;
mName = name;
mDescription = description;
}
public String getJarName() {
return mJarName;
}
public String getJarPath() {
return mJarPath;
}
public String getName() {
return mName;
}
public String getDescription() {
return mDescription;
}
}
private final String mLocation;
private final PlatformTarget mBasePlatform;
private final String mName;
private final String mVendor;
private final int mRevision;
private final String mDescription;
private String[] mSkins;
private String mDefaultSkin;
private IOptionalLibrary[] mLibraries;
private int mVendorId = NO_USB_ID;
/**
* Creates a new add-on
* @param location the OS path location of the add-on
* @param name the name of the add-on
* @param vendor the vendor name of the add-on
* @param revision the revision of the add-on
* @param description the add-on description
* @param libMap A map containing the optional libraries. The map key is the fully-qualified
* library name. The value is a 2 string array with the .jar filename, and the description.
* @param basePlatform the platform the add-on is extending.
*/
AddOnTarget(String location, String name, String vendor, int revision, String description,
Map<String, String[]> libMap, PlatformTarget basePlatform) {
if (location.endsWith(File.separator) == false) {
location = location + File.separator;
}
mLocation = location;
mName = name;
mVendor = vendor;
mRevision = revision;
mDescription = description;
mBasePlatform = basePlatform;
// handle the optional libraries.
if (libMap != null) {
mLibraries = new IOptionalLibrary[libMap.size()];
int index = 0;
for (Entry<String, String[]> entry : libMap.entrySet()) {
String jarFile = entry.getValue()[0];
String desc = entry.getValue()[1];
mLibraries[index++] = new OptionalLibrary(jarFile,
mLocation + SdkConstants.OS_ADDON_LIBS_FOLDER + jarFile,
entry.getKey(), desc);
}
}
}
public String getLocation() {
return mLocation;
}
public String getName() {
return mName;
}
public String getVendor() {
return mVendor;
}
public String getFullName() {
return String.format("%1$s (%2$s)", mName, mVendor);
}
public String getClasspathName() {
return String.format("%1$s [%2$s]", mName, mBasePlatform.getName());
}
public String getDescription() {
return mDescription;
}
public AndroidVersion getVersion() {
// this is always defined by the base platform
return mBasePlatform.getVersion();
}
public String getVersionName() {
return mBasePlatform.getVersionName();
}
public int getRevision() {
return mRevision;
}
public boolean isPlatform() {
return false;
}
public IAndroidTarget getParent() {
return mBasePlatform;
}
public String getPath(int pathId) {
switch (pathId) {
case IMAGES:
return mLocation + SdkConstants.OS_IMAGES_FOLDER;
case SKINS:
return mLocation + SdkConstants.OS_SKINS_FOLDER;
case DOCS:
return mLocation + SdkConstants.FD_DOCS + File.separator
+ SdkConstants.FD_DOCS_REFERENCE;
case SAMPLES:
// only return the add-on samples folder if there is actually a sample (or more)
File sampleLoc = new File(mLocation, SdkConstants.FD_SAMPLES);
if (sampleLoc.isDirectory()) {
File[] files = sampleLoc.listFiles(new FileFilter() {
public boolean accept(File pathname) {
return pathname.isDirectory();
}
});
if (files != null && files.length > 0) {
return sampleLoc.getAbsolutePath();
}
}
// INTENDED FALL-THROUGH
default :
return mBasePlatform.getPath(pathId);
}
}
public String[] getSkins() {
return mSkins;
}
public String getDefaultSkin() {
return mDefaultSkin;
}
public IOptionalLibrary[] getOptionalLibraries() {
return mLibraries;
}
/**
* Returns the list of libraries of the underlying platform.
*
* {@inheritDoc}
*/
public String[] getPlatformLibraries() {
return mBasePlatform.getPlatformLibraries();
}
public int getUsbVendorId() {
return mVendorId;
}
public boolean isCompatibleBaseFor(IAndroidTarget target) {
// basic test
if (target == this) {
return true;
}
/*
* The method javadoc indicates:
* Returns whether the given target is compatible with the receiver.
* <p/>A target is considered compatible if applications developed for the receiver can
* run on the given target.
*/
// The receiver is an add-on. There are 2 big use cases: The add-on has libraries
// or the add-on doesn't (in which case we consider it a platform).
- if (mLibraries.length == 0) {
+ if (mLibraries == null || mLibraries.length == 0) {
return mBasePlatform.isCompatibleBaseFor(target);
} else {
// the only targets that can run the receiver are the same add-on in the same or later
// versions.
// first check: vendor/name
if (mVendor.equals(target.getVendor()) == false ||
mName.equals(target.getName()) == false) {
return false;
}
// now check the version. At this point since we checked the add-on part,
// we can revert to the basic check on version/codename which are done by the
// base platform already.
return mBasePlatform.isCompatibleBaseFor(target);
}
}
public String hashString() {
return String.format(ADD_ON_FORMAT, mVendor, mName,
mBasePlatform.getVersion().getApiString());
}
@Override
public int hashCode() {
return hashString().hashCode();
}
@Override
public boolean equals(Object obj) {
if (obj instanceof AddOnTarget) {
AddOnTarget addon = (AddOnTarget)obj;
return mVendor.equals(addon.mVendor) && mName.equals(addon.mName) &&
mBasePlatform.getVersion().equals(addon.mBasePlatform.getVersion());
}
return false;
}
/*
* Always return +1 if the object we compare to is a platform.
* Otherwise, do vendor then name then api version comparison.
* (non-Javadoc)
* @see java.lang.Comparable#compareTo(java.lang.Object)
*/
public int compareTo(IAndroidTarget target) {
if (target.isPlatform()) {
return +1;
}
// compare vendor
int value = mVendor.compareTo(target.getVendor());
// if same vendor, compare name
if (value == 0) {
value = mName.compareTo(target.getName());
}
// if same vendor/name, compare version
if (value == 0) {
if (getVersion().isPreview() == true) {
value = target.getVersion().isPreview() == true ?
getVersion().getApiString().compareTo(target.getVersion().getApiString()) :
+1; // put the preview at the end.
} else {
value = target.getVersion().isPreview() == true ?
-1 : // put the preview at the end :
getVersion().getApiLevel() - target.getVersion().getApiLevel();
}
}
return value;
}
// ---- local methods.
void setSkins(String[] skins, String defaultSkin) {
mDefaultSkin = defaultSkin;
// we mix the add-on and base platform skins
HashSet<String> skinSet = new HashSet<String>();
skinSet.addAll(Arrays.asList(skins));
skinSet.addAll(Arrays.asList(mBasePlatform.getSkins()));
mSkins = skinSet.toArray(new String[skinSet.size()]);
}
/**
* Sets the USB vendor id in the add-on.
*/
void setUsbVendorId(int vendorId) {
if (vendorId == 0) {
throw new IllegalArgumentException( "VendorId must be > 0");
}
mVendorId = vendorId;
}
}
| true | true | public boolean isCompatibleBaseFor(IAndroidTarget target) {
// basic test
if (target == this) {
return true;
}
/*
* The method javadoc indicates:
* Returns whether the given target is compatible with the receiver.
* <p/>A target is considered compatible if applications developed for the receiver can
* run on the given target.
*/
// The receiver is an add-on. There are 2 big use cases: The add-on has libraries
// or the add-on doesn't (in which case we consider it a platform).
if (mLibraries.length == 0) {
return mBasePlatform.isCompatibleBaseFor(target);
} else {
// the only targets that can run the receiver are the same add-on in the same or later
// versions.
// first check: vendor/name
if (mVendor.equals(target.getVendor()) == false ||
mName.equals(target.getName()) == false) {
return false;
}
// now check the version. At this point since we checked the add-on part,
// we can revert to the basic check on version/codename which are done by the
// base platform already.
return mBasePlatform.isCompatibleBaseFor(target);
}
}
| public boolean isCompatibleBaseFor(IAndroidTarget target) {
// basic test
if (target == this) {
return true;
}
/*
* The method javadoc indicates:
* Returns whether the given target is compatible with the receiver.
* <p/>A target is considered compatible if applications developed for the receiver can
* run on the given target.
*/
// The receiver is an add-on. There are 2 big use cases: The add-on has libraries
// or the add-on doesn't (in which case we consider it a platform).
if (mLibraries == null || mLibraries.length == 0) {
return mBasePlatform.isCompatibleBaseFor(target);
} else {
// the only targets that can run the receiver are the same add-on in the same or later
// versions.
// first check: vendor/name
if (mVendor.equals(target.getVendor()) == false ||
mName.equals(target.getName()) == false) {
return false;
}
// now check the version. At this point since we checked the add-on part,
// we can revert to the basic check on version/codename which are done by the
// base platform already.
return mBasePlatform.isCompatibleBaseFor(target);
}
}
|
diff --git a/src/jvm/clojure/lang/Script.java b/src/jvm/clojure/lang/Script.java
index df1390c2..08f8bbe6 100644
--- a/src/jvm/clojure/lang/Script.java
+++ b/src/jvm/clojure/lang/Script.java
@@ -1,43 +1,43 @@
/**
* Copyright (c) Rich Hickey. All rights reserved.
* The use and distribution terms for this software are covered by the
* Common Public License 1.0 (http://opensource.org/licenses/cpl.php)
* which can be found in the file CPL.TXT at the root of this distribution.
* By using this software in any fashion, you are agreeing to be bound by
* the terms of this license.
* You must not remove this notice, or any other, from this software.
**/
/* rich Oct 18, 2007 */
package clojure.lang;
import java.io.OutputStreamWriter;
import java.io.IOException;
import java.util.List;
import java.util.Arrays;
public class Script{
public static void main(String[] args) throws Exception{
- for(String file : RT.processCommandLine(args))
+ try
+ {
+ for(String file : RT.processCommandLine(args))
+ Compiler.loadFile(file);
+ }
+ finally
+ {
+ OutputStreamWriter w = (OutputStreamWriter) RT.OUT.get();
try
{
- Compiler.loadFile(file);
+ w.flush();
+ w.close();
}
- finally
+ catch(IOException e)
{
- OutputStreamWriter w = (OutputStreamWriter) RT.OUT.get();
- try
- {
- w.flush();
- w.close();
- }
- catch(IOException e)
- {
- e.printStackTrace();
- }
+ e.printStackTrace();
}
+ }
}
}
| false | true | public static void main(String[] args) throws Exception{
for(String file : RT.processCommandLine(args))
try
{
Compiler.loadFile(file);
}
finally
{
OutputStreamWriter w = (OutputStreamWriter) RT.OUT.get();
try
{
w.flush();
w.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
| public static void main(String[] args) throws Exception{
try
{
for(String file : RT.processCommandLine(args))
Compiler.loadFile(file);
}
finally
{
OutputStreamWriter w = (OutputStreamWriter) RT.OUT.get();
try
{
w.flush();
w.close();
}
catch(IOException e)
{
e.printStackTrace();
}
}
}
|
diff --git a/src/de/uni_koblenz/jgralab/codegenerator/AttributedElementCodeGenerator.java b/src/de/uni_koblenz/jgralab/codegenerator/AttributedElementCodeGenerator.java
index fc68924d7..891395a46 100755
--- a/src/de/uni_koblenz/jgralab/codegenerator/AttributedElementCodeGenerator.java
+++ b/src/de/uni_koblenz/jgralab/codegenerator/AttributedElementCodeGenerator.java
@@ -1,372 +1,372 @@
/*
* JGraLab - The Java graph laboratory
* (c) 2006-2009 Institute for Software Technology
* University of Koblenz-Landau, Germany
*
* [email protected]
*
* Please report bugs to http://serres.uni-koblenz.de/bugzilla
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package de.uni_koblenz.jgralab.codegenerator;
import java.util.Set;
import java.util.SortedSet;
import java.util.TreeSet;
import de.uni_koblenz.jgralab.Attribute;
import de.uni_koblenz.jgralab.schema.AttributedElementClass;
import de.uni_koblenz.jgralab.schema.EnumDomain;
/**
* TODO add comment
*
* @author [email protected]
*
*/
public class AttributedElementCodeGenerator extends CodeGenerator {
/**
* all the interfaces of the class which are being implemented
*/
protected SortedSet<String> interfaces;
/**
* the AttributedElementClass to generate code for
*/
protected AttributedElementClass aec;
/**
* specifies if the generated code is a special JGraLab class of layer M2
* this effects the way the constructor and some methods are built valid
* values: "Graph", "Vertex", "Edge", "Incidence"
*/
protected AttributedElementCodeGenerator(
AttributedElementClass attributedElementClass,
String schemaRootPackageName, String implementationName) {
super(schemaRootPackageName, attributedElementClass.getPackageName());
aec = attributedElementClass;
rootBlock.setVariable("ecName", aec.getSimpleName());
rootBlock.setVariable("qualifiedClassName", aec.getQualifiedName());
rootBlock.setVariable("schemaName", aec.getSchema().getName());
rootBlock.setVariable("schemaVariableName", aec.getVariableName());
rootBlock.setVariable("javaClassName", schemaRootPackageName + "."
+ aec.getQualifiedName());
rootBlock.setVariable("qualifiedImplClassName", schemaRootPackageName
+ ".impl." + aec.getQualifiedName() + "Impl");
rootBlock.setVariable("simpleClassName", aec.getSimpleName());
rootBlock.setVariable("simpleImplClassName", aec.getSimpleName()
+ "Impl");
rootBlock.setVariable("uniqueClassName", aec.getUniqueName());
rootBlock.setVariable("schemaPackageName", schemaRootPackageName);
interfaces = new TreeSet<String>();
interfaces.add(aec.getQualifiedName());
rootBlock.setVariable("isAbstractClass", aec.isAbstract() ? "true"
: "false");
for (AttributedElementClass superClass : attributedElementClass
.getDirectSuperClasses()) {
interfaces.add(superClass.getQualifiedName());
}
}
@Override
protected CodeBlock createBody(boolean createClass) {
CodeList code = new CodeList();
if (createClass) {
code.add(createFields(aec.getAttributeList()));
code.add(createConstructor());
code.add(createGetAttributedElementClassMethod());
code.add(createGetM1ClassMethod());
code.add(createGenericGetter(aec.getAttributeList()));
code.add(createGenericSetter(aec.getAttributeList()));
code.add(createGettersAndSetters(aec.getAttributeList(),
createClass));
code.add(createReadAttributesMethod(aec.getAttributeList()));
code.add(createWriteAttributesMethod(aec.getAttributeList()));
} else {
code.add(createGettersAndSetters(aec.getOwnAttributeList(),
createClass));
}
return code;
}
@Override
protected CodeBlock createHeader(boolean createClass) {
CodeSnippet code = new CodeSnippet(true);
code.setVariable("classOrInterface", createClass ? " class"
: " interface");
code.setVariable("abstract",
createClass && aec.isAbstract() ? " abstract" : "");
code
.setVariable("impl", createClass && !aec.isAbstract() ? "Impl"
: "");
code
.add("public#abstract##classOrInterface# #simpleClassName##impl##extends##implements# {");
code.setVariable("extends", createClass ? " extends #baseClassName#"
: "");
StringBuffer buf = new StringBuffer();
if (interfaces.size() > 0) {
String delim = createClass ? " implements " : " extends ";
for (String interfaceName : interfaces) {
if (createClass
|| !interfaceName.equals(aec.getQualifiedName())) {
if (interfaceName.equals("Vertex")
|| interfaceName.equals("Edge")
|| interfaceName.equals("Aggregation")
|| interfaceName.equals("Composition")
|| interfaceName.equals("Graph")) {
buf.append(delim);
buf.append("#jgPackage#." + interfaceName);
delim = ", ";
} else {
buf.append(delim);
buf.append(schemaRootPackageName + "." + interfaceName);
delim = ", ";
}
}
}
}
code.setVariable("implements", buf.toString());
return code;
}
protected CodeBlock createStaticImplementationClassField() {
return new CodeSnippet(
true,
"/**",
" * refers to the default implementation class of this interface",
" */",
"public static final java.lang.Class<#qualifiedImplClassName#> IMPLEMENTATION_CLASS = #qualifiedImplClassName#.class;");
}
protected CodeBlock createSpecialConstructorCode() {
return null;
}
protected CodeBlock createConstructor() {
CodeList code = new CodeList();
code.addNoIndent(new CodeSnippet(true,
"public #simpleClassName#Impl(int id, #jgPackage#.Graph g) {",
"\tsuper(id, g);"));
code.add(createSpecialConstructorCode());
code.addNoIndent(new CodeSnippet("}"));
return code;
}
protected CodeBlock createGetAttributedElementClassMethod() {
return new CodeSnippet(
true,
"public final #jgSchemaPackage#.AttributedElementClass getAttributedElementClass() {",
"\treturn #schemaPackageName#.#schemaName#.instance().#schemaVariableName#;",
"}");
}
protected CodeBlock createGetM1ClassMethod() {
return new CodeSnippet(
true,
"public final java.lang.Class<? extends #jgPackage#.AttributedElement> getM1Class() {",
"\treturn #javaClassName#.class;", "}");
}
protected CodeBlock createGenericGetter(Set<Attribute> attrSet) {
CodeList code = new CodeList();
code
.addNoIndent(new CodeSnippet(
true,
"public Object getAttribute(String attributeName) throws NoSuchFieldException {"));
for (Attribute attr : attrSet) {
CodeSnippet s = new CodeSnippet();
s.setVariable("name", attr.getName());
s.add("if (attributeName.equals(\"#name#\")) return #name#;");
code.add(s);
}
code
.add(new CodeSnippet(
"throw new NoSuchFieldException(\"#qualifiedClassName# doesn't contain an attribute \" + attributeName);"));
code.addNoIndent(new CodeSnippet("}"));
return code;
}
protected CodeBlock createGenericSetter(Set<Attribute> attrSet) {
CodeList code = new CodeList();
CodeSnippet snip = new CodeSnippet(true);
boolean suppressWarningsNeeded = false;
for (Attribute attr : attrSet) {
if (attr.getDomain().isComposite()) {
suppressWarningsNeeded = true;
break;
}
}
if (suppressWarningsNeeded) {
snip.add("@SuppressWarnings(\"unchecked\")");
}
snip
.add("public void setAttribute(String attributeName, Object data) throws NoSuchFieldException {");
code.addNoIndent(snip);
for (Attribute attr : attrSet) {
CodeSnippet s = new CodeSnippet();
s.setVariable("name", attr.getName());
s.setVariable("cName", camelCase(attr.getName()));
if (attr.getDomain().isComposite()) {
s.setVariable("attributeClassName", attr.getDomain()
.getJavaAttributeImplementationTypeName(
schemaRootPackageName));
} else {
s.setVariable("attributeClassName", attr.getDomain()
.getJavaClassName(schemaRootPackageName));
}
boolean isEnumDomain = false;
if (attr.getDomain() instanceof EnumDomain) {
isEnumDomain = true;
}
if (isEnumDomain) {
s.add("if (attributeName.equals(\"#name#\")) {");
s.add("\tif (data instanceof String) {");
- s.add("\t\t#attributeClassName#.fromString((String) data);");
+ s.add("\t\tset#cName#(#attributeClassName#.fromString((String) data));");
s.add("\t} else {");
s.add("\t\tset#cName#((#attributeClassName#) data);");
s.add("\t}");
s.add("\treturn;");
s.add("}");
} else {
s.add("if (attributeName.equals(\"#name#\")) {");
s.add("\tset#cName#((#attributeClassName#) data);");
s.add("\treturn;");
s.add("}");
}
code.add(s);
}
code
.add(new CodeSnippet(
"throw new NoSuchFieldException(\"#qualifiedClassName# doesn't contain an attribute \" + attributeName);"));
code.addNoIndent(new CodeSnippet("}"));
return code;
}
protected CodeBlock createFields(Set<Attribute> attrSet) {
CodeList code = new CodeList();
for (Attribute attr : attrSet) {
code.addNoIndent(createField(attr));
}
return code;
}
protected CodeBlock createGettersAndSetters(Set<Attribute> attrSet,
boolean createClass) {
CodeList code = new CodeList();
for (Attribute attr : attrSet) {
code.addNoIndent(createGetter(attr, createClass));
}
for (Attribute attr : attrSet) {
code.addNoIndent(createSetter(attr, createClass));
}
return code;
}
protected CodeBlock createGetter(Attribute attr, boolean createClass) {
CodeSnippet code = new CodeSnippet(true);
code.setVariable("name", attr.getName());
code.setVariable("cName", camelCase(attr.getName()));
code.setVariable("type", attr.getDomain()
.getJavaAttributeImplementationTypeName(schemaRootPackageName));
code.setVariable("isOrGet", attr.getDomain().getJavaClassName(
schemaRootPackageName).equals("Boolean") ? "is" : "get");
if (createClass) {
code.add("public #type# #isOrGet##cName#() {", "\treturn #name#;",
"}");
} else {
code.add("public #type# #isOrGet##cName#();");
}
return code;
}
protected CodeBlock createSetter(Attribute attr, boolean createClass) {
CodeSnippet code = new CodeSnippet(true);
code.setVariable("name", attr.getName());
code.setVariable("cName", camelCase(attr.getName()));
code.setVariable("type", attr.getDomain()
.getJavaAttributeImplementationTypeName(schemaRootPackageName));
if (createClass) {
code.add("public void set#cName#(#type# #name#) {",
"\tthis.#name# = #name#;", "\tgraphModified();", "}");
} else {
code.add("public void set#cName#(#type# #name#);");
}
return code;
}
protected CodeBlock createField(Attribute attr) {
CodeSnippet code = new CodeSnippet(true, "protected #type# #name#;");
code.setVariable("name", attr.getName());
code.setVariable("type", attr.getDomain()
.getJavaAttributeImplementationTypeName(schemaRootPackageName));
return code;
}
protected CodeBlock createReadAttributesMethod(Set<Attribute> attrSet) {
CodeList code = new CodeList();
addImports("#jgPackage#.GraphIO", "#jgPackage#.GraphIOException");
code
.addNoIndent(new CodeSnippet(true,
"public void readAttributeValues(GraphIO io) throws GraphIOException {"));
if (attrSet != null) {
for (Attribute attribute : attrSet) {
CodeSnippet snippet = new CodeSnippet();
snippet.setVariable("setterName", "set"
+ camelCase(attribute.getName()));
snippet.setVariable("variableName", attribute.getName());
code.add(attribute.getDomain().getReadMethod(
schemaRootPackageName, attribute.getName(), "io"));
snippet.add("#setterName#(#variableName#);");
code.add(snippet);
}
}
code.addNoIndent(new CodeSnippet("}"));
return code;
}
protected CodeBlock createWriteAttributesMethod(Set<Attribute> attrSet) {
CodeList code = new CodeList();
addImports("#jgPackage#.GraphIO", "#jgPackage#.GraphIOException",
"java.io.IOException");
code
.addNoIndent(new CodeSnippet(
true,
"public void writeAttributeValues(GraphIO io) throws GraphIOException, IOException {"));
if (attrSet != null && !attrSet.isEmpty()) {
code.add(new CodeSnippet("io.space();"));
for (Attribute attribute : attrSet) {
code.add(attribute.getDomain().getWriteMethod(
schemaRootPackageName, attribute.getName(), "io"));
}
}
code.addNoIndent(new CodeSnippet("}"));
return code;
}
}
| true | true | protected CodeBlock createGenericSetter(Set<Attribute> attrSet) {
CodeList code = new CodeList();
CodeSnippet snip = new CodeSnippet(true);
boolean suppressWarningsNeeded = false;
for (Attribute attr : attrSet) {
if (attr.getDomain().isComposite()) {
suppressWarningsNeeded = true;
break;
}
}
if (suppressWarningsNeeded) {
snip.add("@SuppressWarnings(\"unchecked\")");
}
snip
.add("public void setAttribute(String attributeName, Object data) throws NoSuchFieldException {");
code.addNoIndent(snip);
for (Attribute attr : attrSet) {
CodeSnippet s = new CodeSnippet();
s.setVariable("name", attr.getName());
s.setVariable("cName", camelCase(attr.getName()));
if (attr.getDomain().isComposite()) {
s.setVariable("attributeClassName", attr.getDomain()
.getJavaAttributeImplementationTypeName(
schemaRootPackageName));
} else {
s.setVariable("attributeClassName", attr.getDomain()
.getJavaClassName(schemaRootPackageName));
}
boolean isEnumDomain = false;
if (attr.getDomain() instanceof EnumDomain) {
isEnumDomain = true;
}
if (isEnumDomain) {
s.add("if (attributeName.equals(\"#name#\")) {");
s.add("\tif (data instanceof String) {");
s.add("\t\t#attributeClassName#.fromString((String) data);");
s.add("\t} else {");
s.add("\t\tset#cName#((#attributeClassName#) data);");
s.add("\t}");
s.add("\treturn;");
s.add("}");
} else {
s.add("if (attributeName.equals(\"#name#\")) {");
s.add("\tset#cName#((#attributeClassName#) data);");
s.add("\treturn;");
s.add("}");
}
code.add(s);
}
code
.add(new CodeSnippet(
"throw new NoSuchFieldException(\"#qualifiedClassName# doesn't contain an attribute \" + attributeName);"));
code.addNoIndent(new CodeSnippet("}"));
return code;
}
| protected CodeBlock createGenericSetter(Set<Attribute> attrSet) {
CodeList code = new CodeList();
CodeSnippet snip = new CodeSnippet(true);
boolean suppressWarningsNeeded = false;
for (Attribute attr : attrSet) {
if (attr.getDomain().isComposite()) {
suppressWarningsNeeded = true;
break;
}
}
if (suppressWarningsNeeded) {
snip.add("@SuppressWarnings(\"unchecked\")");
}
snip
.add("public void setAttribute(String attributeName, Object data) throws NoSuchFieldException {");
code.addNoIndent(snip);
for (Attribute attr : attrSet) {
CodeSnippet s = new CodeSnippet();
s.setVariable("name", attr.getName());
s.setVariable("cName", camelCase(attr.getName()));
if (attr.getDomain().isComposite()) {
s.setVariable("attributeClassName", attr.getDomain()
.getJavaAttributeImplementationTypeName(
schemaRootPackageName));
} else {
s.setVariable("attributeClassName", attr.getDomain()
.getJavaClassName(schemaRootPackageName));
}
boolean isEnumDomain = false;
if (attr.getDomain() instanceof EnumDomain) {
isEnumDomain = true;
}
if (isEnumDomain) {
s.add("if (attributeName.equals(\"#name#\")) {");
s.add("\tif (data instanceof String) {");
s.add("\t\tset#cName#(#attributeClassName#.fromString((String) data));");
s.add("\t} else {");
s.add("\t\tset#cName#((#attributeClassName#) data);");
s.add("\t}");
s.add("\treturn;");
s.add("}");
} else {
s.add("if (attributeName.equals(\"#name#\")) {");
s.add("\tset#cName#((#attributeClassName#) data);");
s.add("\treturn;");
s.add("}");
}
code.add(s);
}
code
.add(new CodeSnippet(
"throw new NoSuchFieldException(\"#qualifiedClassName# doesn't contain an attribute \" + attributeName);"));
code.addNoIndent(new CodeSnippet("}"));
return code;
}
|
diff --git a/src/soardb/DelServlet.java b/src/soardb/DelServlet.java
index 7ca52f0..830b6d0 100644
--- a/src/soardb/DelServlet.java
+++ b/src/soardb/DelServlet.java
@@ -1,62 +1,64 @@
package soardb;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import java.util.logging.Logger;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.EntityNotFoundException;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.google.appengine.api.datastore.Transaction;
import com.google.appengine.api.datastore.TransactionOptions;
import com.google.appengine.api.users.User;
import com.google.appengine.api.users.UserService;
import com.google.appengine.api.users.UserServiceFactory;
@SuppressWarnings("serial")
public class DelServlet extends HttpServlet {
public static final Logger log = Logger.getLogger(DelServlet.class.getName());
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
log.info("in del servlet");
UserService userService = UserServiceFactory.getUserService();
User user = userService.getCurrentUser();
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Key Key = KeyFactory.stringToKey(req.getParameter("key"));
String delete = req.getParameter("delete");
String newsFlag = req.getParameter("news");
String Name = "";
try {
Name = (String)datastore.get(Key).getProperty(N.name);
} catch (EntityNotFoundException e) {
e.printStackTrace();
}
TransactionOptions options = TransactionOptions.Builder.withXG(true);
Transaction tx = datastore.beginTransaction(options);
datastore.delete(Key);
+ tx.commit();
if(newsFlag.equals("true")){
+ tx = datastore.beginTransaction(options);
Date date = new Date();
Entity adminNews = new Entity(N.AdminNews);
adminNews.setProperty(N.blurb,String.format("%s deleted %s: %s", user.getNickname(),delete,Name));
adminNews.setProperty(N.date,date);
datastore.put(adminNews);
}
tx.commit();
resp.setContentType("text/plain");
PrintWriter writer = resp.getWriter();
writer.println("success");
}
}
| false | true | public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
log.info("in del servlet");
UserService userService = UserServiceFactory.getUserService();
User user = userService.getCurrentUser();
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Key Key = KeyFactory.stringToKey(req.getParameter("key"));
String delete = req.getParameter("delete");
String newsFlag = req.getParameter("news");
String Name = "";
try {
Name = (String)datastore.get(Key).getProperty(N.name);
} catch (EntityNotFoundException e) {
e.printStackTrace();
}
TransactionOptions options = TransactionOptions.Builder.withXG(true);
Transaction tx = datastore.beginTransaction(options);
datastore.delete(Key);
if(newsFlag.equals("true")){
Date date = new Date();
Entity adminNews = new Entity(N.AdminNews);
adminNews.setProperty(N.blurb,String.format("%s deleted %s: %s", user.getNickname(),delete,Name));
adminNews.setProperty(N.date,date);
datastore.put(adminNews);
}
tx.commit();
resp.setContentType("text/plain");
PrintWriter writer = resp.getWriter();
writer.println("success");
}
| public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws IOException {
log.info("in del servlet");
UserService userService = UserServiceFactory.getUserService();
User user = userService.getCurrentUser();
DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
Key Key = KeyFactory.stringToKey(req.getParameter("key"));
String delete = req.getParameter("delete");
String newsFlag = req.getParameter("news");
String Name = "";
try {
Name = (String)datastore.get(Key).getProperty(N.name);
} catch (EntityNotFoundException e) {
e.printStackTrace();
}
TransactionOptions options = TransactionOptions.Builder.withXG(true);
Transaction tx = datastore.beginTransaction(options);
datastore.delete(Key);
tx.commit();
if(newsFlag.equals("true")){
tx = datastore.beginTransaction(options);
Date date = new Date();
Entity adminNews = new Entity(N.AdminNews);
adminNews.setProperty(N.blurb,String.format("%s deleted %s: %s", user.getNickname(),delete,Name));
adminNews.setProperty(N.date,date);
datastore.put(adminNews);
}
tx.commit();
resp.setContentType("text/plain");
PrintWriter writer = resp.getWriter();
writer.println("success");
}
|
diff --git a/gwiki/src/main/java/de/micromata/genome/gwiki/controls/GWikiTreeChildrenActionBean.java b/gwiki/src/main/java/de/micromata/genome/gwiki/controls/GWikiTreeChildrenActionBean.java
index 204743c7..db9723c0 100644
--- a/gwiki/src/main/java/de/micromata/genome/gwiki/controls/GWikiTreeChildrenActionBean.java
+++ b/gwiki/src/main/java/de/micromata/genome/gwiki/controls/GWikiTreeChildrenActionBean.java
@@ -1,138 +1,135 @@
////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2010 Micromata GmbH
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
////////////////////////////////////////////////////////////////////////////
package de.micromata.genome.gwiki.controls;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.commons.lang.StringUtils;
import de.micromata.genome.gwiki.model.GWikiElement;
import de.micromata.genome.gwiki.model.GWikiElementInfo;
import de.micromata.genome.gwiki.page.impl.actionbean.ActionBeanBase;
/**
* @author Christian Claus ([email protected])
*
*/
public class GWikiTreeChildrenActionBean extends ActionBeanBase
{
private String rootPage;
private Map<String, String> rootCategories;
public Object onLoadAsync()
{
GWikiElement el = null;
List<GWikiElementInfo> childs = null;
final String superCategory = wikiContext.getRequest().getParameter("id");
final String urlField = wikiContext.getRequest().getParameter("urlField");
final String titleField = wikiContext.getRequest().getParameter("titleField");
final String openTarget = wikiContext.getRequest().getParameter("target");
if (StringUtils.isBlank(superCategory)) {
el = wikiContext.getWikiWeb().findElement(getRootPage());
childs = wikiContext.getElementFinder().getAllDirectChildsByType(el.getElementInfo(), "gwiki");
for (final GWikiElementInfo c : childs) {
getRootCategories().put(c.getId(), c.getTitle());
}
} else {
el = wikiContext.getWikiWeb().findElement(superCategory);
childs = wikiContext.getElementFinder().getAllDirectChilds(el.getElementInfo());
}
final StringBuffer sb = new StringBuffer("");
for (final GWikiElementInfo ei : childs) {
if (wikiContext.getWikiWeb().getAuthorization().isAllowToView(wikiContext, ei) == false) {
continue;
}
if (wikiContext.getElementFinder().getAllDirectChilds(ei).size() > 0) {
sb.append("<li class='jstree-closed' ");
} else {
sb.append("<li ");
}
sb.append("id='").append(ei.getId()).append("'>");
sb.append("<a onclick=\"");
if (StringUtils.isEmpty(openTarget)) {
if (StringUtils.isNotEmpty(urlField)) {
sb.append("$('#" + urlField + "').val('" + ei.getId() + "');");
}
if (StringUtils.isNotEmpty(titleField)) {
sb.append("$('#" + titleField + "').val('" + ei.getTitle() + "');");
}
} else if (StringUtils.equals(openTarget, "true")) {
- String targetLink = wikiContext.getRequest().getContextPath()
- + wikiContext.getRequest().getServletPath()
- + "/"
- + ei.getId();
+ String targetLink = wikiContext.localUrl(ei.getId());
sb.append("javascript:window.location.href='").append(targetLink).append("'");
}
sb.append("\" style=\"cursor:pointer\">");
sb.append(ei.getTitle());
sb.append("</a>");
sb.append("</li>");
}
wikiContext.append(sb.toString());
wikiContext.flush();
return noForward();
}
/**
* @param rootPage the rootPage to set
*/
public void setRootPage(String rootPage)
{
this.rootPage = rootPage;
}
/**
* @return the rootPage
*/
public String getRootPage()
{
if (StringUtils.isBlank(rootPage)) {
GWikiElement home = wikiContext.getWikiWeb().getHomeElement(wikiContext);
if (home != null) {
rootPage = home.getElementInfo().getId();
}
}
return rootPage;
}
/**
* @return the rootCategories
*/
public Map<String, String> getRootCategories()
{
if (this.rootCategories == null) {
this.rootCategories = new HashMap<String, String>();
}
return rootCategories;
}
}
| true | true | public Object onLoadAsync()
{
GWikiElement el = null;
List<GWikiElementInfo> childs = null;
final String superCategory = wikiContext.getRequest().getParameter("id");
final String urlField = wikiContext.getRequest().getParameter("urlField");
final String titleField = wikiContext.getRequest().getParameter("titleField");
final String openTarget = wikiContext.getRequest().getParameter("target");
if (StringUtils.isBlank(superCategory)) {
el = wikiContext.getWikiWeb().findElement(getRootPage());
childs = wikiContext.getElementFinder().getAllDirectChildsByType(el.getElementInfo(), "gwiki");
for (final GWikiElementInfo c : childs) {
getRootCategories().put(c.getId(), c.getTitle());
}
} else {
el = wikiContext.getWikiWeb().findElement(superCategory);
childs = wikiContext.getElementFinder().getAllDirectChilds(el.getElementInfo());
}
final StringBuffer sb = new StringBuffer("");
for (final GWikiElementInfo ei : childs) {
if (wikiContext.getWikiWeb().getAuthorization().isAllowToView(wikiContext, ei) == false) {
continue;
}
if (wikiContext.getElementFinder().getAllDirectChilds(ei).size() > 0) {
sb.append("<li class='jstree-closed' ");
} else {
sb.append("<li ");
}
sb.append("id='").append(ei.getId()).append("'>");
sb.append("<a onclick=\"");
if (StringUtils.isEmpty(openTarget)) {
if (StringUtils.isNotEmpty(urlField)) {
sb.append("$('#" + urlField + "').val('" + ei.getId() + "');");
}
if (StringUtils.isNotEmpty(titleField)) {
sb.append("$('#" + titleField + "').val('" + ei.getTitle() + "');");
}
} else if (StringUtils.equals(openTarget, "true")) {
String targetLink = wikiContext.getRequest().getContextPath()
+ wikiContext.getRequest().getServletPath()
+ "/"
+ ei.getId();
sb.append("javascript:window.location.href='").append(targetLink).append("'");
}
sb.append("\" style=\"cursor:pointer\">");
sb.append(ei.getTitle());
sb.append("</a>");
sb.append("</li>");
}
wikiContext.append(sb.toString());
wikiContext.flush();
return noForward();
}
| public Object onLoadAsync()
{
GWikiElement el = null;
List<GWikiElementInfo> childs = null;
final String superCategory = wikiContext.getRequest().getParameter("id");
final String urlField = wikiContext.getRequest().getParameter("urlField");
final String titleField = wikiContext.getRequest().getParameter("titleField");
final String openTarget = wikiContext.getRequest().getParameter("target");
if (StringUtils.isBlank(superCategory)) {
el = wikiContext.getWikiWeb().findElement(getRootPage());
childs = wikiContext.getElementFinder().getAllDirectChildsByType(el.getElementInfo(), "gwiki");
for (final GWikiElementInfo c : childs) {
getRootCategories().put(c.getId(), c.getTitle());
}
} else {
el = wikiContext.getWikiWeb().findElement(superCategory);
childs = wikiContext.getElementFinder().getAllDirectChilds(el.getElementInfo());
}
final StringBuffer sb = new StringBuffer("");
for (final GWikiElementInfo ei : childs) {
if (wikiContext.getWikiWeb().getAuthorization().isAllowToView(wikiContext, ei) == false) {
continue;
}
if (wikiContext.getElementFinder().getAllDirectChilds(ei).size() > 0) {
sb.append("<li class='jstree-closed' ");
} else {
sb.append("<li ");
}
sb.append("id='").append(ei.getId()).append("'>");
sb.append("<a onclick=\"");
if (StringUtils.isEmpty(openTarget)) {
if (StringUtils.isNotEmpty(urlField)) {
sb.append("$('#" + urlField + "').val('" + ei.getId() + "');");
}
if (StringUtils.isNotEmpty(titleField)) {
sb.append("$('#" + titleField + "').val('" + ei.getTitle() + "');");
}
} else if (StringUtils.equals(openTarget, "true")) {
String targetLink = wikiContext.localUrl(ei.getId());
sb.append("javascript:window.location.href='").append(targetLink).append("'");
}
sb.append("\" style=\"cursor:pointer\">");
sb.append(ei.getTitle());
sb.append("</a>");
sb.append("</li>");
}
wikiContext.append(sb.toString());
wikiContext.flush();
return noForward();
}
|
diff --git a/facebook/src/com/facebook/WebDialog.java b/facebook/src/com/facebook/WebDialog.java
index 3ca2be8..e41486a 100644
--- a/facebook/src/com/facebook/WebDialog.java
+++ b/facebook/src/com/facebook/WebDialog.java
@@ -1,536 +1,536 @@
package com.facebook;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.net.http.SslError;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.webkit.SslErrorHandler;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import com.facebook.android.*;
/**
* This class provides a mechanism for displaying Facebook Web dialogs inside a Dialog. Helper
* methods are provided to construct commonly-used dialogs, or a caller can specify arbitrary
* parameters to call other dialogs.
*/
public class WebDialog extends Dialog {
private static final String LOG_TAG = Settings.LOG_TAG_BASE + "WebDialog";
private static final String DISPLAY_TOUCH = "touch";
private static final String USER_AGENT = "user_agent";
private static final String OAUTH_DIALOG = "oauth";
private static final String FEED_DIALOG = "feed";
private static final String APPREQUESTS_DIALOG = "apprequests";
private static final String TO_PARAM = "to";
private static final String CAPTION_PARAM = "caption";
private static final String DESCRIPTION_PARAM = "description";
private static final String PICTURE_PARAM = "picture";
private static final String NAME_PARAM = "name";
private static final String MESSAGE_PARAM = "message";
static final String REDIRECT_URI = "fbconnect://success";
static final String CANCEL_URI = "fbconnect://cancel";
protected static final int DEFAULT_THEME = android.R.style.Theme_Translucent_NoTitleBar;
private static String applicationIdForSessionlessDialogs;
private String url;
private OnCompleteListener onCompleteListener;
private WebView webView;
private ProgressDialog spinner;
private ImageView crossImageView;
private FrameLayout contentFrameLayout;
private boolean listenerCalled = false;
/**
* Interface that implements a listener to be called when the user's interaction with the
* dialog completes, whether because the dialog finished successfully, or it was cancelled,
* or an error was encountered.
*/
public interface OnCompleteListener {
/**
* Called when the dialog completes.
*
* @param values on success, contains the values returned by the dialog
* @param error on an error, contains an exception describing the error
*/
void onComplete(Bundle values, FacebookException error);
}
/**
* Gets the default application ID that will be used for dialogs created without a corresponding
* valid Session.
*
* @return the application ID
*/
public static String getApplicationIdForSessionlessDialogs() {
return applicationIdForSessionlessDialogs;
}
/**
* If a dialog is created without a corresponding valid Session, the application ID to pass as
* part of the URL must first be specified via this method. This application ID will be used for
* all dialogs created without a Session. If a Session is specified, the application ID associated
* with that Session will override this default setting.
*
* @param applicationIdForSessonlessDialogs
* the application ID to use
*/
public static void setApplicationIdForSessionlessDialogs(String applicationIdForSessonlessDialogs) {
WebDialog.applicationIdForSessionlessDialogs = applicationIdForSessonlessDialogs;
}
/**
* Creates a new WebDialog populated with a URL constructed from the provided parameters. The
* dialog is ready to be shown via {@link android.app.Dialog#show()}.
*
* @param context the Context to use for displaying the dialog
* @param session a Session which, if opened, will be used to populate the application ID and
* access token to use for the dialog call
* @param action the portion of the dialog URL after "dialog/"
* @param parameters a Bundle containing parameters which will be encoded as part of the URL
* @param listener an optional listener which will be notified when the dialog has completed
* @return a WebDialog which is ready to be shown
*/
public static WebDialog createDialog(Context context, Session session, String action, Bundle parameters,
OnCompleteListener listener) {
return createDialog(context, session, action, parameters, DEFAULT_THEME, listener);
}
/**
* Creates a new WebDialog populated with a URL constructed from the provided parameters. The
* dialog is ready to be shown via {@link android.app.Dialog#show()}. The dialog's theme can be
* customized to modify how it is displayed.
*
* @param context the Context to use for displaying the dialog
* @param session a Session which, if opened, will be used to populate the application ID and
* access token to use for the dialog call
* @param action the portion of the dialog URL after "dialog/"
* @param parameters a Bundle containing parameters which will be encoded as part of the URL
* @param theme a theme identifier which will be passed to the Dialog class
* @param listener an optional listener which will be notified when the dialog has completed
* @return a WebDialog which is ready to be shown
*/
public static WebDialog createDialog(Context context, Session session, String action, Bundle parameters, int theme,
OnCompleteListener listener) {
if (parameters == null) {
parameters = new Bundle();
}
if (session == null && Utility.isNullOrEmpty(applicationIdForSessionlessDialogs)) {
throw new FacebookException(
"Must specify either a Session or a default application ID for session-less dialogs");
}
parameters.putString("app_id",
(session != null) ? session.getApplicationId() : applicationIdForSessionlessDialogs);
if (session != null && session.isOpened()) {
parameters.putString("access_token", session.getAccessToken());
}
if (!parameters.containsKey(ServerProtocol.DIALOG_PARAM_REDIRECT_URI)) {
parameters.putString(ServerProtocol.DIALOG_PARAM_REDIRECT_URI, REDIRECT_URI);
}
WebDialog result = new WebDialog(context, action, parameters, theme);
result.setOnCompleteListener(listener);
return result;
}
/**
* Creates a WebDialog which will display the Feed dialog to post an item to the user's Timeline.
* The dialog is ready to be shown via {@link android.app.Dialog#show()}. The dialog's theme can be
* customized to modify how it is displayed. More documentation of the Feed dialog is available at
* https://developers.facebook.com/docs/reference/dialogs/feed/.
*
* @param context the Context to use for displaying the dialog
* @param session a Session which, if opened, will be used to populate the application ID and
* access token to use for the dialog call
* @param caption an optional caption to display in the dialog
* @param description an optional description to display in the dialog
* @param pictureUrl an optional URL of an icon to display in the dialog
* @param name an optional name to display in the dialog
* @param parameters additional parameters to pass to the dialog
* @param theme a theme identifier which will be passed to the Dialog class
* @param listener an optional listener which will be notified when the dialog has completed
* @return a WebDialog which is ready to be shown
*/
public static WebDialog createFeedDialog(Context context, Session session, String caption, String description,
String pictureUrl, String name, Bundle parameters, int theme, OnCompleteListener listener) {
return createFeedDialog(context, session, null, caption, description, pictureUrl, name, parameters, theme,
listener);
}
/**
* Creates a WebDialog which will display the Feed dialog to post an item to the another user's Timeline.
* The dialog is ready to be shown via {@link android.app.Dialog#show()}. The dialog's theme can be
* customized to modify how it is displayed. More documentation of the Feed dialog is available at
* https://developers.facebook.com/docs/reference/dialogs/feed/.
*
* @param context the Context to use for displaying the dialog
* @param session a Session which, if opened, will be used to populate the application ID and
* access token to use for the dialog call
* @param toProfileId the ID of the profile to post to; if null or empty, this will post to the
* user's own Timeline
* @param caption an optional caption to display in the dialog
* @param description an optional description to display in the dialog
* @param pictureUrl an optional URL of an icon to display in the dialog
* @param name an optional name to display in the dialog
* @param parameters additional parameters to pass to the dialog
* @param theme a theme identifier which will be passed to the Dialog class
* @param listener an optional listener which will be notified when the dialog has completed
* @return a WebDialog which is ready to be shown
*/
public static WebDialog createFeedDialog(Context context, Session session, String toProfileId, String caption,
String description,
String pictureUrl, String name, Bundle parameters, int theme, OnCompleteListener listener) {
if (parameters == null) {
parameters = new Bundle();
}
if (!Utility.isNullOrEmpty(toProfileId)) {
parameters.putString(TO_PARAM, toProfileId);
}
if (!Utility.isNullOrEmpty(caption)) {
parameters.putString(CAPTION_PARAM, caption);
}
if (!Utility.isNullOrEmpty(description)) {
parameters.putString(DESCRIPTION_PARAM, description);
}
if (!Utility.isNullOrEmpty(pictureUrl)) {
parameters.putString(PICTURE_PARAM, pictureUrl);
}
if (!Utility.isNullOrEmpty(name)) {
parameters.putString(NAME_PARAM, name);
}
WebDialog result = createDialog(context, session, FEED_DIALOG, parameters, theme, listener);
return result;
}
/**
* Creates a WebDialog which will display the Request dialog to send a request to another user.
* The dialog is ready to be shown via {@link android.app.Dialog#show()}. The dialog's theme can be
* customized to modify how it is displayed. More documentation of the Requests dialog is available at
* https://developers.facebook.com/docs/reference/dialogs/requests/.
*
* @param context the Context to use for displaying the dialog
* @param session a Session which, if opened, will be used to populate the application ID and
* access token to use for the dialog call
* @param toProfileId an optional profile ID which the request will be sent to; if not specified,
* the dialog will prompt the user to select a profile
* @param message an optional message to display in the dialog
* @param parameters additional parameters to pass to the dialog
* @param theme a theme identifier which will be passed to the Dialog class
* @param listener an optional listener which will be notified when the dialog has completed
* @return a WebDialog which is ready to be shown
*/
public static WebDialog createAppRequestDialog(Context context, Session session, String toProfileId, String message,
Bundle parameters, int theme, OnCompleteListener listener) {
if (parameters == null) {
parameters = new Bundle();
}
if (!Utility.isNullOrEmpty(message)) {
parameters.putString(MESSAGE_PARAM, message);
}
if (!Utility.isNullOrEmpty(toProfileId)) {
parameters.putString(TO_PARAM, toProfileId);
}
WebDialog result = createDialog(context, session, APPREQUESTS_DIALOG, parameters, theme, listener);
return result;
}
static WebDialog createAuthDialog(Context context, String applicationId, int theme) {
Bundle parameters = new Bundle();
parameters.putString(ServerProtocol.DIALOG_PARAM_REDIRECT_URI, REDIRECT_URI);
parameters.putString(ServerProtocol.DIALOG_PARAM_CLIENT_ID, applicationId);
return new WebDialog(context, OAUTH_DIALOG, parameters, theme);
}
/**
* Constructor which can be used to display a dialog with an already-constructed URL.
*
* @param context the context to use to display the dialog
* @param url the URL of the Web Dialog to display; no validation is done on this URL, but it should
* be a valid URL pointing to a Facebook Web Dialog
*/
public WebDialog(Context context, String url) {
this(context, url, DEFAULT_THEME);
}
/**
* Constructor which can be used to display a dialog with an already-constructed URL and a custom theme.
*
* @param context the context to use to display the dialog
* @param url the URL of the Web Dialog to display; no validation is done on this URL, but it should
* be a valid URL pointing to a Facebook Web Dialog
* @param theme identifier of a theme to pass to the Dialog class
*/
public WebDialog(Context context, String url, int theme) {
super(context, (theme == 0) ? DEFAULT_THEME : theme);
this.url = url;
}
/**
* Constructor which will construct the URL of the Web dialog based on the specified parameters.
*
* @param context the context to use to display the dialog
* @param action the portion of the dialog URL following "dialog/"
* @param parameters parameters which will be included as part of the URL
* @param theme identifier of a theme to pass to the Dialog class
*/
public WebDialog(Context context, String action, Bundle parameters, int theme) {
this(context, null, theme);
if (parameters == null) {
parameters = new Bundle();
}
parameters.putString(ServerProtocol.DIALOG_PARAM_DISPLAY, DISPLAY_TOUCH);
parameters.putString(ServerProtocol.DIALOG_PARAM_TYPE, USER_AGENT);
Uri uri = Utility.buildUri(ServerProtocol.DIALOG_AUTHORITY, ServerProtocol.DIALOG_PATH + action, parameters);
this.url = uri.toString();
}
/**
* Sets the listener which will be notified when the dialog finishes.
*
* @param listener the listener to notify, or null if no notification is desired
*/
public void setOnCompleteListener(OnCompleteListener listener) {
onCompleteListener = listener;
}
/**
* Gets the listener which will be notified when the dialog finishes.
*
* @return the listener, or null if none has been specified
*/
public OnCompleteListener getOnCompleteListener() {
return onCompleteListener;
}
@Override
public void dismiss() {
if (webView != null) {
webView.stopLoading();
}
if (spinner.isShowing()) {
spinner.dismiss();
}
super.dismiss();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialogInterface) {
sendCancelToListener();
}
});
spinner = new ProgressDialog(getContext());
spinner.requestWindowFeature(Window.FEATURE_NO_TITLE);
spinner.setMessage(getContext().getString(R.string.com_facebook_loading));
spinner.setOnCancelListener(new OnCancelListener() {
@Override
public void onCancel(DialogInterface dialogInterface) {
sendCancelToListener();
WebDialog.this.dismiss();
}
});
requestWindowFeature(Window.FEATURE_NO_TITLE);
contentFrameLayout = new FrameLayout(getContext());
/* Create the 'x' image, but don't add to the contentFrameLayout layout yet
* at this point, we only need to know its drawable width and height
* to place the webview
*/
createCrossImage();
/* Now we know 'x' drawable width and height,
* layout the webivew and add it the contentFrameLayout layout
*/
int crossWidth = crossImageView.getDrawable().getIntrinsicWidth();
setUpWebView(crossWidth / 2);
/* Finally add the 'x' image to the contentFrameLayout layout and
* add contentFrameLayout to the Dialog view
*/
contentFrameLayout.addView(crossImageView, new ViewGroup.LayoutParams(
ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT));
addContentView(contentFrameLayout,
new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
}
private void sendSuccessToListener(Bundle values) {
if (onCompleteListener != null && !listenerCalled) {
listenerCalled = true;
onCompleteListener.onComplete(values, null);
}
}
private void sendErrorToListener(Throwable error) {
if (onCompleteListener != null && !listenerCalled) {
listenerCalled = true;
FacebookException facebookException = null;
if (error instanceof FacebookException) {
facebookException = (FacebookException) error;
} else {
facebookException = new FacebookException(error);
}
onCompleteListener.onComplete(null, facebookException);
}
}
private void sendCancelToListener() {
sendErrorToListener(new FacebookOperationCanceledException());
}
private void createCrossImage() {
crossImageView = new ImageView(getContext());
// Dismiss the dialog when user click on the 'x'
crossImageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
sendCancelToListener();
WebDialog.this.dismiss();
}
});
Drawable crossDrawable = getContext().getResources().getDrawable(R.drawable.com_facebook_close);
crossImageView.setImageDrawable(crossDrawable);
/* 'x' should not be visible while webview is loading
* make it visible only after webview has fully loaded
*/
crossImageView.setVisibility(View.INVISIBLE);
}
@SuppressLint("SetJavaScriptEnabled")
private void setUpWebView(int margin) {
LinearLayout webViewContainer = new LinearLayout(getContext());
webView = new WebView(getContext());
webView.setVerticalScrollBarEnabled(false);
webView.setHorizontalScrollBarEnabled(false);
webView.setWebViewClient(new DialogWebViewClient());
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl(url);
webView.setLayoutParams(new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
ViewGroup.LayoutParams.MATCH_PARENT));
webView.setVisibility(View.INVISIBLE);
webView.getSettings().setSavePassword(false);
webViewContainer.setPadding(margin, margin, margin, margin);
webViewContainer.addView(webView);
contentFrameLayout.addView(webViewContainer);
}
private class DialogWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Util.logd(LOG_TAG, "Redirect URL: " + url);
if (url.startsWith(WebDialog.REDIRECT_URI)) {
Bundle values = Util.parseUrl(url);
String error = values.getString("error");
if (error == null) {
error = values.getString("error_type");
}
String errorMessage = values.getString("error_msg");
if (errorMessage == null) {
errorMessage = values.getString("error_description");
}
String errorCodeString = values.getString("error_code");
int errorCode = FacebookRequestError.INVALID_ERROR_CODE;
if (!Utility.isNullOrEmpty(errorCodeString)) {
try {
errorCode = Integer.parseInt(errorCodeString);
} catch (NumberFormatException ex) {
errorCode = FacebookRequestError.INVALID_ERROR_CODE;
}
}
if (Utility.isNullOrEmpty(error) && Utility
- .isNullOrEmpty(errorMessage) && errorCode != FacebookRequestError.INVALID_ERROR_CODE) {
+ .isNullOrEmpty(errorMessage) && errorCode == FacebookRequestError.INVALID_ERROR_CODE) {
sendSuccessToListener(values);
} else if (error != null && (error.equals("access_denied") ||
error.equals("OAuthAccessDeniedException"))) {
sendCancelToListener();
} else {
FacebookRequestError requestError = new FacebookRequestError(errorCode, error, errorMessage);
sendErrorToListener(new FacebookServiceException(requestError, errorMessage));
}
WebDialog.this.dismiss();
return true;
} else if (url.startsWith(WebDialog.CANCEL_URI)) {
sendCancelToListener();
WebDialog.this.dismiss();
return true;
} else if (url.contains(DISPLAY_TOUCH)) {
return false;
}
// launch non-dialog URLs in a full browser
getContext().startActivity(
new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
return true;
}
@Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
super.onReceivedError(view, errorCode, description, failingUrl);
sendErrorToListener(new FacebookDialogException(description, errorCode, failingUrl));
WebDialog.this.dismiss();
}
@Override
public void onReceivedSslError(WebView view, SslErrorHandler handler, SslError error) {
super.onReceivedSslError(view, handler, error);
sendErrorToListener(new FacebookDialogException(null, ERROR_FAILED_SSL_HANDSHAKE, null));
handler.cancel();
WebDialog.this.dismiss();
}
@Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
Util.logd(LOG_TAG, "Webview loading URL: " + url);
super.onPageStarted(view, url, favicon);
spinner.show();
}
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
spinner.dismiss();
/*
* Once web view is fully loaded, set the contentFrameLayout background to be transparent
* and make visible the 'x' image.
*/
contentFrameLayout.setBackgroundColor(Color.TRANSPARENT);
webView.setVisibility(View.VISIBLE);
crossImageView.setVisibility(View.VISIBLE);
}
}
}
| true | true | public boolean shouldOverrideUrlLoading(WebView view, String url) {
Util.logd(LOG_TAG, "Redirect URL: " + url);
if (url.startsWith(WebDialog.REDIRECT_URI)) {
Bundle values = Util.parseUrl(url);
String error = values.getString("error");
if (error == null) {
error = values.getString("error_type");
}
String errorMessage = values.getString("error_msg");
if (errorMessage == null) {
errorMessage = values.getString("error_description");
}
String errorCodeString = values.getString("error_code");
int errorCode = FacebookRequestError.INVALID_ERROR_CODE;
if (!Utility.isNullOrEmpty(errorCodeString)) {
try {
errorCode = Integer.parseInt(errorCodeString);
} catch (NumberFormatException ex) {
errorCode = FacebookRequestError.INVALID_ERROR_CODE;
}
}
if (Utility.isNullOrEmpty(error) && Utility
.isNullOrEmpty(errorMessage) && errorCode != FacebookRequestError.INVALID_ERROR_CODE) {
sendSuccessToListener(values);
} else if (error != null && (error.equals("access_denied") ||
error.equals("OAuthAccessDeniedException"))) {
sendCancelToListener();
} else {
FacebookRequestError requestError = new FacebookRequestError(errorCode, error, errorMessage);
sendErrorToListener(new FacebookServiceException(requestError, errorMessage));
}
WebDialog.this.dismiss();
return true;
} else if (url.startsWith(WebDialog.CANCEL_URI)) {
sendCancelToListener();
WebDialog.this.dismiss();
return true;
} else if (url.contains(DISPLAY_TOUCH)) {
return false;
}
// launch non-dialog URLs in a full browser
getContext().startActivity(
new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
return true;
}
| public boolean shouldOverrideUrlLoading(WebView view, String url) {
Util.logd(LOG_TAG, "Redirect URL: " + url);
if (url.startsWith(WebDialog.REDIRECT_URI)) {
Bundle values = Util.parseUrl(url);
String error = values.getString("error");
if (error == null) {
error = values.getString("error_type");
}
String errorMessage = values.getString("error_msg");
if (errorMessage == null) {
errorMessage = values.getString("error_description");
}
String errorCodeString = values.getString("error_code");
int errorCode = FacebookRequestError.INVALID_ERROR_CODE;
if (!Utility.isNullOrEmpty(errorCodeString)) {
try {
errorCode = Integer.parseInt(errorCodeString);
} catch (NumberFormatException ex) {
errorCode = FacebookRequestError.INVALID_ERROR_CODE;
}
}
if (Utility.isNullOrEmpty(error) && Utility
.isNullOrEmpty(errorMessage) && errorCode == FacebookRequestError.INVALID_ERROR_CODE) {
sendSuccessToListener(values);
} else if (error != null && (error.equals("access_denied") ||
error.equals("OAuthAccessDeniedException"))) {
sendCancelToListener();
} else {
FacebookRequestError requestError = new FacebookRequestError(errorCode, error, errorMessage);
sendErrorToListener(new FacebookServiceException(requestError, errorMessage));
}
WebDialog.this.dismiss();
return true;
} else if (url.startsWith(WebDialog.CANCEL_URI)) {
sendCancelToListener();
WebDialog.this.dismiss();
return true;
} else if (url.contains(DISPLAY_TOUCH)) {
return false;
}
// launch non-dialog URLs in a full browser
getContext().startActivity(
new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
return true;
}
|
diff --git a/src/org/python/core/PyString.java b/src/org/python/core/PyString.java
index 091a5af6..3b4f3206 100644
--- a/src/org/python/core/PyString.java
+++ b/src/org/python/core/PyString.java
@@ -1,3329 +1,3335 @@
/// Copyright (c) Corporation for National Research Initiatives
package org.python.core;
import org.python.core.stringlib.FieldNameIterator;
import org.python.core.stringlib.InternalFormatSpec;
import org.python.core.stringlib.InternalFormatSpecParser;
import org.python.core.stringlib.MarkupIterator;
import org.python.core.util.ExtraMath;
import org.python.core.util.StringUtil;
import org.python.expose.ExposedMethod;
import org.python.expose.ExposedNew;
import org.python.expose.ExposedType;
import org.python.expose.MethodType;
import java.math.BigInteger;
/**
* A builtin python string.
*/
@ExposedType(name = "str", doc = BuiltinDocs.str_doc)
public class PyString extends PyBaseString implements MemoryViewProtocol
{
public static final PyType TYPE = PyType.fromClass(PyString.class);
protected String string; // cannot make final because of Python intern support
protected transient boolean interned=false;
public String getString() {
return string;
}
// for PyJavaClass.init()
public PyString() {
this(TYPE, "");
}
public PyString(PyType subType, String string) {
super(subType);
if (string == null) {
throw new IllegalArgumentException(
"Cannot create PyString from null!");
}
this.string = string;
}
public PyString(String string) {
this(TYPE, string);
}
public PyString(char c) {
this(TYPE,String.valueOf(c));
}
PyString(StringBuilder buffer) {
this(TYPE, new String(buffer));
}
/**
* Creates a PyString from an already interned String. Just means it won't
* be reinterned if used in a place that requires interned Strings.
*/
public static PyString fromInterned(String interned) {
PyString str = new PyString(TYPE, interned);
str.interned = true;
return str;
}
@ExposedNew
static PyObject str_new(PyNewWrapper new_, boolean init, PyType subtype,
PyObject[] args, String[] keywords) {
ArgParser ap = new ArgParser("str", args, keywords, new String[] { "object" }, 0);
PyObject S = ap.getPyObject(0, null);
if(new_.for_type == subtype) {
if(S == null) {
return new PyString("");
}
return new PyString(S.__str__().toString());
} else {
if (S == null) {
return new PyStringDerived(subtype, "");
}
return new PyStringDerived(subtype, S.__str__().toString());
}
}
public int[] toCodePoints() {
int n = getString().length();
int[] codePoints = new int[n];
for (int i = 0; i < n; i++) {
codePoints[i] = getString().charAt(i);
}
return codePoints;
}
public MemoryView getMemoryView() {
return new MemoryView() {
// beginning of support
public String get_format() {
return "B";
}
public int get_itemsize() {
return 2;
}
public PyTuple get_shape() {
return new PyTuple(Py.newInteger(getString().length()));
}
public int get_ndim() {
return 1;
}
public PyTuple get_strides() {
return new PyTuple(Py.newInteger(1));
}
public boolean get_readonly() {
return true;
}
};
}
public String substring(int start, int end) {
return getString().substring(start, end);
}
@Override
public PyString __str__() {
return str___str__();
}
public
@ExposedMethod(doc = BuiltinDocs.str___str___doc)
final PyString str___str__() {
if (getClass() == PyString.class) {
return this;
}
return new PyString(getString());
}
@Override
public PyUnicode __unicode__() {
return new PyUnicode(this);
}
@Override
public int __len__() {
return str___len__();
}
@ExposedMethod(doc = BuiltinDocs.str___len___doc)
final int str___len__() {
return getString().length();
}
@Override
public String toString() {
return getString();
}
public String internedString() {
if (interned)
return getString();
else {
string = getString().intern();
interned = true;
return getString();
}
}
@Override
public PyString __repr__() {
return str___repr__();
}
@ExposedMethod(doc = BuiltinDocs.str___repr___doc)
final PyString str___repr__() {
return new PyString(encode_UnicodeEscape(getString(), true));
}
private static char[] hexdigit = "0123456789abcdef".toCharArray();
public static String encode_UnicodeEscape(String str,
boolean use_quotes)
{
int size = str.length();
StringBuilder v = new StringBuilder(str.length());
char quote = 0;
if (use_quotes) {
quote = str.indexOf('\'') >= 0 &&
str.indexOf('"') == -1 ? '"' : '\'';
v.append(quote);
}
for (int i = 0; size-- > 0; ) {
int ch = str.charAt(i++);
/* Escape quotes */
if ((use_quotes && ch == quote) || ch == '\\') {
v.append('\\');
v.append((char) ch);
continue;
}
/* Map UTF-16 surrogate pairs to Unicode \UXXXXXXXX escapes */
else if (ch >= 0xD800 && ch < 0xDC00) {
char ch2 = str.charAt(i++);
size--;
if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
int ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000;
v.append('\\');
v.append('U');
v.append(hexdigit[(ucs >> 28) & 0xf]);
v.append(hexdigit[(ucs >> 24) & 0xf]);
v.append(hexdigit[(ucs >> 20) & 0xf]);
v.append(hexdigit[(ucs >> 16) & 0xf]);
v.append(hexdigit[(ucs >> 12) & 0xf]);
v.append(hexdigit[(ucs >> 8) & 0xf]);
v.append(hexdigit[(ucs >> 4) & 0xf]);
v.append(hexdigit[ucs & 0xf]);
continue;
}
/* Fall through: isolated surrogates are copied as-is */
i--;
size++;
}
/* Map 16-bit characters to '\\uxxxx' */
if (ch >= 256) {
v.append('\\');
v.append('u');
v.append(hexdigit[(ch >> 12) & 0xf]);
v.append(hexdigit[(ch >> 8) & 0xf]);
v.append(hexdigit[(ch >> 4) & 0xf]);
v.append(hexdigit[ch & 15]);
}
/* Map special whitespace to '\t', \n', '\r' */
else if (ch == '\t') v.append("\\t");
else if (ch == '\n') v.append("\\n");
else if (ch == '\r') v.append("\\r");
/* Map non-printable US ASCII to '\ooo' */
else if (ch < ' ' || ch >= 127) {
v.append('\\');
v.append('x');
v.append(hexdigit[(ch >> 4) & 0xf]);
v.append(hexdigit[ch & 0xf]);
}
/* Copy everything else as-is */
else
v.append((char) ch);
}
if (use_quotes)
v.append(quote);
return v.toString();
}
private static ucnhashAPI pucnHash = null;
public static String decode_UnicodeEscape(String str,
int start,
int end,
String errors,
boolean unicode) {
StringBuilder v = new StringBuilder(end - start);
for(int s = start; s < end;) {
char ch = str.charAt(s);
/* Non-escape characters are interpreted as Unicode ordinals */
if(ch != '\\') {
v.append(ch);
s++;
continue;
}
int loopStart = s;
/* \ - Escapes */
s++;
if(s == end) {
s = codecs.insertReplacementAndGetResume(v,
errors,
"unicodeescape",
str,
loopStart,
s + 1,
"\\ at end of string");
continue;
}
ch = str.charAt(s++);
switch(ch){
/* \x escapes */
case '\n':
break;
case '\\':
v.append('\\');
break;
case '\'':
v.append('\'');
break;
case '\"':
v.append('\"');
break;
case 'b':
v.append('\b');
break;
case 'f':
v.append('\014');
break; /* FF */
case 't':
v.append('\t');
break;
case 'n':
v.append('\n');
break;
case 'r':
v.append('\r');
break;
case 'v':
v.append('\013');
break; /* VT */
case 'a':
v.append('\007');
break; /* BEL, not classic C */
/* \OOO (octal) escapes */
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
int x = Character.digit(ch, 8);
for(int j = 0; j < 2 && s < end; j++, s++) {
ch = str.charAt(s);
if(ch < '0' || ch > '7')
break;
x = (x << 3) + Character.digit(ch, 8);
}
v.append((char)x);
break;
case 'x':
s = hexescape(v, errors, 2, s, str, end, "truncated \\xXX");
break;
case 'u':
if(!unicode) {
v.append('\\');
v.append('u');
break;
}
s = hexescape(v,
errors,
4,
s,
str,
end,
"truncated \\uXXXX");
break;
case 'U':
if(!unicode) {
v.append('\\');
v.append('U');
break;
}
s = hexescape(v,
errors,
8,
s,
str,
end,
"truncated \\UXXXXXXXX");
break;
case 'N':
if(!unicode) {
v.append('\\');
v.append('N');
break;
}
/*
* Ok, we need to deal with Unicode Character Names now,
* make sure we've imported the hash table data...
*/
if(pucnHash == null) {
PyObject mod = imp.importName("ucnhash", true);
mod = mod.__call__();
pucnHash = (ucnhashAPI)mod.__tojava__(Object.class);
if(pucnHash.getCchMax() < 0)
throw Py.UnicodeError("Unicode names not loaded");
}
if(str.charAt(s) == '{') {
int startName = s + 1;
int endBrace = startName;
/*
* look for either the closing brace, or we exceed the
* maximum length of the unicode character names
*/
int maxLen = pucnHash.getCchMax();
while(endBrace < end && str.charAt(endBrace) != '}'
&& (endBrace - startName) <= maxLen) {
endBrace++;
}
if(endBrace != end && str.charAt(endBrace) == '}') {
int value = pucnHash.getValue(str,
startName,
endBrace);
if(storeUnicodeCharacter(value, v)) {
s = endBrace + 1;
} else {
s = codecs.insertReplacementAndGetResume(v,
errors,
"unicodeescape",
str,
loopStart,
endBrace + 1,
"illegal Unicode character");
}
} else {
s = codecs.insertReplacementAndGetResume(v,
errors,
"unicodeescape",
str,
loopStart,
endBrace,
"malformed \\N character escape");
}
break;
} else {
s = codecs.insertReplacementAndGetResume(v,
errors,
"unicodeescape",
str,
loopStart,
s + 1,
"malformed \\N character escape");
}
break;
default:
v.append('\\');
v.append(str.charAt(s - 1));
break;
}
}
return v.toString();
}
private static int hexescape(StringBuilder partialDecode,
String errors,
int digits,
int hexDigitStart,
String str,
int size,
String errorMessage) {
if(hexDigitStart + digits > size) {
return codecs.insertReplacementAndGetResume(partialDecode,
errors,
"unicodeescape",
str,
hexDigitStart - 2,
size,
errorMessage);
}
int i = 0;
int x = 0;
for(; i < digits; ++i) {
char c = str.charAt(hexDigitStart + i);
int d = Character.digit(c, 16);
if(d == -1) {
return codecs.insertReplacementAndGetResume(partialDecode,
errors,
"unicodeescape",
str,
hexDigitStart - 2,
hexDigitStart + i + 1,
errorMessage);
}
x = (x << 4) & ~0xF;
if(c >= '0' && c <= '9')
x += c - '0';
else if(c >= 'a' && c <= 'f')
x += 10 + c - 'a';
else
x += 10 + c - 'A';
}
if(storeUnicodeCharacter(x, partialDecode)) {
return hexDigitStart + i;
} else {
return codecs.insertReplacementAndGetResume(partialDecode,
errors,
"unicodeescape",
str,
hexDigitStart - 2,
hexDigitStart + i + 1,
"illegal Unicode character");
}
}
/*pass in an int since this can be a UCS-4 character */
private static boolean storeUnicodeCharacter(int value,
StringBuilder partialDecode) {
if (value < 0 || (value >= 0xD800 && value <= 0xDFFF)) {
return false;
} else if (value <= PySystemState.maxunicode) {
partialDecode.appendCodePoint(value);
return true;
}
return false;
}
@ExposedMethod(doc = BuiltinDocs.str___getitem___doc)
final PyObject str___getitem__(PyObject index) {
PyObject ret = seq___finditem__(index);
if (ret == null) {
throw Py.IndexError("string index out of range");
}
return ret;
}
//XXX: need doc
@ExposedMethod(defaults = "null")
final PyObject str___getslice__(PyObject start, PyObject stop, PyObject step) {
return seq___getslice__(start, stop, step);
}
@Override
public int __cmp__(PyObject other) {
return str___cmp__(other);
}
@ExposedMethod(type = MethodType.CMP)
final int str___cmp__(PyObject other) {
if (!(other instanceof PyString))
return -2;
int c = getString().compareTo(((PyString) other).getString());
return c < 0 ? -1 : c > 0 ? 1 : 0;
}
@Override
public PyObject __eq__(PyObject other) {
return str___eq__(other);
}
@ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.str___eq___doc)
final PyObject str___eq__(PyObject other) {
String s = coerce(other);
if (s == null)
return null;
return getString().equals(s) ? Py.True : Py.False;
}
@Override
public PyObject __ne__(PyObject other) {
return str___ne__(other);
}
@ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.str___ne___doc)
final PyObject str___ne__(PyObject other) {
String s = coerce(other);
if (s == null)
return null;
return getString().equals(s) ? Py.False : Py.True;
}
@Override
public PyObject __lt__(PyObject other) {
return str___lt__(other);
}
@ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.str___lt___doc)
final PyObject str___lt__(PyObject other){
String s = coerce(other);
if (s == null)
return null;
return getString().compareTo(s) < 0 ? Py.True : Py.False;
}
@Override
public PyObject __le__(PyObject other) {
return str___le__(other);
}
@ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.str___le___doc)
final PyObject str___le__(PyObject other){
String s = coerce(other);
if (s == null)
return null;
return getString().compareTo(s) <= 0 ? Py.True : Py.False;
}
@Override
public PyObject __gt__(PyObject other) {
return str___gt__(other);
}
@ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.str___gt___doc)
final PyObject str___gt__(PyObject other){
String s = coerce(other);
if (s == null)
return null;
return getString().compareTo(s) > 0 ? Py.True : Py.False;
}
@Override
public PyObject __ge__(PyObject other) {
return str___ge__(other);
}
@ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.str___ge___doc)
final PyObject str___ge__(PyObject other){
String s = coerce(other);
if (s == null)
return null;
return getString().compareTo(s) >= 0 ? Py.True : Py.False;
}
private static String coerce(PyObject o) {
if (o instanceof PyString)
return o.toString();
return null;
}
@Override
public int hashCode() {
return str___hash__();
}
@ExposedMethod(doc = BuiltinDocs.str___hash___doc)
final int str___hash__() {
return getString().hashCode();
}
/**
* @return a byte array with one byte for each char in this object's
* underlying String. Each byte contains the low-order bits of its
* corresponding char.
*/
public byte[] toBytes() {
return StringUtil.toBytes(getString());
}
@Override
public Object __tojava__(Class<?> c) {
if (c.isAssignableFrom(String.class)) {
return getString();
}
if (c == Character.TYPE || c == Character.class)
if (getString().length() == 1)
return new Character(getString().charAt(0));
if (c.isArray()) {
if (c.getComponentType() == Byte.TYPE)
return toBytes();
if (c.getComponentType() == Character.TYPE)
return getString().toCharArray();
}
if (c.isInstance(this))
return this;
return Py.NoConversion;
}
protected PyObject pyget(int i) {
return Py.newString(getString().charAt(i));
}
protected PyObject getslice(int start, int stop, int step) {
if (step > 0 && stop < start)
stop = start;
if (step == 1)
return fromSubstring(start, stop);
else {
int n = sliceLength(start, stop, step);
char new_chars[] = new char[n];
int j = 0;
for (int i=start; j<n; i+=step)
new_chars[j++] = getString().charAt(i);
return createInstance(new String(new_chars), true);
}
}
public PyString createInstance(String str) {
return new PyString(str);
}
protected PyString createInstance(String str, boolean isBasic) {
// ignore isBasic, doesn't apply to PyString, just PyUnicode
return new PyString(str);
}
@Override
public boolean __contains__(PyObject o) {
return str___contains__(o);
}
@ExposedMethod(doc = BuiltinDocs.str___contains___doc)
final boolean str___contains__(PyObject o) {
if (!(o instanceof PyString))
throw Py.TypeError("'in <string>' requires string as left operand");
PyString other = (PyString) o;
return getString().indexOf(other.getString()) >= 0;
}
protected PyObject repeat(int count) {
if(count < 0) {
count = 0;
}
int s = getString().length();
if((long)s * count > Integer.MAX_VALUE) {
// Since Strings store their data in an array, we can't make one
// longer than Integer.MAX_VALUE. Without this check we get
// NegativeArraySize exceptions when we create the array on the
// line with a wrapped int.
throw Py.OverflowError("max str len is " + Integer.MAX_VALUE);
}
char new_chars[] = new char[s * count];
for(int i = 0; i < count; i++) {
getString().getChars(0, s, new_chars, i * s);
}
return createInstance(new String(new_chars));
}
@Override
public PyObject __mul__(PyObject o) {
return str___mul__(o);
}
@ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.str___mul___doc)
final PyObject str___mul__(PyObject o) {
if (!o.isIndex()) {
return null;
}
return repeat(o.asIndex(Py.OverflowError));
}
@Override
public PyObject __rmul__(PyObject o) {
return str___rmul__(o);
}
@ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.str___rmul___doc)
final PyObject str___rmul__(PyObject o) {
if (!o.isIndex()) {
return null;
}
return repeat(o.asIndex(Py.OverflowError));
}
@Override
public PyObject __add__(PyObject other) {
return str___add__(other);
}
@ExposedMethod(type = MethodType.BINARY, doc = BuiltinDocs.str___add___doc)
final PyObject str___add__(PyObject other) {
if (other instanceof PyUnicode) {
return decode().__add__(other);
}
if (other instanceof PyString) {
PyString otherStr = (PyString)other;
return new PyString(getString().concat(otherStr.getString()));
}
return null;
}
@ExposedMethod(doc = BuiltinDocs.str___getnewargs___doc)
final PyTuple str___getnewargs__() {
return new PyTuple(new PyString(this.getString()));
}
@Override
public PyTuple __getnewargs__() {
return str___getnewargs__();
}
@Override
public PyObject __mod__(PyObject other) {
return str___mod__(other);
}
@ExposedMethod(doc = BuiltinDocs.str___mod___doc)
public PyObject str___mod__(PyObject other){
StringFormatter fmt = new StringFormatter(getString(), false);
return fmt.format(other);
}
@Override
public PyObject __int__() {
try
{
return Py.newInteger(atoi(10));
} catch (PyException e) {
if (e.match(Py.OverflowError)) {
return atol(10);
}
throw e;
}
}
@Override
public PyObject __long__() {
return atol(10);
}
@Override
public PyFloat __float__() {
return new PyFloat(atof());
}
@Override
public PyObject __pos__() {
throw Py.TypeError("bad operand type for unary +");
}
@Override
public PyObject __neg__() {
throw Py.TypeError("bad operand type for unary -");
}
@Override
public PyObject __invert__() {
throw Py.TypeError("bad operand type for unary ~");
}
@SuppressWarnings("fallthrough")
@Override
public PyComplex __complex__() {
boolean got_re = false;
boolean got_im = false;
boolean done = false;
boolean sw_error = false;
int s = 0;
int n = getString().length();
while (s < n && Character.isSpaceChar(getString().charAt(s)))
s++;
if (s == n) {
throw Py.ValueError("empty string for complex()");
}
double z = -1.0;
double x = 0.0;
double y = 0.0;
int sign = 1;
do {
char c = getString().charAt(s);
switch (c) {
case '-':
sign = -1;
/* Fallthrough */
case '+':
if (done || s+1 == n) {
sw_error = true;
break;
}
// a character is guaranteed, but it better be a digit
// or J or j
c = getString().charAt(++s); // eat the sign character
// and check the next
if (!Character.isDigit(c) && c!='J' && c!='j')
sw_error = true;
break;
case 'J':
case 'j':
if (got_im || done) {
sw_error = true;
break;
}
if (z < 0.0) {
y = sign;
} else {
y = sign * z;
}
got_im = true;
done = got_re;
sign = 1;
s++; // eat the J or j
break;
case ' ':
while (s < n && Character.isSpaceChar(getString().charAt(s)))
s++;
if (s != n)
sw_error = true;
break;
default:
boolean digit_or_dot = (c == '.' || Character.isDigit(c));
if (!digit_or_dot) {
sw_error = true;
break;
}
int end = endDouble(getString(),s);
z = Double.valueOf(getString().substring(s, end)).doubleValue();
if (z == Double.POSITIVE_INFINITY) {
throw Py.ValueError(String.format("float() out of range: %.150s", getString()));
}
s=end;
if (s < n) {
c = getString().charAt(s);
if (c == 'J' || c == 'j') {
break;
}
}
if (got_re) {
sw_error = true;
break;
}
/* accept a real part */
x = sign * z;
got_re = true;
done = got_im;
z = -1.0;
sign = 1;
break;
} /* end of switch */
} while (s < n && !sw_error);
if (sw_error) {
throw Py.ValueError("malformed string for complex() " +
getString().substring(s));
}
return new PyComplex(x,y);
}
private int endDouble(String string, int s) {
int n = string.length();
while (s < n) {
char c = string.charAt(s++);
if (Character.isDigit(c))
continue;
if (c == '.')
continue;
if (c == 'e' || c == 'E') {
if (s < n) {
c = string.charAt(s);
if (c == '+' || c == '-')
s++;
continue;
}
}
return s-1;
}
return s;
}
// Add in methods from string module
public String lower() {
return str_lower();
}
@ExposedMethod(doc = BuiltinDocs.str_lower_doc)
final String str_lower() {
return getString().toLowerCase();
}
public String upper() {
return str_upper();
}
@ExposedMethod(doc = BuiltinDocs.str_upper_doc)
final String str_upper() {
return getString().toUpperCase();
}
public String title() {
return str_title();
}
@ExposedMethod(doc = BuiltinDocs.str_title_doc)
final String str_title() {
char[] chars = getString().toCharArray();
int n = chars.length;
boolean previous_is_cased = false;
for (int i = 0; i < n; i++) {
char ch = chars[i];
if (previous_is_cased)
chars[i] = Character.toLowerCase(ch);
else
chars[i] = Character.toTitleCase(ch);
if (Character.isLowerCase(ch) ||
Character.isUpperCase(ch) ||
Character.isTitleCase(ch))
previous_is_cased = true;
else
previous_is_cased = false;
}
return new String(chars);
}
public String swapcase() {
return str_swapcase();
}
@ExposedMethod(doc = BuiltinDocs.str_swapcase_doc)
final String str_swapcase() {
char[] chars = getString().toCharArray();
int n=chars.length;
for (int i=0; i<n; i++) {
char c = chars[i];
if (Character.isUpperCase(c)) {
chars[i] = Character.toLowerCase(c);
}
else if (Character.isLowerCase(c)) {
chars[i] = Character.toUpperCase(c);
}
}
return new String(chars);
}
public String strip() {
return str_strip(null);
}
public String strip(String sep) {
return str_strip(sep);
}
@ExposedMethod(defaults = "null", doc = BuiltinDocs.str_strip_doc)
final String str_strip(String sep) {
char[] chars = getString().toCharArray();
int n=chars.length;
int start=0;
if (sep == null)
while (start < n && Character.isWhitespace(chars[start]))
start++;
else
while (start < n && sep.indexOf(chars[start]) >= 0)
start++;
int end=n-1;
if (sep == null)
while (end >= 0 && Character.isWhitespace(chars[end]))
end--;
else
while (end >= 0 && sep.indexOf(chars[end]) >= 0)
end--;
if (end >= start) {
return (end < n-1 || start > 0)
? getString().substring(start, end+1) : getString();
} else {
return "";
}
}
public String lstrip() {
return str_lstrip(null);
}
public String lstrip(String sep) {
return str_lstrip(sep);
}
@ExposedMethod(defaults = "null", doc = BuiltinDocs.str_lstrip_doc)
final String str_lstrip(String sep) {
char[] chars = getString().toCharArray();
int n=chars.length;
int start=0;
if (sep == null)
while (start < n && Character.isWhitespace(chars[start]))
start++;
else
while (start < n && sep.indexOf(chars[start]) >= 0)
start++;
return (start > 0) ? getString().substring(start, n) : getString();
}
public String rstrip(String sep) {
return str_rstrip(sep);
}
@ExposedMethod(defaults = "null", doc = BuiltinDocs.str_rstrip_doc)
final String str_rstrip(String sep) {
char[] chars = getString().toCharArray();
int n=chars.length;
int end=n-1;
if (sep == null)
while (end >= 0 && Character.isWhitespace(chars[end]))
end--;
else
while (end >= 0 && sep.indexOf(chars[end]) >= 0)
end--;
return (end < n-1) ? getString().substring(0, end+1) : getString();
}
public PyList split() {
return str_split(null, -1);
}
public PyList split(String sep) {
return str_split(sep, -1);
}
public PyList split(String sep, int maxsplit) {
return str_split(sep, maxsplit);
}
@ExposedMethod(defaults = {"null", "-1"}, doc = BuiltinDocs.str_split_doc)
final PyList str_split(String sep, int maxsplit) {
if (sep != null) {
if (sep.length() == 0) {
throw Py.ValueError("empty separator");
}
return splitfields(sep, maxsplit);
}
PyList list = new PyList();
char[] chars = getString().toCharArray();
int n=chars.length;
if (maxsplit < 0)
maxsplit = n;
int splits=0;
int index=0;
while (index < n && splits < maxsplit) {
while (index < n && Character.isWhitespace(chars[index]))
index++;
if (index == n)
break;
int start = index;
while (index < n && !Character.isWhitespace(chars[index]))
index++;
list.append(fromSubstring(start, index));
splits++;
}
while (index < n && Character.isWhitespace(chars[index]))
index++;
if (index < n) {
list.append(fromSubstring(index, n));
}
return list;
}
public PyList rsplit() {
return str_rsplit(null, -1);
}
public PyList rsplit(String sep) {
return str_rsplit(sep, -1);
}
public PyList rsplit(String sep, int maxsplit) {
return str_rsplit(sep, maxsplit);
}
@ExposedMethod(defaults = {"null", "-1"}, doc = BuiltinDocs.str_rsplit_doc)
final PyList str_rsplit(String sep, int maxsplit) {
if (sep != null) {
if (sep.length() == 0) {
throw Py.ValueError("empty separator");
}
PyList list = rsplitfields(sep, maxsplit);
list.reverse();
return list;
}
PyList list = new PyList();
char[] chars = getString().toCharArray();
if (maxsplit < 0) {
maxsplit = chars.length;
}
int splits = 0;
int i = chars.length - 1;
while (i > -1 && Character.isWhitespace(chars[i])) {
i--;
}
if (i == -1) {
return list;
}
while (splits < maxsplit) {
while (i > -1 && Character.isWhitespace(chars[i])) {
i--;
}
if (i == -1) {
break;
}
int nextWsChar = i;
while (nextWsChar > -1 && !Character.isWhitespace(chars[nextWsChar])) {
nextWsChar--;
}
if (nextWsChar == -1) {
break;
}
splits++;
list.add(fromSubstring(nextWsChar + 1, i + 1));
i = nextWsChar;
}
while (i > -1 && Character.isWhitespace(chars[i])) {
i--;
}
if (i > -1) {
list.add(fromSubstring(0,i+1));
}
list.reverse();
return list;
}
public PyTuple partition(PyObject sepObj) {
return str_partition(sepObj);
}
@ExposedMethod(doc = BuiltinDocs.str_partition_doc)
final PyTuple str_partition(PyObject sepObj) {
String sep;
if (sepObj instanceof PyUnicode) {
return unicodePartition(sepObj);
} else if (sepObj instanceof PyString) {
sep = ((PyString) sepObj).getString();
} else {
throw Py.TypeError("expected a character buffer object");
}
if (sep.length() == 0) {
throw Py.ValueError("empty separator");
}
int index = getString().indexOf(sep);
if (index != -1) {
return new PyTuple(fromSubstring(0, index), sepObj,
fromSubstring(index + sep.length(), getString().length()));
} else {
return new PyTuple(this, Py.EmptyString, Py.EmptyString);
}
}
final PyTuple unicodePartition(PyObject sepObj) {
PyUnicode strObj = __unicode__();
String str = strObj.getString();
// Will throw a TypeError if not a basestring
String sep = sepObj.asString();
sepObj = sepObj.__unicode__();
if (sep.length() == 0) {
throw Py.ValueError("empty separator");
}
int index = str.indexOf(sep);
if (index != -1) {
return new PyTuple(strObj.fromSubstring(0, index), sepObj,
strObj.fromSubstring(index + sep.length(), str.length()));
} else {
PyUnicode emptyUnicode = Py.newUnicode("");
return new PyTuple(this, emptyUnicode, emptyUnicode);
}
}
public PyTuple rpartition(PyObject sepObj) {
return str_rpartition(sepObj);
}
@ExposedMethod(doc = BuiltinDocs.str_rpartition_doc)
final PyTuple str_rpartition(PyObject sepObj) {
String sep;
if (sepObj instanceof PyUnicode) {
return unicodePartition(sepObj);
} else if (sepObj instanceof PyString) {
sep = ((PyString) sepObj).getString();
} else {
throw Py.TypeError("expected a character buffer object");
}
if (sep.length() == 0) {
throw Py.ValueError("empty separator");
}
int index = getString().lastIndexOf(sep);
if (index != -1) {
return new PyTuple(fromSubstring(0, index), sepObj,
fromSubstring(index + sep.length(), getString().length()));
} else {
return new PyTuple(Py.EmptyString, Py.EmptyString, this);
}
}
final PyTuple unicodeRpartition(PyObject sepObj) {
PyUnicode strObj = __unicode__();
String str = strObj.getString();
// Will throw a TypeError if not a basestring
String sep = sepObj.asString();
sepObj = sepObj.__unicode__();
if (sep.length() == 0) {
throw Py.ValueError("empty separator");
}
int index = str.lastIndexOf(sep);
if (index != -1) {
return new PyTuple(strObj.fromSubstring(0, index), sepObj,
strObj.fromSubstring(index + sep.length(), str.length()));
} else {
PyUnicode emptyUnicode = Py.newUnicode("");
return new PyTuple(emptyUnicode, emptyUnicode, this);
}
}
private PyList splitfields(String sep, int maxsplit) {
PyList list = new PyList();
int length = getString().length();
if (maxsplit < 0)
maxsplit = length + 1;
int lastbreak = 0;
int splits = 0;
int sepLength = sep.length();
int index;
if((sep.length() == 0) && (maxsplit != 0)) {
index = getString().indexOf(sep, lastbreak);
list.append(fromSubstring(lastbreak, index));
splits++;
}
while (splits < maxsplit) {
index = getString().indexOf(sep, lastbreak);
if (index == -1)
break;
if(sep.length() == 0)
index++;
splits += 1;
list.append(fromSubstring(lastbreak, index));
lastbreak = index + sepLength;
}
if (lastbreak <= length) {
list.append(fromSubstring(lastbreak, length));
}
return list;
}
private PyList rsplitfields(String sep, int maxsplit) {
PyList list = new PyList();
int length = getString().length();
if (maxsplit < 0) {
maxsplit = length + 1;
}
int lastbreak = length;
int splits = 0;
int index = length;
int sepLength = sep.length();
while (index > 0 && splits < maxsplit) {
int i = getString().lastIndexOf(sep, index - sepLength);
if (i == index) {
i -= sepLength;
}
if (i < 0) {
break;
}
splits++;
list.append(fromSubstring(i + sepLength, lastbreak));
lastbreak = i;
index = i;
}
list.append(fromSubstring(0, lastbreak));
return list;
}
public PyList splitlines() {
return str_splitlines(false);
}
public PyList splitlines(boolean keepends) {
return str_splitlines(keepends);
}
@ExposedMethod(defaults = "false", doc = BuiltinDocs.str_splitlines_doc)
final PyList str_splitlines(boolean keepends) {
PyList list = new PyList();
char[] chars = getString().toCharArray();
int n=chars.length;
int j = 0;
for (int i = 0; i < n; ) {
/* Find a line and append it */
while (i < n && chars[i] != '\n' && chars[i] != '\r' &&
Character.getType(chars[i]) != Character.LINE_SEPARATOR)
i++;
/* Skip the line break reading CRLF as one line break */
int eol = i;
if (i < n) {
if (chars[i] == '\r' && i + 1 < n && chars[i+1] == '\n')
i += 2;
else
i++;
if (keepends)
eol = i;
}
list.append(fromSubstring(j, eol));
j = i;
}
if (j < n) {
list.append(fromSubstring(j, n));
}
return list;
}
protected PyString fromSubstring(int begin, int end) {
return createInstance(getString().substring(begin, end), true);
}
public int index(String sub) {
return str_index(sub, 0, null);
}
public int index(String sub, int start) {
return str_index(sub, start, null);
}
public int index(String sub, int start, int end) {
return str_index(sub, start, Py.newInteger(end));
}
@ExposedMethod(defaults = {"0", "null"}, doc = BuiltinDocs.str_index_doc)
final int str_index(String sub, int start, PyObject end) {
int index = str_find(sub, start, end);
if (index == -1)
throw Py.ValueError("substring not found in string.index");
return index;
}
public int rindex(String sub) {
return str_rindex(sub, 0, null);
}
public int rindex(String sub, int start) {
return str_rindex(sub, start, null);
}
public int rindex(String sub, int start, int end) {
return str_rindex(sub, start, Py.newInteger(end));
}
@ExposedMethod(defaults = {"0", "null"}, doc = BuiltinDocs.str_rindex_doc)
final int str_rindex(String sub, int start, PyObject end) {
int index = str_rfind(sub, start, end);
if(index == -1)
throw Py.ValueError("substring not found in string.rindex");
return index;
}
public int count(String sub) {
return str_count(sub, 0, null);
}
public int count(String sub, int start) {
return str_count(sub, start, null);
}
public int count(String sub, int start, int end) {
return str_count(sub, start, Py.newInteger(end));
}
@ExposedMethod(defaults = {"0", "null"}, doc = BuiltinDocs.str_count_doc)
final int str_count(String sub, int start, PyObject end) {
int[] indices = translateIndices(start, end);
int n = sub.length();
if(n == 0) {
if (start > getString().length()) {
return 0;
}
return indices[1] - indices[0] + 1;
}
int count = 0;
while(true){
int index = getString().indexOf(sub, indices[0]);
indices[0] = index + n;
if(indices[0] > indices[1] || index == -1) {
break;
}
count++;
}
return count;
}
public int find(String sub) {
return str_find(sub, 0, null);
}
public int find(String sub, int start) {
return str_find(sub, start, null);
}
public int find(String sub, int start, int end) {
return str_find(sub, start, Py.newInteger(end));
}
@ExposedMethod(defaults = {"0", "null"}, doc = BuiltinDocs.str_find_doc)
final int str_find(String sub, int start, PyObject end) {
int[] indices = translateIndices(start, end);
int index = getString().indexOf(sub, indices[0]);
if (index < start || index > indices[1]) {
return -1;
}
return index;
}
public int rfind(String sub) {
return str_rfind(sub, 0, null);
}
public int rfind(String sub, int start) {
return str_rfind(sub, start, null);
}
public int rfind(String sub, int start, int end) {
return str_rfind(sub, start, Py.newInteger(end));
}
@ExposedMethod(defaults = {"0", "null"}, doc = BuiltinDocs.str_rfind_doc)
final int str_rfind(String sub, int start, PyObject end) {
int[] indices = translateIndices(start, end);
int index = getString().lastIndexOf(sub, indices[1] - sub.length());
if (index < start) {
return -1;
}
return index;
}
public double atof() {
StringBuilder s = null;
int n = getString().length();
for (int i = 0; i < n; i++) {
char ch = getString().charAt(i);
if (ch == '\u0000') {
throw Py.ValueError("null byte in argument for float()");
}
if (Character.isDigit(ch)) {
if (s == null)
s = new StringBuilder(getString());
int val = Character.digit(ch, 10);
s.setCharAt(i, Character.forDigit(val, 10));
}
}
String sval = getString();
if (s != null)
sval = s.toString();
try {
// Double.valueOf allows format specifier ("d" or "f") at the end
String lowSval = sval.toLowerCase();
if (lowSval.equals("nan")) return Double.NaN;
else if (lowSval.equals("inf")) return Double.POSITIVE_INFINITY;
else if (lowSval.equals("-inf")) return Double.NEGATIVE_INFINITY;
if (lowSval.endsWith("d") || lowSval.endsWith("f")) {
throw new NumberFormatException("format specifiers not allowed");
}
return Double.valueOf(sval).doubleValue();
}
catch (NumberFormatException exc) {
throw Py.ValueError("invalid literal for __float__: "+getString());
}
}
public int atoi() {
return atoi(10);
}
public int atoi(int base) {
if ((base != 0 && base < 2) || (base > 36)) {
throw Py.ValueError("invalid base for atoi()");
}
int b = 0;
int e = getString().length();
while (b < e && Character.isWhitespace(getString().charAt(b)))
b++;
while (e > b && Character.isWhitespace(getString().charAt(e-1)))
e--;
char sign = 0;
if (b < e) {
sign = getString().charAt(b);
if (sign == '-' || sign == '+') {
b++;
while (b < e && Character.isWhitespace(getString().charAt(b))) b++;
}
if (base == 16) {
if (getString().charAt(b) == '0') {
if (b < e-1 &&
Character.toUpperCase(getString().charAt(b+1)) == 'X') {
b += 2;
}
}
} else if (base == 0) {
if (getString().charAt(b) == '0') {
if (b < e-1 && Character.toUpperCase(getString().charAt(b+1)) == 'X') {
base = 16;
b += 2;
} else if (b < e-1 && Character.toUpperCase(getString().charAt(b+1)) == 'O') {
base = 8;
b += 2;
} else if (b < e-1 && Character.toUpperCase(getString().charAt(b+1)) == 'B') {
base = 2;
b += 2;
} else {
base = 8;
}
}
} else if (base == 8) {
if (b < e-1 && Character.toUpperCase(getString().charAt(b+1)) == 'O') {
b += 2;
}
} else if (base == 2) {
if (b < e-1 &&
Character.toUpperCase(getString().charAt(b+1)) == 'B') {
b += 2;
}
}
}
if (base == 0)
base = 10;
String s = getString();
if (b > 0 || e < getString().length())
s = getString().substring(b, e);
try {
BigInteger bi;
if (sign == '-') {
bi = new BigInteger("-" + s, base);
} else
bi = new BigInteger(s, base);
if (bi.compareTo(PyInteger.MAX_INT) > 0 || bi.compareTo(PyInteger.MIN_INT) < 0) {
throw Py.OverflowError("long int too large to convert to int");
}
return bi.intValue();
} catch (NumberFormatException exc) {
throw Py.ValueError("invalid literal for int() with base " + base + ": " + getString());
} catch (StringIndexOutOfBoundsException exc) {
throw Py.ValueError("invalid literal for int() with base " + base + ": " + getString());
}
}
public PyLong atol() {
return atol(10);
}
public PyLong atol(int base) {
String str = getString();
int b = 0;
int e = str.length();
while (b < e && Character.isWhitespace(str.charAt(b)))
b++;
while (e > b && Character.isWhitespace(str.charAt(e-1)))
e--;
char sign = 0;
if (b < e) {
sign = getString().charAt(b);
if (sign == '-' || sign == '+') {
b++;
while (b < e && Character.isWhitespace(str.charAt(b))) b++;
}
if (base == 0 || base == 16) {
if (getString().charAt(b) == '0') {
if (b < e-1 &&
Character.toUpperCase(getString().charAt(b+1)) == 'X') {
base = 16;
b += 2;
} else {
if (base == 0)
base = 8;
}
}
}
}
if (base == 0)
base = 10;
if (base < 2 || base > 36)
throw Py.ValueError("invalid base for long literal:" + base);
// if the base >= 22, then an 'l' or 'L' is a digit!
if (base < 22 && e > b && (str.charAt(e-1) == 'L' || str.charAt(e-1) == 'l'))
e--;
if (b > 0 || e < str.length())
str = str.substring(b, e);
try {
java.math.BigInteger bi = null;
if (sign == '-')
bi = new java.math.BigInteger("-" + str, base);
else
bi = new java.math.BigInteger(str, base);
return new PyLong(bi);
} catch (NumberFormatException exc) {
if (this instanceof PyUnicode) {
// TODO: here's a basic issue: do we use the BigInteger constructor
// above, or add an equivalent to CPython's PyUnicode_EncodeDecimal;
// we should note that the current error string does not quite match
// CPython regardless of the codec, that's going to require some more work
throw Py.UnicodeEncodeError("decimal", "codec can't encode character",
0,0, "invalid decimal Unicode string");
}
else {
throw Py.ValueError("invalid literal for long() with base " + base + ": " + getString());
}
} catch (StringIndexOutOfBoundsException exc) {
throw Py.ValueError("invalid literal for long() with base " + base + ": " + getString());
}
}
private static String padding(int n, char pad) {
char[] chars = new char[n];
for (int i=0; i<n; i++)
chars[i] = pad;
return new String(chars);
}
private static char parse_fillchar(String function, String fillchar) {
if (fillchar == null) { return ' '; }
if (fillchar.length() != 1) {
throw Py.TypeError(function + "() argument 2 must be char, not str");
}
return fillchar.charAt(0);
}
public String ljust(int width) {
return str_ljust(width, null);
}
public String ljust(int width, String padding) {
return str_ljust(width, padding);
}
@ExposedMethod(defaults="null", doc = BuiltinDocs.str_ljust_doc)
final String str_ljust(int width, String fillchar) {
char pad = parse_fillchar("ljust", fillchar);
int n = width-getString().length();
if (n <= 0)
return getString();
return getString()+padding(n, pad);
}
public String rjust(int width) {
return str_rjust(width, null);
}
@ExposedMethod(defaults="null", doc = BuiltinDocs.str_rjust_doc)
final String str_rjust(int width, String fillchar) {
char pad = parse_fillchar("rjust", fillchar);
int n = width-getString().length();
if (n <= 0)
return getString();
return padding(n, pad)+getString();
}
public String center(int width) {
return str_center(width, null);
}
@ExposedMethod(defaults="null", doc = BuiltinDocs.str_center_doc)
final String str_center(int width, String fillchar) {
char pad = parse_fillchar("center", fillchar);
int n = width-getString().length();
if (n <= 0)
return getString();
int half = n/2;
if (n%2 > 0 && width%2 > 0)
half += 1;
return padding(half, pad)+getString()+padding(n-half, pad);
}
public String zfill(int width) {
return str_zfill(width);
}
@ExposedMethod(doc = BuiltinDocs.str_zfill_doc)
final String str_zfill(int width) {
String s = getString();
int n = s.length();
if (n >= width)
return s;
char[] chars = new char[width];
int nzeros = width-n;
int i=0;
int sStart=0;
if (n > 0) {
char start = s.charAt(0);
if (start == '+' || start == '-') {
chars[0] = start;
i += 1;
nzeros++;
sStart=1;
}
}
for(;i<nzeros; i++) {
chars[i] = '0';
}
s.getChars(sStart, s.length(), chars, i);
return new String(chars);
}
public String expandtabs() {
return str_expandtabs(8);
}
public String expandtabs(int tabsize) {
return str_expandtabs(tabsize);
}
@ExposedMethod(defaults = "8", doc = BuiltinDocs.str_expandtabs_doc)
final String str_expandtabs(int tabsize) {
String s = getString();
StringBuilder buf = new StringBuilder((int)(s.length()*1.5));
char[] chars = s.toCharArray();
int n = chars.length;
int position = 0;
for(int i=0; i<n; i++) {
char c = chars[i];
if (c == '\t') {
int spaces = tabsize-position%tabsize;
position += spaces;
while (spaces-- > 0) {
buf.append(' ');
}
continue;
}
if (c == '\n' || c == '\r') {
position = -1;
}
buf.append(c);
position++;
}
return buf.toString();
}
public String capitalize() {
return str_capitalize();
}
@ExposedMethod(doc = BuiltinDocs.str_capitalize_doc)
final String str_capitalize() {
if (getString().length() == 0)
return getString();
String first = getString().substring(0,1).toUpperCase();
return first.concat(getString().substring(1).toLowerCase());
}
@ExposedMethod(defaults = "null", doc = BuiltinDocs.str_replace_doc)
final PyString str_replace(PyObject oldPiece, PyObject newPiece, PyObject maxsplit) {
if(!(oldPiece instanceof PyString) || !(newPiece instanceof PyString)) {
throw Py.TypeError("str or unicode required for replace");
}
return replace((PyString)oldPiece, (PyString)newPiece, maxsplit == null ? -1 : maxsplit.asInt());
}
protected PyString replace(PyString oldPiece, PyString newPiece, int maxsplit) {
int len = getString().length();
int old_len = oldPiece.getString().length();
if (len == 0) {
if (maxsplit == -1 && old_len == 0) {
return createInstance(newPiece.getString(), true);
}
return createInstance(getString(), true);
}
if (old_len == 0 && newPiece.getString().length() != 0 && maxsplit !=0) {
// old="" and new != "", interleave new piece with each char in original, taking in effect maxsplit
StringBuilder buffer = new StringBuilder();
int i = 0;
buffer.append(newPiece.getString());
for (; i < len && (i < maxsplit-1 || maxsplit == -1); i++) {
buffer.append(getString().charAt(i));
buffer.append(newPiece.getString());
}
buffer.append(getString().substring(i));
return createInstance(buffer.toString(), true);
}
if(maxsplit == -1) {
if(old_len == 0) {
maxsplit = len + 1;
} else {
maxsplit = len;
}
}
return newPiece.join(splitfields(oldPiece.getString(), maxsplit));
}
public PyString join(PyObject seq) {
return str_join(seq);
}
@ExposedMethod(doc = BuiltinDocs.str_join_doc)
final PyString str_join(PyObject obj) {
PySequence seq = fastSequence(obj, "");
int seqLen = seq.__len__();
if (seqLen == 0) {
return Py.EmptyString;
}
PyObject item;
if (seqLen == 1) {
item = seq.pyget(0);
if (item.getType() == PyString.TYPE || item.getType() == PyUnicode.TYPE) {
return (PyString)item;
}
}
// There are at least two things to join, or else we have a subclass of the
// builtin types in the sequence. Do a pre-pass to figure out the total amount of
// space we'll need, see whether any argument is absurd, and defer to the Unicode
// join if appropriate
int i = 0;
long size = 0;
int sepLen = getString().length();
for (; i < seqLen; i++) {
item = seq.pyget(i);
if (!(item instanceof PyString)) {
throw Py.TypeError(String.format("sequence item %d: expected string, %.80s found",
i, item.getType().fastGetName()));
}
if (item instanceof PyUnicode) {
// Defer to Unicode join. CAUTION: There's no gurantee that the original
// sequence can be iterated over again, so we must pass seq here
return unicodeJoin(seq);
}
if (i != 0) {
size += sepLen;
}
size += ((PyString) item).getString().length();
if (size > Integer.MAX_VALUE) {
throw Py.OverflowError("join() result is too long for a Python string");
}
}
// Catenate everything
StringBuilder buf = new StringBuilder((int)size);
for (i = 0; i < seqLen; i++) {
item = seq.pyget(i);
if (i != 0) {
buf.append(getString());
}
buf.append(((PyString) item).getString());
}
return new PyString(buf.toString());
}
final PyUnicode unicodeJoin(PyObject obj) {
PySequence seq = fastSequence(obj, "");
// A codec may be invoked to convert str objects to Unicode, and so it's possible
// to call back into Python code during PyUnicode_FromObject(), and so it's
// possible for a sick codec to change the size of fseq (if seq is a list).
// Therefore we have to keep refetching the size -- can't assume seqlen is
// invariant.
int seqLen = seq.__len__();
// If empty sequence, return u""
if (seqLen == 0) {
return new PyUnicode();
}
// If singleton sequence with an exact Unicode, return that
PyObject item;
if (seqLen == 1) {
item = seq.pyget(0);
if (item.getType() == PyUnicode.TYPE) {
return (PyUnicode)item;
}
}
String sep = null;
if (seqLen > 1) {
if (this instanceof PyUnicode) {
sep = getString();
} else {
sep = ((PyUnicode) decode()).getString();
// In case decode()'s codec mutated seq
seqLen = seq.__len__();
}
}
// At least two items to join, or one that isn't exact Unicode
long size = 0;
int sepLen = getString().length();
StringBuilder buf = new StringBuilder();
String itemString;
for (int i = 0; i < seqLen; i++) {
item = seq.pyget(i);
// Convert item to Unicode
if (!(item instanceof PyString)) {
throw Py.TypeError(String.format("sequence item %d: expected string or Unicode,"
+ " %.80s found",
i, item.getType().fastGetName()));
}
if (!(item instanceof PyUnicode)) {
item = ((PyString)item).decode();
// In case decode()'s codec mutated seq
seqLen = seq.__len__();
}
itemString = ((PyUnicode) item).getString();
if (i != 0) {
size += sepLen;
buf.append(sep);
}
size += itemString.length();
if (size > Integer.MAX_VALUE) {
throw Py.OverflowError("join() result is too long for a Python string");
}
buf.append(itemString);
}
return new PyUnicode(buf.toString());
}
public boolean startswith(PyObject prefix) {
return str_startswith(prefix, 0, null);
}
public boolean startswith(PyObject prefix, int offset) {
return str_startswith(prefix, offset, null);
}
public boolean startswith(PyObject prefix, int start, int end) {
return str_startswith(prefix, start, Py.newInteger(end));
}
@ExposedMethod(defaults = {"0", "null"}, doc = BuiltinDocs.str_startswith_doc)
final boolean str_startswith(PyObject prefix, int start, PyObject end) {
int[] indices = translateIndices(start, end);
if (prefix instanceof PyString) {
String strPrefix = ((PyString) prefix).getString();
if (indices[1] - indices[0] < strPrefix.length())
return false;
return getString().startsWith(strPrefix, indices[0]);
} else if (prefix instanceof PyTuple) {
PyObject[] prefixes = ((PyTuple)prefix).getArray();
for (int i = 0 ; i < prefixes.length ; i++) {
if (!(prefixes[i] instanceof PyString))
throw Py.TypeError("expected a character buffer object");
String strPrefix = ((PyString) prefixes[i]).getString();
if (indices[1] - indices[0] < strPrefix.length())
continue;
if (getString().startsWith(strPrefix, indices[0]))
return true;
}
return false;
} else {
throw Py.TypeError("expected a character buffer object or tuple");
}
}
public boolean endswith(PyObject suffix) {
return str_endswith(suffix, 0, null);
}
public boolean endswith(PyObject suffix, int start) {
return str_endswith(suffix, start, null);
}
public boolean endswith(PyObject suffix, int start, int end) {
return str_endswith(suffix, start, Py.newInteger(end));
}
@ExposedMethod(defaults = {"0", "null"}, doc = BuiltinDocs.str_endswith_doc)
final boolean str_endswith(PyObject suffix, int start, PyObject end) {
int[] indices = translateIndices(start, end);
String substr = getString().substring(indices[0], indices[1]);
if (suffix instanceof PyString) {
return substr.endsWith(((PyString) suffix).getString());
} else if (suffix instanceof PyTuple) {
PyObject[] suffixes = ((PyTuple)suffix).getArray();
for (int i = 0 ; i < suffixes.length ; i++) {
if (!(suffixes[i] instanceof PyString))
throw Py.TypeError("expected a character buffer object");
if (substr.endsWith(((PyString) suffixes[i]).getString()))
return true;
}
return false;
} else {
throw Py.TypeError("expected a character buffer object or tuple");
}
}
/**
* Turns the possibly negative Python slice start and end into valid indices
* into this string.
*
* @return a 2 element array of indices into this string describing a
* substring from [0] to [1]. [0] <= [1], [0] >= 0 and [1] <=
* string.length()
*
*/
protected int[] translateIndices(int start, PyObject end) {
int iEnd;
if(end == null) {
iEnd = getString().length();
} else {
iEnd = end.asInt();
}
int n = getString().length();
if(iEnd < 0) {
iEnd = n + iEnd;
if(iEnd < 0) {
iEnd = 0;
}
} else if(iEnd > n) {
iEnd = n;
}
if(start < 0) {
start = n + start;
if(start < 0) {
start = 0;
}
}
if(start > iEnd) {
start = iEnd;
}
return new int[] {start, iEnd};
}
public String translate(String table) {
return str_translate(table, null);
}
public String translate(String table, String deletechars) {
return str_translate(table, deletechars);
}
@ExposedMethod(defaults = "null", doc = BuiltinDocs.str_translate_doc)
final String str_translate(String table, String deletechars) {
if (table.length() != 256)
throw Py.ValueError(
"translation table must be 256 characters long");
StringBuilder buf = new StringBuilder(getString().length());
for (int i=0; i < getString().length(); i++) {
char c = getString().charAt(i);
if (deletechars != null && deletechars.indexOf(c) >= 0)
continue;
try {
buf.append(table.charAt(c));
}
catch (IndexOutOfBoundsException e) {
throw Py.TypeError(
"translate() only works for 8-bit character strings");
}
}
return buf.toString();
}
//XXX: is this needed?
public String translate(PyObject table) {
StringBuilder v = new StringBuilder(getString().length());
for (int i=0; i < getString().length(); i++) {
char ch = getString().charAt(i);
PyObject w = Py.newInteger(ch);
PyObject x = table.__finditem__(w);
if (x == null) {
/* No mapping found: default to 1-1 mapping */
v.append(ch);
continue;
}
/* Apply mapping */
if (x instanceof PyInteger) {
int value = ((PyInteger) x).getValue();
v.append((char) value);
} else if (x == Py.None) {
;
} else if (x instanceof PyString) {
if (x.__len__() != 1) {
/* 1-n mapping */
throw new PyException(Py.NotImplementedError,
"1-n mappings are currently not implemented");
}
v.append(x.toString());
}
else {
/* wrong return value */
throw Py.TypeError(
"character mapping must return integer, " +
"None or unicode");
}
}
return v.toString();
}
public boolean islower() {
return str_islower();
}
@ExposedMethod(doc = BuiltinDocs.str_islower_doc)
final boolean str_islower() {
int n = getString().length();
/* Shortcut for single character strings */
if (n == 1)
return Character.isLowerCase(getString().charAt(0));
boolean cased = false;
for (int i = 0; i < n; i++) {
char ch = getString().charAt(i);
if (Character.isUpperCase(ch) || Character.isTitleCase(ch))
return false;
else if (!cased && Character.isLowerCase(ch))
cased = true;
}
return cased;
}
public boolean isupper() {
return str_isupper();
}
@ExposedMethod(doc = BuiltinDocs.str_isupper_doc)
final boolean str_isupper() {
int n = getString().length();
/* Shortcut for single character strings */
if (n == 1)
return Character.isUpperCase(getString().charAt(0));
boolean cased = false;
for (int i = 0; i < n; i++) {
char ch = getString().charAt(i);
if (Character.isLowerCase(ch) || Character.isTitleCase(ch))
return false;
else if (!cased && Character.isUpperCase(ch))
cased = true;
}
return cased;
}
public boolean isalpha() {
return str_isalpha();
}
@ExposedMethod(doc = BuiltinDocs.str_isalpha_doc)
final boolean str_isalpha() {
int n = getString().length();
/* Shortcut for single character strings */
if (n == 1)
return Character.isLetter(getString().charAt(0));
if (n == 0)
return false;
for (int i = 0; i < n; i++) {
char ch = getString().charAt(i);
if (!Character.isLetter(ch))
return false;
}
return true;
}
public boolean isalnum() {
return str_isalnum();
}
@ExposedMethod(doc = BuiltinDocs.str_isalnum_doc)
final boolean str_isalnum() {
int n = getString().length();
/* Shortcut for single character strings */
if (n == 1)
return _isalnum(getString().charAt(0));
if (n == 0)
return false;
for (int i = 0; i < n; i++) {
char ch = getString().charAt(i);
if (!_isalnum(ch))
return false;
}
return true;
}
private boolean _isalnum(char ch) {
// This can ever be entirely compatible with CPython. In CPython
// The type is not used, the numeric property is determined from
// the presense of digit, decimal or numeric fields. These fields
// are not available in exactly the same way in java.
return Character.isLetterOrDigit(ch) ||
Character.getType(ch) == Character.LETTER_NUMBER;
}
public boolean isdecimal() {
return str_isdecimal();
}
@ExposedMethod(doc = BuiltinDocs.unicode_isdecimal_doc)
final boolean str_isdecimal() {
int n = getString().length();
/* Shortcut for single character strings */
if (n == 1) {
char ch = getString().charAt(0);
return _isdecimal(ch);
}
if (n == 0)
return false;
for (int i = 0; i < n; i++) {
char ch = getString().charAt(i);
if (!_isdecimal(ch))
return false;
}
return true;
}
private boolean _isdecimal(char ch) {
// See the comment in _isalnum. Here it is even worse.
return Character.getType(ch) == Character.DECIMAL_DIGIT_NUMBER;
}
public boolean isdigit() {
return str_isdigit();
}
@ExposedMethod(doc = BuiltinDocs.str_isdigit_doc)
final boolean str_isdigit() {
int n = getString().length();
/* Shortcut for single character strings */
if (n == 1)
return Character.isDigit(getString().charAt(0));
if (n == 0)
return false;
for (int i = 0; i < n; i++) {
char ch = getString().charAt(i);
if (!Character.isDigit(ch))
return false;
}
return true;
}
public boolean isnumeric() {
return str_isnumeric();
}
@ExposedMethod(doc = BuiltinDocs.unicode_isnumeric_doc)
final boolean str_isnumeric() {
int n = getString().length();
/* Shortcut for single character strings */
if (n == 1)
return _isnumeric(getString().charAt(0));
if (n == 0)
return false;
for (int i = 0; i < n; i++) {
char ch = getString().charAt(i);
if (!_isnumeric(ch))
return false;
}
return true;
}
private boolean _isnumeric(char ch) {
int type = Character.getType(ch);
return type == Character.DECIMAL_DIGIT_NUMBER ||
type == Character.LETTER_NUMBER ||
type == Character.OTHER_NUMBER;
}
public boolean istitle() {
return str_istitle();
}
@ExposedMethod(doc = BuiltinDocs.str_istitle_doc)
final boolean str_istitle() {
int n = getString().length();
/* Shortcut for single character strings */
if (n == 1)
return Character.isTitleCase(getString().charAt(0)) ||
Character.isUpperCase(getString().charAt(0));
boolean cased = false;
boolean previous_is_cased = false;
for (int i = 0; i < n; i++) {
char ch = getString().charAt(i);
if (Character.isUpperCase(ch) || Character.isTitleCase(ch)) {
if (previous_is_cased)
return false;
previous_is_cased = true;
cased = true;
}
else if (Character.isLowerCase(ch)) {
if (!previous_is_cased)
return false;
previous_is_cased = true;
cased = true;
}
else
previous_is_cased = false;
}
return cased;
}
public boolean isspace() {
return str_isspace();
}
@ExposedMethod(doc = BuiltinDocs.str_isspace_doc)
final boolean str_isspace() {
int n = getString().length();
/* Shortcut for single character strings */
if (n == 1)
return Character.isWhitespace(getString().charAt(0));
if (n == 0)
return false;
for (int i = 0; i < n; i++) {
char ch = getString().charAt(i);
if (!Character.isWhitespace(ch))
return false;
}
return true;
}
public boolean isunicode() {
return str_isunicode();
}
@ExposedMethod(doc = "isunicode is deprecated.")
final boolean str_isunicode() {
Py.warning(Py.DeprecationWarning, "isunicode is deprecated.");
int n = getString().length();
for (int i = 0; i < n; i++) {
char ch = getString().charAt(i);
if (ch > 255)
return true;
}
return false;
}
public String encode() {
return encode(null, null);
}
public String encode(String encoding) {
return encode(encoding, null);
}
public String encode(String encoding, String errors) {
return codecs.encode(this, encoding, errors);
}
@ExposedMethod(doc = BuiltinDocs.str_encode_doc)
final String str_encode(PyObject[] args, String[] keywords) {
ArgParser ap = new ArgParser("encode", args, keywords, "encoding", "errors");
String encoding = ap.getString(0, null);
String errors = ap.getString(1, null);
return encode(encoding, errors);
}
public PyObject decode() {
return decode(null, null);
}
public PyObject decode(String encoding) {
return decode(encoding, null);
}
public PyObject decode(String encoding, String errors) {
return codecs.decode(this, encoding, errors);
}
@ExposedMethod(doc = BuiltinDocs.str_decode_doc)
final PyObject str_decode(PyObject[] args, String[] keywords) {
ArgParser ap = new ArgParser("decode", args, keywords, "encoding", "errors");
String encoding = ap.getString(0, null);
String errors = ap.getString(1, null);
return decode(encoding, errors);
}
@ExposedMethod(doc = BuiltinDocs.str__formatter_parser_doc)
final PyObject str__formatter_parser() {
return new MarkupIterator(getString());
}
@ExposedMethod(doc = BuiltinDocs.str__formatter_field_name_split_doc)
final PyObject str__formatter_field_name_split() {
FieldNameIterator iterator = new FieldNameIterator(getString());
Object headObj = iterator.head();
PyObject head = headObj instanceof Integer
? new PyInteger((Integer) headObj)
: new PyString((String) headObj);
return new PyTuple(head, iterator);
}
@ExposedMethod(doc = BuiltinDocs.str_format_doc)
final PyObject str_format(PyObject[] args, String[] keywords) {
try {
return new PyString(buildFormattedString(getString(), args, keywords));
} catch (IllegalArgumentException e) {
throw Py.ValueError(e.getMessage());
}
}
private String buildFormattedString(String value, PyObject[] args, String[] keywords) {
StringBuilder result = new StringBuilder();
MarkupIterator it = new MarkupIterator(value);
while (true) {
MarkupIterator.Chunk chunk = it.nextChunk();
if (chunk == null) {
break;
}
result.append(chunk.literalText);
if (chunk.fieldName.length() > 0) {
outputMarkup(result, chunk, args, keywords);
}
}
return result.toString();
}
private void outputMarkup(StringBuilder result, MarkupIterator.Chunk chunk,
PyObject[] args, String[] keywords) {
PyObject fieldObj = getFieldObject(chunk.fieldName, args, keywords);
if (fieldObj == null) {
return;
}
if ("r".equals(chunk.conversion)) {
fieldObj = fieldObj.__repr__();
} else if ("s".equals(chunk.conversion)) {
fieldObj = fieldObj.__str__();
} else if (chunk.conversion != null) {
throw Py.ValueError("Unknown conversion specifier " + chunk.conversion);
}
String formatSpec = chunk.formatSpec;
if (chunk.formatSpecNeedsExpanding) {
formatSpec = buildFormattedString(formatSpec, args, keywords);
}
renderField(fieldObj, formatSpec, result);
}
private PyObject getFieldObject(String fieldName, PyObject[] args, String[] keywords) {
FieldNameIterator iterator = new FieldNameIterator(fieldName);
Object head = iterator.head();
PyObject obj = null;
int positionalCount = args.length - keywords.length;
if (head instanceof Integer) {
int index = (Integer) head;
if (index >= positionalCount) {
throw Py.IndexError("tuple index out of range");
}
obj = args[index];
} else {
for (int i = 0; i < keywords.length; i++) {
if (keywords[i].equals(head)) {
obj = args[positionalCount + i];
break;
}
}
if (obj == null) {
throw Py.KeyError((String) head);
}
}
if (obj != null) {
while (true) {
FieldNameIterator.Chunk chunk = iterator.nextChunk();
if (chunk == null) {
break;
}
if (chunk.is_attr) {
obj = obj.__getattr__((String) chunk.value);
} else {
PyObject key = chunk.value instanceof String
? new PyString((String) chunk.value)
: new PyInteger((Integer) chunk.value);
obj = obj.__getitem__(key);
}
if (obj == null) {
break;
}
}
}
return obj;
}
private void renderField(PyObject fieldObj, String formatSpec, StringBuilder result) {
PyString formatSpecStr = formatSpec == null ? Py.EmptyString : new PyString(formatSpec);
result.append(fieldObj.__format__(formatSpecStr).asString());
}
@Override
public PyObject __format__(PyObject formatSpec) {
return str___format__(formatSpec);
}
@ExposedMethod(doc = BuiltinDocs.str___format___doc)
final PyObject str___format__(PyObject formatSpec) {
if (!(formatSpec instanceof PyString)) {
throw Py.TypeError("__format__ requires str or unicode");
}
PyString formatSpecStr = (PyString) formatSpec;
String result;
try {
String specString = formatSpecStr.getString();
InternalFormatSpec spec = new InternalFormatSpecParser(specString).parse();
result = formatString(getString(), spec);
} catch (IllegalArgumentException e) {
throw Py.ValueError(e.getMessage());
}
return formatSpecStr.createInstance(result);
}
/**
* Internal implementation of str.__format__()
*
* @param text the text to format
* @param spec the PEP 3101 formatting specification
* @return the result of the formatting
*/
public static String formatString(String text, InternalFormatSpec spec) {
if (spec.precision >= 0 && text.length() > spec.precision) {
text = text.substring(0, spec.precision);
}
return spec.pad(text, '<', 0);
}
/* arguments' conversion helper */
@Override
public String asString(int index) throws PyObject.ConversionException {
return getString();
}
@Override
public String asString() {
return getString();
}
@Override
public int asInt() {
// We have to override asInt/Long/Double because we override __int/long/float__,
// but generally don't want implicit atoi conversions for the base types. blah
asNumberCheck("__int__", "an integer");
return super.asInt();
}
@Override
public long asLong() {
asNumberCheck("__long__", "an integer");
return super.asLong();
}
@Override
public double asDouble() {
asNumberCheck("__float__", "a float");
return super.asDouble();
}
private void asNumberCheck(String methodName, String description) {
PyType type = getType();
if (type == PyString.TYPE || type == PyUnicode.TYPE || type.lookup(methodName) == null) {
throw Py.TypeError(description + " is required");
}
}
@Override
public String asName(int index) throws PyObject.ConversionException {
return internedString();
}
@Override
protected String unsupportedopMessage(String op, PyObject o2) {
if (op.equals("+")) {
return "cannot concatenate ''{1}'' and ''{2}'' objects";
}
return super.unsupportedopMessage(op, o2);
}
}
final class StringFormatter
{
int index;
String format;
StringBuilder buffer;
boolean negative;
int precision;
int argIndex;
PyObject args;
boolean unicodeCoercion;
final char pop() {
try {
return format.charAt(index++);
} catch (StringIndexOutOfBoundsException e) {
throw Py.ValueError("incomplete format");
}
}
final char peek() {
return format.charAt(index);
}
final void push() {
index--;
}
public StringFormatter(String format) {
this(format, false);
}
public StringFormatter(String format, boolean unicodeCoercion) {
index = 0;
this.format = format;
this.unicodeCoercion = unicodeCoercion;
buffer = new StringBuilder(format.length()+100);
}
PyObject getarg() {
PyObject ret = null;
switch(argIndex) {
// special index indicating a mapping
case -3:
return args;
// special index indicating a single item that has already been
// used
case -2:
break;
// special index indicating a single item that has not yet been
// used
case -1:
argIndex=-2;
return args;
default:
ret = args.__finditem__(argIndex++);
break;
}
if (ret == null)
throw Py.TypeError("not enough arguments for format string");
return ret;
}
int getNumber() {
char c = pop();
if (c == '*') {
PyObject o = getarg();
if (o instanceof PyInteger)
return ((PyInteger)o).getValue();
throw Py.TypeError("* wants int");
} else {
if (Character.isDigit(c)) {
int numStart = index-1;
while (Character.isDigit(c = pop()))
;
index -= 1;
Integer i = Integer.valueOf(
format.substring(numStart, index));
return i.intValue();
}
index -= 1;
return 0;
}
}
private void checkPrecision(String type) {
if(precision > 250) {
// A magic number. Larger than in CPython.
throw Py.OverflowError("formatted " + type + " is too long (precision too long?)");
}
}
private String formatLong(PyObject arg, char type, boolean altFlag) {
PyString argAsString;
switch (type) {
case 'o':
argAsString = arg.__oct__();
break;
case 'x':
case 'X':
argAsString = arg.__hex__();
break;
default:
argAsString = arg.__str__();
break;
}
checkPrecision("long");
String s = argAsString.toString();
int end = s.length();
int ptr = 0;
int numnondigits = 0;
if (type == 'x' || type == 'X')
numnondigits = 2;
if (s.endsWith("L"))
end--;
negative = s.charAt(0) == '-';
if (negative) {
ptr++;
}
int numdigits = end - numnondigits - ptr;
if (!altFlag) {
switch (type) {
case 'o' :
if (numdigits > 1) {
++ptr;
--numdigits;
}
break;
case 'x' :
case 'X' :
ptr += 2;
numnondigits -= 2;
break;
}
}
if (precision > numdigits) {
StringBuilder buf = new StringBuilder();
for (int i = 0; i < numnondigits; ++i)
buf.append(s.charAt(ptr++));
for (int i = 0; i < precision - numdigits; i++)
buf.append('0');
for (int i = 0; i < numdigits; i++)
buf.append(s.charAt(ptr++));
s = buf.toString();
} else if (end < s.length() || ptr > 0)
s = s.substring(ptr, end);
switch (type) {
case 'X' :
s = s.toUpperCase();
break;
}
return s;
}
/**
* Formats arg as an integer, with the specified radix
*
* type and altFlag are needed to be passed to {@link #formatLong(PyObject, char, boolean)}
* in case the result of <code>arg.__int__()</code> is a PyLong.
*/
private String formatInteger(PyObject arg, int radix, boolean unsigned, char type, boolean altFlag) {
PyObject argAsInt;
if (arg instanceof PyInteger || arg instanceof PyLong) {
argAsInt = arg;
} else {
// use __int__ to get an int (or long)
if (arg instanceof PyFloat) {
// safe to call __int__:
argAsInt = arg.__int__();
} else {
// Same case noted on formatFloatDecimal:
// We can't simply call arg.__int__() because PyString implements
// it without exposing it to python (i.e, str instances has no
// __int__ attribute). So, we would support strings as arguments
// for %d format, which is forbidden by CPython tests (on
// test_format.py).
try {
argAsInt = arg.__getattr__("__int__").__call__();
} catch (PyException e) {
// XXX: Swallow customs AttributeError throws from __float__ methods
// No better alternative for the moment
if (e.match(Py.AttributeError)) {
throw Py.TypeError("int argument required");
}
throw e;
}
}
}
if (argAsInt instanceof PyInteger) {
return formatInteger(((PyInteger)argAsInt).getValue(), radix, unsigned);
} else { // must be a PyLong (as per __int__ contract)
return formatLong(argAsInt, type, altFlag);
}
}
private String formatInteger(long v, int radix, boolean unsigned) {
checkPrecision("integer");
if (unsigned) {
if (v < 0)
v = 0x100000000l + v;
} else {
if (v < 0) {
negative = true;
v = -v;
}
}
String s = Long.toString(v, radix);
while (s.length() < precision) {
s = "0"+s;
}
return s;
}
private double asDouble(PyObject obj) {
try {
return obj.asDouble();
} catch (PyException pye) {
throw !pye.match(Py.TypeError) ? pye : Py.TypeError("float argument required");
}
}
private String formatFloatDecimal(double v, boolean truncate) {
checkPrecision("decimal");
java.text.NumberFormat numberFormat = java.text.NumberFormat.getInstance(
java.util.Locale.US);
int prec = precision;
if (prec == -1)
prec = 6;
if (v < 0) {
v = -v;
negative = true;
}
numberFormat.setMaximumFractionDigits(prec);
numberFormat.setMinimumFractionDigits(truncate ? 0 : prec);
numberFormat.setGroupingUsed(false);
String ret = numberFormat.format(v);
return ret;
}
private String formatFloatExponential(PyObject arg, char e,
boolean truncate)
{
StringBuilder buf = new StringBuilder();
double v = asDouble(arg);
boolean isNegative = false;
if (v < 0) {
v = -v;
isNegative = true;
}
double power = 0.0;
if (v > 0)
power = ExtraMath.closeFloor(Math.log10(v));
//System.err.println("formatExp: "+v+", "+power);
int savePrecision = precision;
precision = 2;
String exp = formatInteger((long)power, 10, false);
if (negative) {
negative = false;
exp = '-'+exp;
}
else {
exp = '+' + exp;
}
precision = savePrecision;
double base = v/Math.pow(10, power);
buf.append(formatFloatDecimal(base, truncate));
buf.append(e);
buf.append(exp);
negative = isNegative;
return buf.toString();
}
@SuppressWarnings("fallthrough")
public PyString format(PyObject args) {
PyObject dict = null;
this.args = args;
boolean needUnicode = unicodeCoercion;
if (args instanceof PyTuple) {
argIndex = 0;
} else {
// special index indicating a single item rather than a tuple
argIndex = -1;
if (args instanceof PyDictionary ||
args instanceof PyStringMap ||
(!(args instanceof PySequence) &&
args.__findattr__("__getitem__") != null))
{
dict = args;
argIndex = -3;
}
}
while (index < format.length()) {
boolean ljustFlag=false;
boolean signFlag=false;
boolean blankFlag=false;
boolean altFlag=false;
boolean zeroFlag=false;
int width = -1;
precision = -1;
char c = pop();
if (c != '%') {
buffer.append(c);
continue;
}
c = pop();
if (c == '(') {
if (dict == null)
throw Py.TypeError("format requires a mapping");
int parens = 1;
int keyStart = index;
while (parens > 0) {
c = pop();
if (c == ')')
parens--;
else if (c == '(')
parens++;
}
String tmp = format.substring(keyStart, index-1);
this.args = dict.__getitem__(needUnicode ? new PyUnicode(tmp) : new PyString(tmp));
} else {
push();
}
while (true) {
switch (c = pop()) {
case '-': ljustFlag=true; continue;
case '+': signFlag=true; continue;
case ' ': blankFlag=true; continue;
case '#': altFlag=true; continue;
case '0': zeroFlag=true; continue;
}
break;
}
push();
width = getNumber();
if (width < 0) {
width = -width;
ljustFlag = true;
}
c = pop();
if (c == '.') {
precision = getNumber();
if (precision < -1)
precision = 0;
c = pop();
}
if (c == 'h' || c == 'l' || c == 'L') {
c = pop();
}
if (c == '%') {
buffer.append(c);
continue;
}
PyObject arg = getarg();
char fill = ' ';
String string=null;
negative = false;
if (zeroFlag)
fill = '0';
else
fill = ' ';
switch(c) {
case 's':
if (arg instanceof PyUnicode) {
needUnicode = true;
}
case 'r':
fill = ' ';
if (c == 's')
if (needUnicode)
string = arg.__unicode__().toString();
else
string = arg.__str__().toString();
else
string = arg.__repr__().toString();
if (precision >= 0 && string.length() > precision) {
string = string.substring(0, precision);
}
break;
case 'i':
case 'd':
if (arg instanceof PyLong)
string = formatLong(arg, c, altFlag);
else
string = formatInteger(arg, 10, false, c, altFlag);
break;
case 'u':
if (arg instanceof PyLong)
string = formatLong(arg, c, altFlag);
else if (arg instanceof PyInteger || arg instanceof PyFloat)
string = formatInteger(arg, 10, false, c, altFlag);
else throw Py.TypeError("int argument required");
break;
case 'o':
if (arg instanceof PyLong)
string = formatLong(arg, c, altFlag);
else if (arg instanceof PyInteger || arg instanceof PyFloat) {
string = formatInteger(arg, 8, false, c, altFlag);
if (altFlag && string.charAt(0) != '0') {
string = "0" + string;
}
}
else throw Py.TypeError("int argument required");
break;
case 'x':
if (arg instanceof PyLong)
string = formatLong(arg, c, altFlag);
else if (arg instanceof PyInteger || arg instanceof PyFloat) {
string = formatInteger(arg, 16, false, c, altFlag);
string = string.toLowerCase();
if (altFlag) {
string = "0x" + string;
}
}
else throw Py.TypeError("int argument required");
break;
case 'X':
if (arg instanceof PyLong)
string = formatLong(arg, c, altFlag);
else if (arg instanceof PyInteger || arg instanceof PyFloat) {
string = formatInteger(arg, 16, false, c, altFlag);
string = string.toUpperCase();
if (altFlag) {
string = "0X" + string;
}
}
else throw Py.TypeError("int argument required");
break;
case 'e':
case 'E':
string = formatFloatExponential(arg, c, false);
+ if (c == 'E')
+ string = string.toUpperCase();
break;
case 'f':
case 'F':
string = formatFloatDecimal(asDouble(arg), false);
+ if (c == 'F')
+ string = string.toUpperCase();
break;
case 'g':
case 'G':
int origPrecision = precision;
if (precision == -1) {
precision = 6;
}
double v = asDouble(arg);
int exponent = (int)ExtraMath.closeFloor(Math.log10(Math.abs(v == 0 ? 1 : v)));
if (v == Double.POSITIVE_INFINITY) {
string = "inf";
} else if (v == Double.NEGATIVE_INFINITY) {
string = "-inf";
} else if (exponent >= -4 && exponent < precision) {
precision -= exponent + 1;
string = formatFloatDecimal(v, !altFlag);
// XXX: this block may be unnecessary now
if (altFlag && string.indexOf('.') == -1) {
int zpad = origPrecision - string.length();
string += '.';
if (zpad > 0) {
char zeros[] = new char[zpad];
for (int ci=0; ci<zpad; zeros[ci++] = '0')
;
string += new String(zeros);
}
}
} else {
// Exponential precision is the number of digits after the decimal
// point, whereas 'g' precision is the number of significant digits --
// and expontential always provides one significant digit before the
// decimal point
precision--;
string = formatFloatExponential(arg, (char)(c-2), !altFlag);
}
+ if (c == 'G')
+ string = string.toUpperCase();
break;
case 'c':
fill = ' ';
if (arg instanceof PyString) {
string = ((PyString)arg).toString();
if (string.length() != 1) {
throw Py.TypeError("%c requires int or char");
}
if (arg instanceof PyUnicode) {
needUnicode = true;
}
break;
}
int val;
try {
// Explicitly __int__ so we can look for an AttributeError (which is
// less invasive to mask than a TypeError)
val = arg.__int__().asInt();
} catch (PyException e){
if (e.match(Py.AttributeError)) {
throw Py.TypeError("%c requires int or char");
}
throw e;
}
if (!needUnicode) {
if (val < 0) {
throw Py.OverflowError("unsigned byte integer is less than minimum");
} else if (val > 255) {
throw Py.OverflowError("unsigned byte integer is greater than maximum");
}
} else if (val < 0 || val > PySystemState.maxunicode) {
throw Py.OverflowError("%c arg not in range(0x110000) (wide Python build)");
}
string = new String(new int[] {val}, 0, 1);
break;
default:
throw Py.ValueError("unsupported format character '" +
codecs.encode(Py.newString(c), null, "replace") +
"' (0x" + Integer.toHexString(c) + ") at index " +
(index-1));
}
int length = string.length();
int skip = 0;
String signString = null;
if (negative) {
signString = "-";
} else {
if (signFlag) {
signString = "+";
} else if (blankFlag) {
signString = " ";
}
}
if (width < length)
width = length;
if (signString != null) {
if (fill != ' ')
buffer.append(signString);
if (width > length)
width--;
}
if (altFlag && (c == 'x' || c == 'X')) {
if (fill != ' ') {
buffer.append('0');
buffer.append(c);
skip += 2;
}
width -= 2;
if (width < 0)
width = 0;
length -= 2;
}
if (width > length && !ljustFlag) {
do {
buffer.append(fill);
} while (--width > length);
}
if (fill == ' ') {
if (signString != null)
buffer.append(signString);
if (altFlag && (c == 'x' || c == 'X')) {
buffer.append('0');
buffer.append(c);
skip += 2;
}
}
if (skip > 0)
buffer.append(string.substring(skip));
else
buffer.append(string);
while (--width >= length) {
buffer.append(' ');
}
}
if (argIndex == -1 ||
(argIndex >= 0 && args.__finditem__(argIndex) != null))
{
throw Py.TypeError("not all arguments converted during string formatting");
}
if (needUnicode) {
return new PyUnicode(buffer);
}
return new PyString(buffer);
}
}
| false | true | public PyString format(PyObject args) {
PyObject dict = null;
this.args = args;
boolean needUnicode = unicodeCoercion;
if (args instanceof PyTuple) {
argIndex = 0;
} else {
// special index indicating a single item rather than a tuple
argIndex = -1;
if (args instanceof PyDictionary ||
args instanceof PyStringMap ||
(!(args instanceof PySequence) &&
args.__findattr__("__getitem__") != null))
{
dict = args;
argIndex = -3;
}
}
while (index < format.length()) {
boolean ljustFlag=false;
boolean signFlag=false;
boolean blankFlag=false;
boolean altFlag=false;
boolean zeroFlag=false;
int width = -1;
precision = -1;
char c = pop();
if (c != '%') {
buffer.append(c);
continue;
}
c = pop();
if (c == '(') {
if (dict == null)
throw Py.TypeError("format requires a mapping");
int parens = 1;
int keyStart = index;
while (parens > 0) {
c = pop();
if (c == ')')
parens--;
else if (c == '(')
parens++;
}
String tmp = format.substring(keyStart, index-1);
this.args = dict.__getitem__(needUnicode ? new PyUnicode(tmp) : new PyString(tmp));
} else {
push();
}
while (true) {
switch (c = pop()) {
case '-': ljustFlag=true; continue;
case '+': signFlag=true; continue;
case ' ': blankFlag=true; continue;
case '#': altFlag=true; continue;
case '0': zeroFlag=true; continue;
}
break;
}
push();
width = getNumber();
if (width < 0) {
width = -width;
ljustFlag = true;
}
c = pop();
if (c == '.') {
precision = getNumber();
if (precision < -1)
precision = 0;
c = pop();
}
if (c == 'h' || c == 'l' || c == 'L') {
c = pop();
}
if (c == '%') {
buffer.append(c);
continue;
}
PyObject arg = getarg();
char fill = ' ';
String string=null;
negative = false;
if (zeroFlag)
fill = '0';
else
fill = ' ';
switch(c) {
case 's':
if (arg instanceof PyUnicode) {
needUnicode = true;
}
case 'r':
fill = ' ';
if (c == 's')
if (needUnicode)
string = arg.__unicode__().toString();
else
string = arg.__str__().toString();
else
string = arg.__repr__().toString();
if (precision >= 0 && string.length() > precision) {
string = string.substring(0, precision);
}
break;
case 'i':
case 'd':
if (arg instanceof PyLong)
string = formatLong(arg, c, altFlag);
else
string = formatInteger(arg, 10, false, c, altFlag);
break;
case 'u':
if (arg instanceof PyLong)
string = formatLong(arg, c, altFlag);
else if (arg instanceof PyInteger || arg instanceof PyFloat)
string = formatInteger(arg, 10, false, c, altFlag);
else throw Py.TypeError("int argument required");
break;
case 'o':
if (arg instanceof PyLong)
string = formatLong(arg, c, altFlag);
else if (arg instanceof PyInteger || arg instanceof PyFloat) {
string = formatInteger(arg, 8, false, c, altFlag);
if (altFlag && string.charAt(0) != '0') {
string = "0" + string;
}
}
else throw Py.TypeError("int argument required");
break;
case 'x':
if (arg instanceof PyLong)
string = formatLong(arg, c, altFlag);
else if (arg instanceof PyInteger || arg instanceof PyFloat) {
string = formatInteger(arg, 16, false, c, altFlag);
string = string.toLowerCase();
if (altFlag) {
string = "0x" + string;
}
}
else throw Py.TypeError("int argument required");
break;
case 'X':
if (arg instanceof PyLong)
string = formatLong(arg, c, altFlag);
else if (arg instanceof PyInteger || arg instanceof PyFloat) {
string = formatInteger(arg, 16, false, c, altFlag);
string = string.toUpperCase();
if (altFlag) {
string = "0X" + string;
}
}
else throw Py.TypeError("int argument required");
break;
case 'e':
case 'E':
string = formatFloatExponential(arg, c, false);
break;
case 'f':
case 'F':
string = formatFloatDecimal(asDouble(arg), false);
break;
case 'g':
case 'G':
int origPrecision = precision;
if (precision == -1) {
precision = 6;
}
double v = asDouble(arg);
int exponent = (int)ExtraMath.closeFloor(Math.log10(Math.abs(v == 0 ? 1 : v)));
if (v == Double.POSITIVE_INFINITY) {
string = "inf";
} else if (v == Double.NEGATIVE_INFINITY) {
string = "-inf";
} else if (exponent >= -4 && exponent < precision) {
precision -= exponent + 1;
string = formatFloatDecimal(v, !altFlag);
// XXX: this block may be unnecessary now
if (altFlag && string.indexOf('.') == -1) {
int zpad = origPrecision - string.length();
string += '.';
if (zpad > 0) {
char zeros[] = new char[zpad];
for (int ci=0; ci<zpad; zeros[ci++] = '0')
;
string += new String(zeros);
}
}
} else {
// Exponential precision is the number of digits after the decimal
// point, whereas 'g' precision is the number of significant digits --
// and expontential always provides one significant digit before the
// decimal point
precision--;
string = formatFloatExponential(arg, (char)(c-2), !altFlag);
}
break;
case 'c':
fill = ' ';
if (arg instanceof PyString) {
string = ((PyString)arg).toString();
if (string.length() != 1) {
throw Py.TypeError("%c requires int or char");
}
if (arg instanceof PyUnicode) {
needUnicode = true;
}
break;
}
int val;
try {
// Explicitly __int__ so we can look for an AttributeError (which is
// less invasive to mask than a TypeError)
val = arg.__int__().asInt();
} catch (PyException e){
if (e.match(Py.AttributeError)) {
throw Py.TypeError("%c requires int or char");
}
throw e;
}
if (!needUnicode) {
if (val < 0) {
throw Py.OverflowError("unsigned byte integer is less than minimum");
} else if (val > 255) {
throw Py.OverflowError("unsigned byte integer is greater than maximum");
}
} else if (val < 0 || val > PySystemState.maxunicode) {
throw Py.OverflowError("%c arg not in range(0x110000) (wide Python build)");
}
string = new String(new int[] {val}, 0, 1);
break;
default:
throw Py.ValueError("unsupported format character '" +
codecs.encode(Py.newString(c), null, "replace") +
"' (0x" + Integer.toHexString(c) + ") at index " +
(index-1));
}
int length = string.length();
int skip = 0;
String signString = null;
if (negative) {
signString = "-";
} else {
if (signFlag) {
signString = "+";
} else if (blankFlag) {
signString = " ";
}
}
if (width < length)
width = length;
if (signString != null) {
if (fill != ' ')
buffer.append(signString);
if (width > length)
width--;
}
if (altFlag && (c == 'x' || c == 'X')) {
if (fill != ' ') {
buffer.append('0');
buffer.append(c);
skip += 2;
}
width -= 2;
if (width < 0)
width = 0;
length -= 2;
}
if (width > length && !ljustFlag) {
do {
buffer.append(fill);
} while (--width > length);
}
if (fill == ' ') {
if (signString != null)
buffer.append(signString);
if (altFlag && (c == 'x' || c == 'X')) {
buffer.append('0');
buffer.append(c);
skip += 2;
}
}
if (skip > 0)
buffer.append(string.substring(skip));
else
buffer.append(string);
while (--width >= length) {
buffer.append(' ');
}
}
if (argIndex == -1 ||
(argIndex >= 0 && args.__finditem__(argIndex) != null))
{
throw Py.TypeError("not all arguments converted during string formatting");
}
if (needUnicode) {
return new PyUnicode(buffer);
}
return new PyString(buffer);
}
| public PyString format(PyObject args) {
PyObject dict = null;
this.args = args;
boolean needUnicode = unicodeCoercion;
if (args instanceof PyTuple) {
argIndex = 0;
} else {
// special index indicating a single item rather than a tuple
argIndex = -1;
if (args instanceof PyDictionary ||
args instanceof PyStringMap ||
(!(args instanceof PySequence) &&
args.__findattr__("__getitem__") != null))
{
dict = args;
argIndex = -3;
}
}
while (index < format.length()) {
boolean ljustFlag=false;
boolean signFlag=false;
boolean blankFlag=false;
boolean altFlag=false;
boolean zeroFlag=false;
int width = -1;
precision = -1;
char c = pop();
if (c != '%') {
buffer.append(c);
continue;
}
c = pop();
if (c == '(') {
if (dict == null)
throw Py.TypeError("format requires a mapping");
int parens = 1;
int keyStart = index;
while (parens > 0) {
c = pop();
if (c == ')')
parens--;
else if (c == '(')
parens++;
}
String tmp = format.substring(keyStart, index-1);
this.args = dict.__getitem__(needUnicode ? new PyUnicode(tmp) : new PyString(tmp));
} else {
push();
}
while (true) {
switch (c = pop()) {
case '-': ljustFlag=true; continue;
case '+': signFlag=true; continue;
case ' ': blankFlag=true; continue;
case '#': altFlag=true; continue;
case '0': zeroFlag=true; continue;
}
break;
}
push();
width = getNumber();
if (width < 0) {
width = -width;
ljustFlag = true;
}
c = pop();
if (c == '.') {
precision = getNumber();
if (precision < -1)
precision = 0;
c = pop();
}
if (c == 'h' || c == 'l' || c == 'L') {
c = pop();
}
if (c == '%') {
buffer.append(c);
continue;
}
PyObject arg = getarg();
char fill = ' ';
String string=null;
negative = false;
if (zeroFlag)
fill = '0';
else
fill = ' ';
switch(c) {
case 's':
if (arg instanceof PyUnicode) {
needUnicode = true;
}
case 'r':
fill = ' ';
if (c == 's')
if (needUnicode)
string = arg.__unicode__().toString();
else
string = arg.__str__().toString();
else
string = arg.__repr__().toString();
if (precision >= 0 && string.length() > precision) {
string = string.substring(0, precision);
}
break;
case 'i':
case 'd':
if (arg instanceof PyLong)
string = formatLong(arg, c, altFlag);
else
string = formatInteger(arg, 10, false, c, altFlag);
break;
case 'u':
if (arg instanceof PyLong)
string = formatLong(arg, c, altFlag);
else if (arg instanceof PyInteger || arg instanceof PyFloat)
string = formatInteger(arg, 10, false, c, altFlag);
else throw Py.TypeError("int argument required");
break;
case 'o':
if (arg instanceof PyLong)
string = formatLong(arg, c, altFlag);
else if (arg instanceof PyInteger || arg instanceof PyFloat) {
string = formatInteger(arg, 8, false, c, altFlag);
if (altFlag && string.charAt(0) != '0') {
string = "0" + string;
}
}
else throw Py.TypeError("int argument required");
break;
case 'x':
if (arg instanceof PyLong)
string = formatLong(arg, c, altFlag);
else if (arg instanceof PyInteger || arg instanceof PyFloat) {
string = formatInteger(arg, 16, false, c, altFlag);
string = string.toLowerCase();
if (altFlag) {
string = "0x" + string;
}
}
else throw Py.TypeError("int argument required");
break;
case 'X':
if (arg instanceof PyLong)
string = formatLong(arg, c, altFlag);
else if (arg instanceof PyInteger || arg instanceof PyFloat) {
string = formatInteger(arg, 16, false, c, altFlag);
string = string.toUpperCase();
if (altFlag) {
string = "0X" + string;
}
}
else throw Py.TypeError("int argument required");
break;
case 'e':
case 'E':
string = formatFloatExponential(arg, c, false);
if (c == 'E')
string = string.toUpperCase();
break;
case 'f':
case 'F':
string = formatFloatDecimal(asDouble(arg), false);
if (c == 'F')
string = string.toUpperCase();
break;
case 'g':
case 'G':
int origPrecision = precision;
if (precision == -1) {
precision = 6;
}
double v = asDouble(arg);
int exponent = (int)ExtraMath.closeFloor(Math.log10(Math.abs(v == 0 ? 1 : v)));
if (v == Double.POSITIVE_INFINITY) {
string = "inf";
} else if (v == Double.NEGATIVE_INFINITY) {
string = "-inf";
} else if (exponent >= -4 && exponent < precision) {
precision -= exponent + 1;
string = formatFloatDecimal(v, !altFlag);
// XXX: this block may be unnecessary now
if (altFlag && string.indexOf('.') == -1) {
int zpad = origPrecision - string.length();
string += '.';
if (zpad > 0) {
char zeros[] = new char[zpad];
for (int ci=0; ci<zpad; zeros[ci++] = '0')
;
string += new String(zeros);
}
}
} else {
// Exponential precision is the number of digits after the decimal
// point, whereas 'g' precision is the number of significant digits --
// and expontential always provides one significant digit before the
// decimal point
precision--;
string = formatFloatExponential(arg, (char)(c-2), !altFlag);
}
if (c == 'G')
string = string.toUpperCase();
break;
case 'c':
fill = ' ';
if (arg instanceof PyString) {
string = ((PyString)arg).toString();
if (string.length() != 1) {
throw Py.TypeError("%c requires int or char");
}
if (arg instanceof PyUnicode) {
needUnicode = true;
}
break;
}
int val;
try {
// Explicitly __int__ so we can look for an AttributeError (which is
// less invasive to mask than a TypeError)
val = arg.__int__().asInt();
} catch (PyException e){
if (e.match(Py.AttributeError)) {
throw Py.TypeError("%c requires int or char");
}
throw e;
}
if (!needUnicode) {
if (val < 0) {
throw Py.OverflowError("unsigned byte integer is less than minimum");
} else if (val > 255) {
throw Py.OverflowError("unsigned byte integer is greater than maximum");
}
} else if (val < 0 || val > PySystemState.maxunicode) {
throw Py.OverflowError("%c arg not in range(0x110000) (wide Python build)");
}
string = new String(new int[] {val}, 0, 1);
break;
default:
throw Py.ValueError("unsupported format character '" +
codecs.encode(Py.newString(c), null, "replace") +
"' (0x" + Integer.toHexString(c) + ") at index " +
(index-1));
}
int length = string.length();
int skip = 0;
String signString = null;
if (negative) {
signString = "-";
} else {
if (signFlag) {
signString = "+";
} else if (blankFlag) {
signString = " ";
}
}
if (width < length)
width = length;
if (signString != null) {
if (fill != ' ')
buffer.append(signString);
if (width > length)
width--;
}
if (altFlag && (c == 'x' || c == 'X')) {
if (fill != ' ') {
buffer.append('0');
buffer.append(c);
skip += 2;
}
width -= 2;
if (width < 0)
width = 0;
length -= 2;
}
if (width > length && !ljustFlag) {
do {
buffer.append(fill);
} while (--width > length);
}
if (fill == ' ') {
if (signString != null)
buffer.append(signString);
if (altFlag && (c == 'x' || c == 'X')) {
buffer.append('0');
buffer.append(c);
skip += 2;
}
}
if (skip > 0)
buffer.append(string.substring(skip));
else
buffer.append(string);
while (--width >= length) {
buffer.append(' ');
}
}
if (argIndex == -1 ||
(argIndex >= 0 && args.__finditem__(argIndex) != null))
{
throw Py.TypeError("not all arguments converted during string formatting");
}
if (needUnicode) {
return new PyUnicode(buffer);
}
return new PyString(buffer);
}
|
diff --git a/parser/org/eclipse/cdt/internal/core/parser/ast/complete/CompleteParseASTFactory.java b/parser/org/eclipse/cdt/internal/core/parser/ast/complete/CompleteParseASTFactory.java
index 11eab1833..b4eab4c49 100644
--- a/parser/org/eclipse/cdt/internal/core/parser/ast/complete/CompleteParseASTFactory.java
+++ b/parser/org/eclipse/cdt/internal/core/parser/ast/complete/CompleteParseASTFactory.java
@@ -1,3725 +1,3727 @@
/**********************************************************************
* Copyright (c) 2002,2003, 2004 Rational Software Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* IBM Rational Software - Initial API and implementation
***********************************************************************/
package org.eclipse.cdt.internal.core.parser.ast.complete;
import java.util.ArrayList;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Stack;
import org.eclipse.cdt.core.parser.Enum;
import org.eclipse.cdt.core.parser.IFilenameProvider;
import org.eclipse.cdt.core.parser.IProblem;
import org.eclipse.cdt.core.parser.ISourceElementCallbackDelegate;
import org.eclipse.cdt.core.parser.IToken;
import org.eclipse.cdt.core.parser.ITokenDuple;
import org.eclipse.cdt.core.parser.ParserLanguage;
import org.eclipse.cdt.core.parser.ParserMode;
import org.eclipse.cdt.core.parser.ast.ASTAccessVisibility;
import org.eclipse.cdt.core.parser.ast.ASTClassKind;
import org.eclipse.cdt.core.parser.ast.ASTNotImplementedException;
import org.eclipse.cdt.core.parser.ast.ASTPointerOperator;
import org.eclipse.cdt.core.parser.ast.ASTSemanticException;
import org.eclipse.cdt.core.parser.ast.IASTASMDefinition;
import org.eclipse.cdt.core.parser.ast.IASTAbstractDeclaration;
import org.eclipse.cdt.core.parser.ast.IASTAbstractTypeSpecifierDeclaration;
import org.eclipse.cdt.core.parser.ast.IASTClassSpecifier;
import org.eclipse.cdt.core.parser.ast.IASTCodeScope;
import org.eclipse.cdt.core.parser.ast.IASTCompilationUnit;
import org.eclipse.cdt.core.parser.ast.IASTConstructorMemberInitializer;
import org.eclipse.cdt.core.parser.ast.IASTDesignator;
import org.eclipse.cdt.core.parser.ast.IASTElaboratedTypeSpecifier;
import org.eclipse.cdt.core.parser.ast.IASTEnumerationSpecifier;
import org.eclipse.cdt.core.parser.ast.IASTEnumerator;
import org.eclipse.cdt.core.parser.ast.IASTExceptionSpecification;
import org.eclipse.cdt.core.parser.ast.IASTExpression;
import org.eclipse.cdt.core.parser.ast.IASTFactory;
import org.eclipse.cdt.core.parser.ast.IASTField;
import org.eclipse.cdt.core.parser.ast.IASTFunction;
import org.eclipse.cdt.core.parser.ast.IASTInitializerClause;
import org.eclipse.cdt.core.parser.ast.IASTLinkageSpecification;
import org.eclipse.cdt.core.parser.ast.IASTMethod;
import org.eclipse.cdt.core.parser.ast.IASTNamespaceAlias;
import org.eclipse.cdt.core.parser.ast.IASTNamespaceDefinition;
import org.eclipse.cdt.core.parser.ast.IASTNode;
import org.eclipse.cdt.core.parser.ast.IASTParameterDeclaration;
import org.eclipse.cdt.core.parser.ast.IASTReference;
import org.eclipse.cdt.core.parser.ast.IASTScope;
import org.eclipse.cdt.core.parser.ast.IASTSimpleTypeSpecifier;
import org.eclipse.cdt.core.parser.ast.IASTTemplate;
import org.eclipse.cdt.core.parser.ast.IASTTemplateDeclaration;
import org.eclipse.cdt.core.parser.ast.IASTTemplateInstantiation;
import org.eclipse.cdt.core.parser.ast.IASTTemplateParameter;
import org.eclipse.cdt.core.parser.ast.IASTTemplateSpecialization;
import org.eclipse.cdt.core.parser.ast.IASTTypeId;
import org.eclipse.cdt.core.parser.ast.IASTTypeSpecifier;
import org.eclipse.cdt.core.parser.ast.IASTTypedefDeclaration;
import org.eclipse.cdt.core.parser.ast.IASTUsingDeclaration;
import org.eclipse.cdt.core.parser.ast.IASTUsingDirective;
import org.eclipse.cdt.core.parser.ast.IASTVariable;
import org.eclipse.cdt.core.parser.ast.IReferenceManager;
import org.eclipse.cdt.core.parser.ast.IASTClassSpecifier.ClassNameType;
import org.eclipse.cdt.core.parser.ast.IASTExpression.IASTNewExpressionDescriptor;
import org.eclipse.cdt.core.parser.ast.IASTExpression.Kind;
import org.eclipse.cdt.core.parser.ast.IASTSimpleTypeSpecifier.Type;
import org.eclipse.cdt.core.parser.ast.IASTTemplateParameter.ParamKind;
import org.eclipse.cdt.core.parser.extension.IASTFactoryExtension;
import org.eclipse.cdt.internal.core.parser.ast.ASTAbstractDeclaration;
import org.eclipse.cdt.internal.core.parser.ast.BaseASTFactory;
import org.eclipse.cdt.internal.core.parser.problem.IProblemFactory;
import org.eclipse.cdt.internal.core.parser.pst.ExtensibleSymbolExtension;
import org.eclipse.cdt.internal.core.parser.pst.ForewardDeclaredSymbolExtension;
import org.eclipse.cdt.internal.core.parser.pst.IContainerSymbol;
import org.eclipse.cdt.internal.core.parser.pst.IDeferredTemplateInstance;
import org.eclipse.cdt.internal.core.parser.pst.IDerivableContainerSymbol;
import org.eclipse.cdt.internal.core.parser.pst.IExtensibleSymbol;
import org.eclipse.cdt.internal.core.parser.pst.IParameterizedSymbol;
import org.eclipse.cdt.internal.core.parser.pst.ISymbol;
import org.eclipse.cdt.internal.core.parser.pst.ISymbolASTExtension;
import org.eclipse.cdt.internal.core.parser.pst.ISymbolOwner;
import org.eclipse.cdt.internal.core.parser.pst.ITemplateFactory;
import org.eclipse.cdt.internal.core.parser.pst.ITemplateSymbol;
import org.eclipse.cdt.internal.core.parser.pst.IUsingDeclarationSymbol;
import org.eclipse.cdt.internal.core.parser.pst.IUsingDirectiveSymbol;
import org.eclipse.cdt.internal.core.parser.pst.NamespaceSymbolExtension;
import org.eclipse.cdt.internal.core.parser.pst.ParserSymbolTable;
import org.eclipse.cdt.internal.core.parser.pst.ParserSymbolTableError;
import org.eclipse.cdt.internal.core.parser.pst.ParserSymbolTableException;
import org.eclipse.cdt.internal.core.parser.pst.StandardSymbolExtension;
import org.eclipse.cdt.internal.core.parser.pst.TemplateSymbolExtension;
import org.eclipse.cdt.internal.core.parser.pst.TypeInfo;
import org.eclipse.cdt.internal.core.parser.pst.ISymbolASTExtension.ExtensionException;
import org.eclipse.cdt.internal.core.parser.pst.ParserSymbolTable.TypeInfoProvider;
import org.eclipse.cdt.internal.core.parser.pst.TypeInfo.PtrOp;
import org.eclipse.cdt.internal.core.parser.token.TokenFactory;
import org.eclipse.cdt.internal.core.parser.util.TraceUtil;
/**
* @author jcamelon
*
* The CompleteParseASTFactory class creates a complete AST
* for a given parsed code.
*
*/
public class CompleteParseASTFactory extends BaseASTFactory implements IASTFactory
{
protected static final String EMPTY_STRING = ""; //$NON-NLS-1$
private final static List SUBSCRIPT;
private final static IProblemFactory problemFactory = new ASTProblemFactory();
private final IFilenameProvider fileProvider;
private final ParserMode mode;
private final ReferenceCache cache = new ReferenceCache();
private static final int BUILTIN_TYPE_SIZE = 64;
private final Hashtable typeIdCache = new Hashtable( BUILTIN_TYPE_SIZE );
private final Hashtable simpleTypeSpecCache = new Hashtable( BUILTIN_TYPE_SIZE );
private static final int DEFAULT_QUALIFIEDNAME_REFERENCE_SIZE = 4;
static
{
SUBSCRIPT = new ArrayList(1);
SUBSCRIPT.add( TypeInfo.OperatorExpression.subscript );
}
static private class LookupType extends Enum {
public static final LookupType QUALIFIED = new LookupType( 1 );
public static final LookupType UNQUALIFIED = new LookupType( 2 );
public static final LookupType FORDEFINITION = new LookupType( 3 );
public static final LookupType FORFRIENDSHIP = new LookupType( 4 );
public static final LookupType FORPARENTSCOPE = new LookupType( 5 );
private LookupType( int constant)
{
super( constant );
}
}
public CompleteParseASTFactory( IFilenameProvider filenameProvider, ParserLanguage language, ParserMode mode, IASTFactoryExtension extension )
{
super(extension);
pst = new ParserSymbolTable( language, mode );
fileProvider = filenameProvider;
this.mode = mode;
}
/*
* Adds a reference to a reference list
* Overrides an existing reference if it has the same name and offset
*/
protected void addReference(List references, IASTReference reference){
if( reference == null )
return;
if( references == null )
{
cache.returnReference( reference );
return;
}
Iterator i = references.iterator();
while (i.hasNext()){
IASTReference ref = (IASTReference)i.next();
if (ref != null){
if( (ref.getName().equals(reference.getName()))
&& (ref.getOffset() == reference.getOffset())
){
cache.returnReference( ref );
i.remove();
break;
}
}
}
references.add(reference);
}
protected void addTemplateIdReferences( List references, List templateArgs ){
if( templateArgs == null )
return;
Iterator i = templateArgs.iterator();
while( i.hasNext() ){
ASTExpression exp = (ASTExpression) i.next();
Iterator j = null;
if( exp.getExpressionKind() == IASTExpression.Kind.POSTFIX_TYPEID_TYPEID )
j = ((ASTTypeId) exp.getTypeId()).getReferences().iterator();
else
j = exp.getReferences().iterator();
while( j.hasNext() ){
IASTReference r = (IASTReference) j.next();
addReference( references, cache.getReference(r.getOffset(), r.getReferencedElement()));
}
}
}
/*
* Test if the provided list is a valid parameter list
* Parameters are list of TypeInfos
*/
protected boolean validParameterList(List parameters){
Iterator i = parameters.iterator();
while (i.hasNext()){
TypeInfo info = (TypeInfo)i.next();
if (info != null){
if((info.getType() == TypeInfo.t_type)
&& (info.getTypeSymbol() == null))
return false;
}else
return false;
}
return true;
}
private ISymbol lookupElement (IContainerSymbol startingScope, String name, TypeInfo.eType type, List parameters, LookupType lookupType ) throws ASTSemanticException {
return lookupElement( startingScope, name, type, parameters, null, lookupType );
}
private ISymbol lookupElement (IContainerSymbol startingScope, String name, TypeInfo.eType type, List parameters, List arguments, LookupType lookupType ) throws ASTSemanticException {
ISymbol result = null;
if( startingScope == null ) return null;
try {
if((type == TypeInfo.t_function) || (type == TypeInfo.t_constructor)){
// looking for a function
if(validParameterList(parameters))
if(type == TypeInfo.t_constructor){
IDerivableContainerSymbol startingDerivableScope = (IDerivableContainerSymbol) startingScope;
result = startingDerivableScope.lookupConstructor( new LinkedList(parameters));
}
else {
if( arguments != null )
result = startingScope.lookupFunctionTemplateId( name, new LinkedList( parameters), new LinkedList( arguments ), ( lookupType == LookupType.FORDEFINITION ) );
else if( lookupType == LookupType.QUALIFIED )
result = startingScope.qualifiedFunctionLookup(name, new LinkedList(parameters));
else if( lookupType == LookupType.UNQUALIFIED || lookupType == LookupType.FORPARENTSCOPE)
result = startingScope.unqualifiedFunctionLookup( name, new LinkedList( parameters ) );
else if( lookupType == LookupType.FORDEFINITION )
result = startingScope.lookupMethodForDefinition( name, new LinkedList( parameters ) );
else if( lookupType == LookupType.FORFRIENDSHIP ){
result = ((IDerivableContainerSymbol)startingScope).lookupFunctionForFriendship( name, new LinkedList( parameters) );
}
}
else
result = null;
}else{
// looking for something else
if( arguments != null )
result = startingScope.lookupTemplateId( name, arguments );
else if( lookupType == LookupType.QUALIFIED )
result = startingScope.qualifiedLookup(name, type);
else if( lookupType == LookupType.UNQUALIFIED || lookupType == LookupType.FORPARENTSCOPE )
result = startingScope.elaboratedLookup( type, name );
else if( lookupType == LookupType.FORDEFINITION )
result = startingScope.lookupMemberForDefinition( name );
else if( lookupType == LookupType.FORFRIENDSHIP )
result = ((IDerivableContainerSymbol)startingScope).lookupForFriendship( name );
}
} catch (ParserSymbolTableException e) {
if( e.reason != ParserSymbolTableException.r_UnableToResolveFunction )
handleProblem( e.createProblemID(), name );
} catch (ParserSymbolTableError e){
handleProblem( IProblem.INTERNAL_RELATED, name );
}
return result;
}
protected ISymbol lookupQualifiedName( IContainerSymbol startingScope, String name, List references, boolean throwOnError, LookupType lookup ) throws ASTSemanticException{
return lookupQualifiedName(startingScope, name, TypeInfo.t_any, null, 0, references, throwOnError, lookup );
}
protected ISymbol lookupQualifiedName( IContainerSymbol startingScope, String name, TypeInfo.eType type, List parameters, int offset, List references, boolean throwOnError, LookupType lookup ) throws ASTSemanticException
{
ISymbol result = null;
if( name == null && throwOnError )
handleProblem( IProblem.SEMANTIC_NAME_NOT_PROVIDED, null );
else if( name == null ) return null;
try
{
result = lookupElement(startingScope, name, type, parameters, lookup);
if( result != null )
addReference(references, createReference( result, name, offset ));
else if( throwOnError )
handleProblem( IProblem.SEMANTIC_NAME_NOT_FOUND, name );
}
catch (ASTSemanticException e)
{
if( throwOnError )
throw new ASTSemanticException( e );
return null;
}
return result;
}
protected ISymbol lookupQualifiedName( IContainerSymbol startingScope, ITokenDuple name, List references, boolean throwOnError ) throws ASTSemanticException{
return lookupQualifiedName(startingScope, name, references, throwOnError, LookupType.UNQUALIFIED);
}
protected ISymbol lookupQualifiedName( IContainerSymbol startingScope, ITokenDuple name, List references, boolean throwOnError, LookupType lookup ) throws ASTSemanticException{
return lookupQualifiedName(startingScope, name, TypeInfo.t_any, null, references, throwOnError, lookup );
}
protected ISymbol lookupQualifiedName( IContainerSymbol startingScope, ITokenDuple name, TypeInfo.eType type, List parameters, List references, boolean throwOnError ) throws ASTSemanticException{
return lookupQualifiedName( startingScope, name, type, parameters, references, throwOnError, LookupType.UNQUALIFIED );
}
protected ISymbol lookupQualifiedName( IContainerSymbol startingScope, ITokenDuple name, TypeInfo.eType type, List parameters, List references, boolean throwOnError, LookupType lookup ) throws ASTSemanticException
{
ISymbol result = null;
IToken firstSymbol = null;
if( name == null && throwOnError ) handleProblem( IProblem.SEMANTIC_NAME_NOT_PROVIDED, null );
else if( name == null ) return null;
List [] templateArgLists = name.getTemplateIdArgLists();
List args = null;
int idx = 0;
String image = null;
switch( name.getSegmentCount() )
{
case 0:
if( throwOnError )
handleProblem( IProblem.SEMANTIC_NAME_NOT_PROVIDED, null );
else
return null;
case 1:
image = name.extractNameFromTemplateId();
args = ( templateArgLists != null ) ? getTemplateArgList( templateArgLists[ 0 ] ) : null;
result = lookupElement(startingScope, image, type, parameters, args, lookup );
if( result != null )
{
if( lookup == LookupType.FORPARENTSCOPE && startingScope instanceof ITemplateFactory ){
if( args != null )
((ITemplateFactory)startingScope).pushTemplateId( result, args );
else
((ITemplateFactory)startingScope).pushSymbol( result );
}
if( references != null )
addReference( references, createReference( result, image, name.getStartOffset() ));
if( args != null && references != null )
{
addTemplateIdReferences( references, templateArgLists[0] );
name.freeReferences( cache );
}
}
else
{
if( startingScope.getASTExtension().getPrimaryDeclaration() instanceof IASTCodeScope )
{
if( ((IASTCodeScope) startingScope.getASTExtension().getPrimaryDeclaration()).getContainingFunction() instanceof IASTMethod )
{
IASTClassSpecifier classSpecifier = ((IASTMethod) ((IASTCodeScope) startingScope.getASTExtension().getPrimaryDeclaration()).getContainingFunction()).getOwnerClassSpecifier();
if( classSpecifier != null )
((ASTClassSpecifier)classSpecifier).addUnresolvedReference( new UnresolvedReferenceDuple( startingScope, name ));
break;
}
}
if ( throwOnError )
handleProblem( IProblem.SEMANTIC_NAME_NOT_FOUND, image, name.getStartOffset(), name.getEndOffset(), name.getLineNumber(), true );
return null;
}
break;
default:
Iterator iter = name.iterator();
firstSymbol = name.getFirstToken();
result = startingScope;
if( firstSymbol.getType() == IToken.tCOLONCOLON )
result = pst.getCompilationUnit();
while( iter.hasNext() )
{
IToken t = (IToken)iter.next();
if( t.getType() == IToken.tCOLONCOLON ){
idx++;
continue;
} else if( t.getType() == IToken.t_template ){
continue;
}
if( t.isPointer() ) break;
image = t.getImage();
int offset = t.getOffset();
if( templateArgLists != null && templateArgLists[ idx ] != null ){
if( iter.hasNext() && t.getNext().getType() == IToken.tLT )
t = TokenFactory.consumeTemplateIdArguments( (IToken) iter.next(), iter );
}
try
{
if( result instanceof IDeferredTemplateInstance ){
result = ((IDeferredTemplateInstance)result).getTemplate().getTemplatedSymbol();
}
args = ( templateArgLists != null ) ? getTemplateArgList( templateArgLists[ idx ] ) : null;
if( t == name.getLastToken() )
result = lookupElement((IContainerSymbol)result, image, type, parameters, args, ( lookup == LookupType.FORDEFINITION ) ? lookup : LookupType.QUALIFIED );
else
if( templateArgLists != null && templateArgLists[idx] != null )
result = ((IContainerSymbol)result).lookupTemplateId( image, args );
else
result = ((IContainerSymbol)result).lookupNestedNameSpecifier( image );
if( result != null ){
if( lookup == LookupType.FORPARENTSCOPE && startingScope instanceof ITemplateFactory ){
if( templateArgLists != null && templateArgLists[idx] != null )
((ITemplateFactory)startingScope).pushTemplateId( result, args );
else
((ITemplateFactory)startingScope).pushSymbol( result );
}
if( references != null )
addReference( references, createReference( result, image, offset ));
if( references != null && templateArgLists != null && templateArgLists[idx] != null )
{
addTemplateIdReferences( references, templateArgLists[idx] );
name.freeReferences(cache);
}
}
else
break;
}
catch( ParserSymbolTableException pste )
{
if ( throwOnError )
handleProblem( pste.createProblemID(), image );
return null;
}
catch( ParserSymbolTableError e )
{
if( throwOnError )
handleProblem( IProblem.INTERNAL_RELATED, image );
return null;
}
}
}
return result;
}
protected IToken consumeTemplateIdArguments( IToken name, Iterator iter ){
IToken token = name;
if( token.getNext().getType() == IToken.tLT )
{
token = (IToken) iter.next();
Stack scopes = new Stack();
scopes.push(new Integer(IToken.tLT));
while (!scopes.empty())
{
int top;
token = (IToken) iter.next();
switch( token.getType() ){
case IToken.tGT:
if (((Integer)scopes.peek()).intValue() == IToken.tLT) {
scopes.pop();
}
break;
case IToken.tRBRACKET :
do {
top = ((Integer)scopes.pop()).intValue();
} while (!scopes.empty() && (top == IToken.tGT || top == IToken.tLT));
//if (top != IToken.tLBRACKET) throw backtrack;
break;
case IToken.tRPAREN :
do {
top = ((Integer)scopes.pop()).intValue();
} while (!scopes.empty() && (top == IToken.tGT || top == IToken.tLT));
//if (top != IToken.tLPAREN) throw backtrack;
break;
case IToken.tLT :
case IToken.tLBRACKET:
case IToken.tLPAREN:
scopes.push(new Integer(token.getType()));
break;
}
}
}
return token;
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.parser.ast.IASTFactory#createUsingDirective(org.eclipse.cdt.core.parser.ast.IASTScope, org.eclipse.cdt.core.parser.ITokenDuple, int, int)
*/
public IASTUsingDirective createUsingDirective(
IASTScope scope,
ITokenDuple duple,
int startingOffset,
int startingLine, int endingOffset, int endingLine)
throws ASTSemanticException
{
List references = new ArrayList();
ISymbol symbol = lookupQualifiedName(
scopeToSymbol( scope), duple, references, true );
IUsingDirectiveSymbol usingDirective = null;
if( symbol != null )
try {
usingDirective = ((ASTScope)scope).getContainerSymbol().addUsingDirective( (IContainerSymbol)symbol );
} catch (ParserSymbolTableException pste) {
handleProblem( pste.createProblemID(), duple.toString(), startingOffset, endingOffset, startingLine, true );
}
ASTUsingDirective using = new ASTUsingDirective( scopeToSymbol(scope), usingDirective, startingOffset, startingLine, endingOffset, endingLine, references );
attachSymbolExtension( usingDirective, using );
return using;
}
protected IContainerSymbol getScopeToSearchUpon(
IASTScope currentScope,
IToken firstToken, Iterator iterator )
{
if( firstToken.getType() == IToken.tCOLONCOLON )
{
iterator.next();
return pst.getCompilationUnit();
}
return scopeToSymbol(currentScope);
}
protected IContainerSymbol scopeToSymbol(IASTScope currentScope)
{
if( currentScope instanceof ASTScope )
return ((ASTScope)currentScope).getContainerSymbol();
else if ( currentScope instanceof ASTTemplateDeclaration )
return ((ASTTemplateDeclaration)currentScope).getContainerSymbol();
else if ( currentScope instanceof ASTTemplateInstantiation )
return ((ASTTemplateInstantiation)currentScope).getContainerSymbol();
else
return scopeToSymbol(((ASTAnonymousDeclaration)currentScope).getOwnerScope());
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.parser.ast.IASTFactory#createUsingDeclaration(org.eclipse.cdt.core.parser.ast.IASTScope, boolean, org.eclipse.cdt.core.parser.ITokenDuple, int, int)
*/
public IASTUsingDeclaration createUsingDeclaration(
IASTScope scope,
boolean isTypeName,
ITokenDuple name,
int startingOffset,
int startingLine, int endingOffset, int endingLine) throws ASTSemanticException
{
List references = new ArrayList();
IUsingDeclarationSymbol endResult = null;
if(name.getSegmentCount() > 1)
{
ITokenDuple duple = name.getLeadingSegments();
IContainerSymbol containerSymbol = null;
if( duple == null ){
//null leading segment means globally qualified
containerSymbol = scopeToSymbol( scope ).getSymbolTable().getCompilationUnit();
} else {
ISymbol symbol = lookupQualifiedName( scopeToSymbol(scope), duple, references, true );
if( symbol instanceof IContainerSymbol )
containerSymbol = (IContainerSymbol) symbol;
else if ( symbol instanceof IDeferredTemplateInstance )
containerSymbol = ((IDeferredTemplateInstance)symbol).getTemplate().getTemplatedSymbol();
}
try
{
endResult = scopeToSymbol(scope).addUsingDeclaration( name.getLastToken().getImage(), containerSymbol );
}
catch (ParserSymbolTableException e)
{
handleProblem(e.createProblemID(), name.getLastToken().getImage(), startingOffset, endingOffset, startingLine, true );
}
} else
try {
endResult = scopeToSymbol(scope).addUsingDeclaration(name.getLastToken().getImage());
} catch (ParserSymbolTableException e) {
handleProblem(e.createProblemID(), name.getLastToken().getImage(), startingOffset, endingOffset, startingLine, true );
}
if( endResult != null )
{
Iterator i = endResult.getReferencedSymbols().iterator();
while( i.hasNext() )
addReference( references, createReference( (ISymbol) i.next(), name.getLastToken().getImage(), name.getLastToken().getOffset() ) );
}
ASTUsingDeclaration using = new ASTUsingDeclaration( scope, name.getLastToken().getImage(),
endResult.getReferencedSymbols(), isTypeName, startingOffset, startingLine, endingOffset, endingLine, references );
attachSymbolExtension( endResult, using );
return using;
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.parser.ast.IASTFactory#createASMDefinition(org.eclipse.cdt.core.parser.ast.IASTScope, java.lang.String, int, int)
*/
public IASTASMDefinition createASMDefinition(
IASTScope scope,
String assembly,
int startingOffset,
int startingLine, int endingOffset, int endingLine)
{
return new ASTASMDefinition( scopeToSymbol(scope), assembly, startingOffset, startingLine, endingOffset, endingLine);
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.parser.ast.IASTFactory#createNamespaceDefinition(org.eclipse.cdt.core.parser.ast.IASTScope, java.lang.String, int, int)
*/
public IASTNamespaceDefinition createNamespaceDefinition(
IASTScope scope,
String identifier,
int startingOffset,
int startingLine, int nameOffset, int nameEndOffset, int nameLineNumber) throws ASTSemanticException
{
IContainerSymbol pstScope = scopeToSymbol(scope);
ISymbol namespaceSymbol = null;
if( ! identifier.equals( EMPTY_STRING ) )
{
try
{
namespaceSymbol = pstScope.qualifiedLookup( identifier );
}
catch (ParserSymbolTableException e)
{
handleProblem( e.createProblemID(), identifier, nameOffset, nameEndOffset, nameLineNumber, true );
}
}
if( namespaceSymbol != null )
{
if( namespaceSymbol.getType() != TypeInfo.t_namespace )
handleProblem( IProblem.SEMANTIC_INVALID_OVERLOAD, identifier, nameOffset, nameEndOffset, nameLineNumber, true );
}
else
{
namespaceSymbol = pst.newContainerSymbol( identifier, TypeInfo.t_namespace );
if( identifier.equals( EMPTY_STRING ) )
namespaceSymbol.setContainingSymbol( pstScope );
else
{
try
{
pstScope.addSymbol( namespaceSymbol );
}
catch (ParserSymbolTableException e1)
{
// assert false : e1;
}
}
}
ASTNamespaceDefinition namespaceDef = new ASTNamespaceDefinition( namespaceSymbol, startingOffset, startingLine, nameOffset, nameEndOffset, nameLineNumber);
attachSymbolExtension( namespaceSymbol, namespaceDef, true );
return namespaceDef;
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.parser.ast.IASTFactory#createCompilationUnit()
*/
public IASTCompilationUnit createCompilationUnit()
{
ISymbol symbol = pst.getCompilationUnit();
ASTCompilationUnit compilationUnit = new ASTCompilationUnit( symbol );
attachSymbolExtension(symbol, compilationUnit, true );
return compilationUnit;
}
protected void attachSymbolExtension( IExtensibleSymbol symbol, ASTNode astNode )
{
ISymbolASTExtension symbolExtension = new ExtensibleSymbolExtension( symbol, astNode );
symbol.setASTExtension( symbolExtension );
}
protected void attachSymbolExtension(
ISymbol symbol,
ASTSymbol astSymbol, boolean asDefinition )
{
ISymbolASTExtension symbolExtension = symbol.getASTExtension();
if( symbolExtension == null )
{
if( astSymbol instanceof IASTNamespaceDefinition )
symbolExtension = new NamespaceSymbolExtension( symbol, astSymbol );
else if( astSymbol instanceof IASTFunction || astSymbol instanceof IASTMethod ||
astSymbol instanceof IASTEnumerationSpecifier ||
astSymbol instanceof IASTClassSpecifier ||
astSymbol instanceof IASTElaboratedTypeSpecifier )
{
symbolExtension = new ForewardDeclaredSymbolExtension( symbol, astSymbol );
}
else if( astSymbol instanceof IASTTemplateDeclaration ){
symbolExtension = new TemplateSymbolExtension( symbol, astSymbol );
}
else
{
symbolExtension = new StandardSymbolExtension( symbol, astSymbol );
}
symbol.setASTExtension( symbolExtension );
}
else
{
if( asDefinition )
try {
symbolExtension.addDefinition( astSymbol );
} catch (ExtensionException e) {
// assert false : ExtensionException.class;
}
}
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.parser.ast.IASTFactory#createLinkageSpecification(org.eclipse.cdt.core.parser.ast.IASTScope, java.lang.String, int)
*/
public IASTLinkageSpecification createLinkageSpecification(
IASTScope scope,
String spec,
int startingOffset, int startingLine)
{
return new ASTLinkageSpecification( scopeToSymbol( scope ), spec, startingOffset, startingLine );
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.parser.ast.IASTFactory#createClassSpecifier(org.eclipse.cdt.core.parser.ast.IASTScope, java.lang.String, org.eclipse.cdt.core.parser.ast.ASTClassKind, org.eclipse.cdt.core.parser.ast.IASTClassSpecifier.ClassNameType, org.eclipse.cdt.core.parser.ast.ASTAccessVisibility, org.eclipse.cdt.core.parser.ast.IASTTemplate, int, int)
*/
public IASTClassSpecifier createClassSpecifier(
IASTScope scope,
ITokenDuple name,
ASTClassKind kind,
ClassNameType type,
ASTAccessVisibility access,
int startingOffset,
int startingLine, int nameOffset, int nameEndOffset, int nameLine) throws ASTSemanticException
{
IContainerSymbol currentScopeSymbol = scopeToSymbol(scope);
TypeInfo.eType pstType = classKindToTypeInfo(kind);
List references = new ArrayList();
String newSymbolName = EMPTY_STRING;
List templateIdArgList = null;
boolean isTemplateId = false;
if( name != null ){
IToken nameToken = null;
if( name.getSegmentCount() != 1 ) // qualified name
{
ITokenDuple containerSymbolName = name.getLeadingSegments();
ISymbol temp = lookupQualifiedName( currentScopeSymbol, containerSymbolName, references, true);
if( temp instanceof IDeferredTemplateInstance )
currentScopeSymbol = ((IDeferredTemplateInstance)temp).getTemplate().getTemplatedSymbol();
else
currentScopeSymbol = (IContainerSymbol) temp;
if( currentScopeSymbol == null )
handleProblem( IProblem.SEMANTIC_NAME_NOT_FOUND, containerSymbolName.toString(), containerSymbolName.getFirstToken().getOffset(), containerSymbolName.getLastToken().getEndOffset(), containerSymbolName.getLastToken().getLineNumber(), true );
nameToken = name.getLastSegment().getFirstToken();
} else {
nameToken = name.getFirstToken();
}
//template-id
List [] array = name.getTemplateIdArgLists();
if( array != null ){
templateIdArgList = array[ array.length - 1 ];
isTemplateId = (templateIdArgList != null);
}
newSymbolName = nameToken.getImage();
}
ISymbol classSymbol = null;
if( !newSymbolName.equals(EMPTY_STRING) && !isTemplateId ){
try
{
classSymbol = currentScopeSymbol.lookupMemberForDefinition(newSymbolName);
}
catch (ParserSymbolTableException e)
{
handleProblem(IProblem.SEMANTIC_UNIQUE_NAME_PREDEFINED, name.toString(), nameOffset, nameEndOffset, nameLine, true);
}
if( classSymbol != null && ! classSymbol.isForwardDeclaration() )
handleProblem( IProblem.SEMANTIC_UNIQUE_NAME_PREDEFINED, newSymbolName, nameOffset, nameEndOffset, nameLine, true );
if( classSymbol != null && classSymbol.getType() != pstType )
{
boolean isError = true;
if( classSymbol.isType( TypeInfo.t_class, TypeInfo.t_union ) )
{
if ( ( pstType == TypeInfo.t_class || pstType == TypeInfo.t_struct || pstType == TypeInfo.t_union ) )
isError = false;
}
handleProblem( IProblem.SEMANTIC_INVALID_OVERLOAD, newSymbolName, nameOffset, nameEndOffset, nameLine, isError );
}
}
IDerivableContainerSymbol newSymbol = pst.newDerivableContainerSymbol( newSymbolName, pstType );
if( classSymbol != null )
classSymbol.setTypeSymbol( newSymbol );
List args = null;
if( isTemplateId ){
args = getTemplateArgList( templateIdArgList );
}
try
{
if( !isTemplateId )
currentScopeSymbol.addSymbol( newSymbol );
else
currentScopeSymbol.addTemplateId( newSymbol, args );
}
catch (ParserSymbolTableException e2)
{
handleProblem( e2.createProblemID(), newSymbolName );
}
if( name != null && name.getTemplateIdArgLists() != null )
{
for( int i = 0; i < name.getTemplateIdArgLists().length; ++i )
addTemplateIdReferences( references, name.getTemplateIdArgLists()[i]);
name.freeReferences( cache );
}
ASTClassSpecifier classSpecifier = new ASTClassSpecifier( newSymbol, kind, type, access, startingOffset, startingLine, nameOffset, nameEndOffset, nameLine, references );
attachSymbolExtension(newSymbol, classSpecifier, true );
return classSpecifier;
}
private List getTemplateArgList( List args ){
if( args == null )
return null;
List list = new LinkedList();
Iterator iter = args.iterator();
ASTExpression exp;
while( iter.hasNext() )
{
exp = (ASTExpression) iter.next();
TypeInfo info = exp.getResultType().getResult();
list.add( info );
}
return list;
}
protected void handleProblem( int id, String attribute ) throws ASTSemanticException
{
handleProblem( null, id, attribute, -1, -1, -1, true ); //TODO make this right
}
protected void handleProblem( IASTScope scope, int id, String attribute ) throws ASTSemanticException
{
handleProblem( scope, id, attribute, -1, -1, -1, true );
}
protected void handleProblem( int id, String attribute, int startOffset, int endOffset, int lineNumber, boolean isError) throws ASTSemanticException {
handleProblem( null, id, attribute, startOffset, endOffset, lineNumber, isError );
}
/**
* @param id
* @param attribute
* @param startOffset
* @param endOffset
* @param lineNumber
* @param isError TODO
* @throws ASTSemanticException
*/
protected void handleProblem( IASTScope scope, int id, String attribute, int startOffset, int endOffset, int lineNumber, boolean isError) throws ASTSemanticException {
IProblem p = problemFactory.createProblem( id,
startOffset, endOffset, lineNumber, fileProvider.getCurrentFilename(), attribute, !isError, isError );
TraceUtil.outputTrace(logService, "CompleteParseASTFactory - IProblem : ", p, null, null, null ); //$NON-NLS-1$
if( shouldThrowException( scope, id, !isError ) )
throw new ASTSemanticException(p);
}
protected boolean shouldThrowException( IASTScope scope, int id, boolean isWarning ){
if( isWarning ) return false;
if( scope != null ){
IContainerSymbol symbol = scopeToSymbol( scope );
if( symbol.isTemplateMember() ){
if( id == IProblem.SEMANTIC_INVALID_CONVERSION_TYPE ||
id == IProblem.SEMANTIC_INVALID_TYPE )
{
return false;
}
}
}
return true;
}
protected TypeInfo.eType classKindToTypeInfo(ASTClassKind kind)
{
TypeInfo.eType pstType = null;
if( kind == ASTClassKind.CLASS )
pstType = TypeInfo.t_class;
else if( kind == ASTClassKind.STRUCT )
pstType = TypeInfo.t_struct;
else if( kind == ASTClassKind.UNION )
pstType = TypeInfo.t_union;
else if( kind == ASTClassKind.ENUM )
pstType = TypeInfo.t_enumeration;
// else
// assert false : kind ;
return pstType;
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.parser.ast.IASTFactory#addBaseSpecifier(org.eclipse.cdt.core.parser.ast.IASTClassSpecifier, boolean, org.eclipse.cdt.core.parser.ast.ASTAccessVisibility, java.lang.String)
*/
public void addBaseSpecifier(
IASTClassSpecifier astClassSpec,
boolean isVirtual,
ASTAccessVisibility visibility,
ITokenDuple parentClassName) throws ASTSemanticException
{
IDerivableContainerSymbol classSymbol = (IDerivableContainerSymbol)scopeToSymbol( astClassSpec);
Iterator iterator = null;
List references = new ArrayList();
if( parentClassName != null )
{
iterator = parentClassName.iterator();
if( !iterator.hasNext() )
handleProblem( IProblem.SEMANTIC_NAME_NOT_PROVIDED, null );
}
else
handleProblem( IProblem.SEMANTIC_NAME_NOT_PROVIDED, null );
//Its possible that the parent is not an IContainerSymbol if its a template parameter or some kinds of template instances
ISymbol symbol = lookupQualifiedName( classSymbol, parentClassName, references, true );
if( symbol instanceof ITemplateSymbol )
handleProblem( IProblem.SEMANTIC_INVALID_TEMPLATE_ARGUMENT, parentClassName.toString(), parentClassName.getStartOffset(), parentClassName.getEndOffset(), parentClassName.getLineNumber(), true);
List [] templateArgumentLists = parentClassName.getTemplateIdArgLists();
if( templateArgumentLists != null )
{
for( int i = 0; i < templateArgumentLists.length; ++i )
addTemplateIdReferences( references, templateArgumentLists[i]);
}
parentClassName.freeReferences(cache);
classSymbol.addParent( symbol, isVirtual, visibility, parentClassName.getFirstToken().getOffset(), references );
}
/**
* @param symbol
* @param referenceElementName
* @return
*/
protected IASTReference createReference(ISymbol symbol, String referenceElementName, int offset ) throws ASTSemanticException
{
if( mode != ParserMode.COMPLETE_PARSE )
return null;
//referenced symbol doesn't have an attached AST node, could happen say for the copy constructor added
//by the symbol table.
if( symbol.getASTExtension() == null )
return null;
Iterator i = symbol.getASTExtension().getAllDefinitions();
ASTSymbol declaration = i.hasNext() ? (ASTSymbol) i.next() : null;
ASTSymbol definition = i.hasNext() ? (ASTSymbol) i.next() : null;
// assert (symbol != null ) : "createReference cannot be called on null symbol ";
if( symbol.getTypeInfo().checkBit( TypeInfo.isTypedef ) ||
symbol.getASTExtension().getPrimaryDeclaration() instanceof IASTTypedefDeclaration )
return cache.getReference( offset, declaration);
else if( symbol.getType() == TypeInfo.t_namespace )
return cache.getReference( offset, declaration);
else if( symbol.getType() == TypeInfo.t_class ||
symbol.getType() == TypeInfo.t_struct ||
symbol.getType() == TypeInfo.t_union )
return cache.getReference( offset, (ISourceElementCallbackDelegate)symbol.getASTExtension().getPrimaryDeclaration() );
else if( symbol.getType() == TypeInfo.t_enumeration )
return cache.getReference( offset, (IASTEnumerationSpecifier)symbol.getASTExtension().getPrimaryDeclaration() );
else if( symbol.getType() == TypeInfo.t_enumerator )
return cache.getReference( offset, declaration );
else if(( symbol.getType() == TypeInfo.t_function ) || (symbol.getType() == TypeInfo.t_constructor))
{
ASTNode referenced = (definition != null) ? definition : declaration;
if( referenced instanceof IASTMethod )
return cache.getReference( offset, (IASTMethod)referenced );
return cache.getReference( offset, (IASTFunction)referenced );
}
else if( ( symbol.getType() == TypeInfo.t_type ) ||
( symbol.getType() == TypeInfo.t_bool )||
( symbol.getType() == TypeInfo.t_char ) ||
( symbol.getType() == TypeInfo.t_wchar_t )||
( symbol.getType() == TypeInfo.t_int ) ||
( symbol.getType() == TypeInfo.t_float )||
( symbol.getType() == TypeInfo.t_double ) ||
( symbol.getType() == TypeInfo.t_void ) ||
( symbol.getType() == TypeInfo.t__Bool) ||
( symbol.getType() == TypeInfo.t_templateParameter ) )
{
if( symbol.getContainingSymbol().getType() == TypeInfo.t_class ||
symbol.getContainingSymbol().getType() == TypeInfo.t_struct ||
symbol.getContainingSymbol().getType() == TypeInfo.t_union )
{
return cache.getReference( offset, (definition != null ? definition : declaration ));
}
else if( ( symbol.getContainingSymbol().getType() == TypeInfo.t_function ||
symbol.getContainingSymbol().getType() == TypeInfo.t_constructor ) &&
symbol.getContainingSymbol() instanceof IParameterizedSymbol &&
((IParameterizedSymbol)symbol.getContainingSymbol()).getParameterList() != null &&
((IParameterizedSymbol)symbol.getContainingSymbol()).getParameterList().contains( symbol ) )
{
return cache.getReference( offset, declaration );
}
else
{
ASTNode s = (definition != null) ? definition : declaration;
if(s instanceof IASTVariable)
return cache.getReference( offset, (IASTVariable)s);
else if (s instanceof IASTParameterDeclaration)
return cache.getReference( offset, (IASTParameterDeclaration)s);
else if (s instanceof IASTTemplateParameter )
return cache.getReference( offset, (IASTTemplateParameter)s );
}
}
// assert false : "Unreachable code : createReference()";
return null;
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.parser.ast.IASTFactory#createEnumerationSpecifier(org.eclipse.cdt.core.parser.ast.IASTScope, java.lang.String, int, int)
*/
public IASTEnumerationSpecifier createEnumerationSpecifier(
IASTScope scope,
String name,
int startingOffset,
int startingLine, int nameOffset, int nameEndOffset, int nameLine) throws ASTSemanticException
{
IContainerSymbol containerSymbol = scopeToSymbol(scope);
TypeInfo.eType pstType = TypeInfo.t_enumeration;
IDerivableContainerSymbol classSymbol = pst.newDerivableContainerSymbol( name, pstType );
try
{
containerSymbol.addSymbol( classSymbol );
}
catch (ParserSymbolTableException e)
{
handleProblem( e.createProblemID(), name );
}
ASTEnumerationSpecifier enumSpecifier = new ASTEnumerationSpecifier( classSymbol, startingOffset, startingLine, nameOffset, nameEndOffset, nameLine );
attachSymbolExtension(classSymbol, enumSpecifier, true );
return enumSpecifier;
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.parser.ast.IASTFactory#addEnumerator(org.eclipse.cdt.core.parser.ast.IASTEnumerationSpecifier, java.lang.String, int, int, org.eclipse.cdt.core.parser.ast.IASTExpression)
*/
public IASTEnumerator addEnumerator(
IASTEnumerationSpecifier enumeration,
String name,
int startingOffset,
int startingLine,
int nameOffset, int nameEndOffset, int nameLine, int endingOffset, int endLine, IASTExpression initialValue) throws ASTSemanticException
{
IContainerSymbol enumerationSymbol = (IContainerSymbol)((ISymbolOwner)enumeration).getSymbol();
ISymbol enumeratorSymbol = pst.newSymbol( name, TypeInfo.t_enumerator );
try
{
enumerationSymbol.addSymbol( enumeratorSymbol );
}
catch (ParserSymbolTableException e1)
{
if( e1.reason == ParserSymbolTableException.r_InvalidOverload )
handleProblem( IProblem.SEMANTIC_INVALID_OVERLOAD, name, startingOffset, endingOffset, startingLine, true );
// assert false : e1;
}
ASTEnumerator enumerator = new ASTEnumerator( enumeratorSymbol, enumeration, startingOffset, startingLine, nameOffset, nameEndOffset, nameLine, endingOffset, endLine, initialValue );
((ASTEnumerationSpecifier)enumeration).addEnumerator( enumerator );
attachSymbolExtension( enumeratorSymbol, enumerator, true );
return enumerator;
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.parser.ast.IASTFactory#createExpression(org.eclipse.cdt.core.parser.ast.IASTExpression.Kind, org.eclipse.cdt.core.parser.ast.IASTExpression, org.eclipse.cdt.core.parser.ast.IASTExpression, org.eclipse.cdt.core.parser.ast.IASTExpression, java.lang.String, java.lang.String, java.lang.String, org.eclipse.cdt.core.parser.ast.IASTExpression.IASTNewExpressionDescriptor)
*/
public IASTExpression createExpression(
IASTScope scope,
Kind kind,
IASTExpression lhs,
IASTExpression rhs,
IASTExpression thirdExpression,
IASTTypeId typeId,
ITokenDuple idExpression, String literal, IASTNewExpressionDescriptor newDescriptor) throws ASTSemanticException
{
if( idExpression != null )
{
TraceUtil.outputTrace(
logService,
"Entering createExpression with Kind=", //$NON-NLS-1$
null,
kind.getKindName(),
" idexpression=", //$NON-NLS-1$
idExpression.toString()
);
}
else if( literal != null && !literal.equals( EMPTY_STRING ))
{
TraceUtil.outputTrace(
logService,
"Entering createExpression with Kind=", //$NON-NLS-1$
null,
kind.getKindName(),
" literal=", //$NON-NLS-1$
literal
);
}
List references = new ArrayList();
ISymbol symbol = getExpressionSymbol(scope, kind, lhs, rhs, idExpression, references );
// Try to figure out the result that this expression evaluates to
ExpressionResult expressionResult = getExpressionResultType(scope, kind, lhs, rhs, thirdExpression, typeId, literal, symbol);
if( newDescriptor != null ){
createConstructorReference( newDescriptor, typeId, references );
}
if( symbol == null )
purgeBadReferences( kind, rhs );
// expression results could be empty, but should not be null
// assert expressionResult != null : expressionResult; //throw new ASTSemanticException();
// create the ASTExpression
ASTExpression expression = null;
if( extension.overrideCreateExpressionMethod() )
expression = (ASTExpression) extension.createExpression( scope, kind, lhs, rhs, thirdExpression, typeId, idExpression, literal, newDescriptor, references );
else
expression = ExpressionFactory.createExpression( kind, lhs, rhs, thirdExpression, typeId, idExpression, literal, newDescriptor, references );
// Assign the result to the created expression
expression.setResultType (expressionResult);
return expression;
}
private void createConstructorReference( IASTNewExpressionDescriptor descriptor, IASTTypeId typeId, List references ){
ISymbol symbol = null;
try {
symbol = typeId.getTypeSymbol();
if( symbol.isType( TypeInfo.t_type ) )
symbol = symbol.getTypeSymbol();
} catch (ASTNotImplementedException e) {
return;
}
if( symbol == null || !( symbol instanceof IDerivableContainerSymbol ) )
return;
Iterator i = descriptor.getNewInitializerExpressions();
ASTExpression exp = ( i.hasNext() )? (ASTExpression) i.next() : null;
ITokenDuple duple = ((ASTTypeId)typeId).getTokenDuple().getLastSegment();
if( createConstructorReference( symbol, exp, duple, references ) ){
//if we have a constructor reference, get rid of the class reference.
i = ((ASTTypeId)typeId).getReferences().iterator();
while( i.hasNext() )
{
ReferenceCache.ASTReference ref = (ReferenceCache.ASTReference) i.next();
if( ref.getName().equals( duple.toString() ) &&
ref.getOffset() == duple.getStartOffset() )
{
cache.returnReference( ref );
i.remove();
}
}
}
}
private boolean createConstructorReference( ISymbol classSymbol, ASTExpression expressionList, ITokenDuple duple, List references ){
if( classSymbol != null && classSymbol.getTypeInfo().checkBit( TypeInfo.isTypedef ) ){
TypeInfoProvider provider = pst.getTypeInfoProvider();
TypeInfo info = classSymbol.getTypeInfo().getFinalType( provider );
classSymbol = info.getTypeSymbol();
provider.returnTypeInfo( info );
}
if( classSymbol == null || ! (classSymbol instanceof IDerivableContainerSymbol ) ){
return false;
}
List parameters = new LinkedList();
while( expressionList != null ){
parameters.add( expressionList.getResultType().getResult() );
expressionList = (ASTExpression) expressionList.getRHSExpression();
}
IParameterizedSymbol constructor = null;
try {
constructor = ((IDerivableContainerSymbol)classSymbol).lookupConstructor( parameters );
} catch (ParserSymbolTableException e1) {
return false;
}
if( constructor != null ){
IASTReference reference = null;
try {
reference = createReference( constructor, duple.toString(), duple.getStartOffset() );
} catch (ASTSemanticException e2) {
return false;
}
if( reference != null ){
addReference( references, reference );
return true;
}
}
return false;
}
/**
* @param kind
* @param rhs
*/
private void purgeBadReferences(Kind kind, IASTExpression rhs) {
if( rhs == null ) return;
if( kind == Kind.POSTFIX_ARROW_IDEXPRESSION || kind == Kind.POSTFIX_ARROW_TEMPL_IDEXP ||
kind == Kind.POSTFIX_DOT_IDEXPRESSION || kind == Kind.POSTFIX_DOT_TEMPL_IDEXPRESS )
{
ASTExpression astExpression = (ASTExpression) rhs;
Iterator refs = astExpression.getReferences().iterator();
String idExpression = astExpression.getIdExpression();
if( !idExpression.equals( "")) //$NON-NLS-1$
{
while( refs.hasNext() )
{
IASTReference r = (IASTReference) refs.next();
if( r.getName().equals( idExpression ) )
{
refs.remove();
cache.returnReference(r);
}
}
}
}
}
/*
* Try and dereference the symbol in the expression
*/
private ISymbol getExpressionSymbol(
IASTScope scope,
Kind kind,
IASTExpression lhs,
IASTExpression rhs,
ITokenDuple idExpression,
List references )throws ASTSemanticException
{
ISymbol symbol = null;
IContainerSymbol startingScope = scopeToSymbol( scope );
//If the expression has an id, look up id and add it to references
if( idExpression != null )
symbol = lookupQualifiedName( startingScope, idExpression, references, false );
// If the expression is lookup symbol if it is in the scope of a type after a "." or an "->"
IContainerSymbol searchScope = getSearchScope(kind, lhs, startingScope);
if ( searchScope != null && !searchScope.equals(startingScope))
symbol = lookupQualifiedName(searchScope, ((ASTIdExpression)rhs).getIdExpressionTokenDuple(), references, false, LookupType.QUALIFIED );
// get symbol if it is the "this" pointer
// go up the scope until you hit a class
if (kind == IASTExpression.Kind.PRIMARY_THIS){
try{
symbol = startingScope.lookup("this"); //$NON-NLS-1$
}catch (ParserSymbolTableException e){
handleProblem( e.createProblemID(), "this"); //$NON-NLS-1$
}
}
// lookup symbol if it is a function call
if (kind == IASTExpression.Kind.POSTFIX_FUNCTIONCALL){
ITokenDuple functionId = getFunctionId(lhs);
IContainerSymbol functionScope = getSearchScope(lhs.getExpressionKind(), lhs.getLHSExpression(), startingScope);
if( functionScope == null )
return null;
ExpressionResult expResult = ((ASTExpression)rhs).getResultType();
List parameters = null;
if(expResult instanceof ExpressionResultList){
ExpressionResultList expResultList = (ExpressionResultList) expResult;
parameters = expResultList.getResultList();
}else {
parameters = new ArrayList();
parameters.add(expResult.getResult());
}
if( functionScope.equals( startingScope ) )
symbol = lookupQualifiedName(functionScope, functionId, TypeInfo.t_function, parameters, references, false);
else
symbol = lookupQualifiedName(functionScope, functionId, TypeInfo.t_function, parameters, references, false, LookupType.QUALIFIED );
}
return symbol;
}
/*
* Returns the function ID token
*/
private ITokenDuple getFunctionId (IASTExpression expression){
if(expression.getExpressionKind().isPostfixMemberReference() && expression.getRHSExpression() instanceof ASTIdExpression )
return ((ASTIdExpression)expression.getRHSExpression()).getIdExpressionTokenDuple();
else if( expression instanceof ASTIdExpression )
return ((ASTIdExpression)expression).getIdExpressionTokenDuple();
return null;
}
private IContainerSymbol getSearchScope (Kind kind, IASTExpression lhs, IContainerSymbol startingScope) throws ASTSemanticException{
if( kind.isPostfixMemberReference() )
{
TypeInfo lhsInfo = ((ASTExpression)lhs).getResultType().getResult();
if(lhsInfo != null){
TypeInfoProvider provider = pst.getTypeInfoProvider();
TypeInfo info = null;
try{
info = lhsInfo.getFinalType( provider );
} catch ( ParserSymbolTableError e ){
return null;
}
ISymbol containingScope = info.getTypeSymbol();
provider.returnTypeInfo( info );
// assert containingScope != null : "Malformed Expression";
if( containingScope instanceof IDeferredTemplateInstance )
return ((IDeferredTemplateInstance) containingScope).getTemplate().getTemplatedSymbol();
return ( containingScope instanceof IContainerSymbol ) ? (IContainerSymbol)containingScope : null;
}
// assert lhsInfo != null : "Malformed Expression";
return null;
}
return startingScope;
}
/*
* Conditional Expression conversion
*/
protected TypeInfo conditionalExpressionConversions(TypeInfo second, TypeInfo third){
TypeInfo info = new TypeInfo();
if(second.equals(third)){
info = second;
return info;
}
if((second.getType() == TypeInfo.t_void) && (third.getType() != TypeInfo.t_void)){
info = third;
return info;
}
if((second.getType() != TypeInfo.t_void) && (third.getType() == TypeInfo.t_void)){
info = second;
return info;
}
if((second.getType() == TypeInfo.t_void) && (third.getType() == TypeInfo.t_void)){
info = second;
return info;
}
try{
info = pst.getConditionalOperand(second, third);
return info;
} catch(ParserSymbolTableException e){
// empty info
return info;
}
}
/*
* Apply the usual arithmetic conversions to find out the result of an expression
* that has a lhs and a rhs as indicated in the specs (section 5.Expressions, page 64)
*/
protected TypeInfo usualArithmeticConversions( IASTScope scope, TypeInfo lhs, TypeInfo rhs) throws ASTSemanticException{
// if you have a variable of type basic type, then we need to go to the basic type first
while( (lhs.getType() == TypeInfo.t_type) && (lhs.getTypeSymbol() != null)){
lhs = lhs.getTypeSymbol().getTypeInfo();
}
while( (rhs.getType() == TypeInfo.t_type) && (rhs.getTypeSymbol() != null)){
rhs = rhs.getTypeSymbol().getTypeInfo();
}
if( !lhs.isType(TypeInfo.t__Bool, TypeInfo.t_enumerator ) &&
!rhs.isType(TypeInfo.t__Bool, TypeInfo.t_enumerator ) )
{
handleProblem( scope, IProblem.SEMANTIC_INVALID_CONVERSION_TYPE, null );
}
TypeInfo info = new TypeInfo();
if(
( lhs.checkBit(TypeInfo.isLong) && lhs.getType() == TypeInfo.t_double)
|| ( rhs.checkBit(TypeInfo.isLong) && rhs.getType() == TypeInfo.t_double)
){
info.setType(TypeInfo.t_double);
info.setBit(true, TypeInfo.isLong);
return info;
}
else if(
( lhs.getType() == TypeInfo.t_double )
|| ( rhs.getType() == TypeInfo.t_double )
){
info.setType(TypeInfo.t_double);
return info;
}
else if (
( lhs.getType() == TypeInfo.t_float )
|| ( rhs.getType() == TypeInfo.t_float )
){
info.setType(TypeInfo.t_float);
return info;
} else {
// perform intergral promotions (Specs section 4.5)
info.setType(TypeInfo.t_int);
}
if(
( lhs.checkBit(TypeInfo.isUnsigned) && lhs.checkBit(TypeInfo.isLong))
|| ( rhs.checkBit(TypeInfo.isUnsigned) && rhs.checkBit(TypeInfo.isLong))
){
info.setBit(true, TypeInfo.isUnsigned);
info.setBit(true, TypeInfo.isLong);
return info;
}
else if(
( lhs.checkBit(TypeInfo.isUnsigned) && rhs.checkBit(TypeInfo.isLong) )
|| ( rhs.checkBit(TypeInfo.isUnsigned) && lhs.checkBit(TypeInfo.isLong) )
){
info.setBit(true, TypeInfo.isUnsigned);
info.setBit(true, TypeInfo.isLong);
return info;
}
else if (
( lhs.checkBit(TypeInfo.isLong))
|| ( rhs.checkBit(TypeInfo.isLong))
){
info.setBit(true, TypeInfo.isLong);
return info;
}
else if (
( lhs.checkBit(TypeInfo.isUnsigned) )
|| ( rhs.checkBit(TypeInfo.isUnsigned) )
){
info.setBit(true, TypeInfo.isUnsigned);
return info;
} else {
// it should be both = int
return info;
}
}
private TypeInfo addToInfo(ASTExpression exp, boolean flag, int mask)
{
// assert exp != null : exp;
TypeInfo info = exp.getResultType().getResult();
info.setBit(flag, mask);
return info;
}
protected ExpressionResult getExpressionResultType(
IASTScope scope,
Kind kind, IASTExpression lhs,
IASTExpression rhs,
IASTExpression thirdExpression,
IASTTypeId typeId,
String literal,
ISymbol symbol) throws ASTSemanticException{
TypeInfo info = new TypeInfo();
if( extension.canHandleExpressionKind( kind ))
{
extension.getExpressionResultType( kind, lhs, rhs, typeId );
return new ExpressionResult( info );
}
ExpressionResult result = null;
if( literal != null && !literal.equals(EMPTY_STRING) && kind.isLiteral() ){
info.setDefault( literal );
}
// types that resolve to void
if ((kind == IASTExpression.Kind.PRIMARY_EMPTY)
|| (kind == IASTExpression.Kind.THROWEXPRESSION)
|| (kind == IASTExpression.Kind.POSTFIX_DOT_DESTRUCTOR)
|| (kind == IASTExpression.Kind.POSTFIX_ARROW_DESTRUCTOR)
|| (kind == IASTExpression.Kind.DELETE_CASTEXPRESSION)
|| (kind == IASTExpression.Kind.DELETE_VECTORCASTEXPRESSION)
){
info.setType(TypeInfo.t_void);
result = new ExpressionResult(info);
return result;
}
// types that resolve to int
if ((kind == IASTExpression.Kind.PRIMARY_INTEGER_LITERAL)
|| (kind == IASTExpression.Kind.POSTFIX_SIMPLETYPE_INT)
){
info.setType(TypeInfo.t_int);
result = new ExpressionResult(info);
return result;
}
// size of is always unsigned int
if ((kind == IASTExpression.Kind.UNARY_SIZEOF_TYPEID)
|| (kind == IASTExpression.Kind.UNARY_SIZEOF_UNARYEXPRESSION)
){
info.setType(TypeInfo.t_int);
info.setBit(true, TypeInfo.isUnsigned);
result = new ExpressionResult(info);
return result;
}
// types that resolve to char
if( (kind == IASTExpression.Kind.PRIMARY_CHAR_LITERAL)
|| (kind == IASTExpression.Kind.POSTFIX_SIMPLETYPE_CHAR)){
info.setType(TypeInfo.t_char);
// check that this is really only one literal
if(literal.length() > 1){
// this is a string
info.addPtrOperator(new TypeInfo.PtrOp(TypeInfo.PtrOp.t_pointer));
}
result = new ExpressionResult(info);
return result;
}
// types that resolve to string
if (kind == IASTExpression.Kind.PRIMARY_STRING_LITERAL){
info.setType(TypeInfo.t_char);
info.addPtrOperator(new TypeInfo.PtrOp(TypeInfo.PtrOp.t_pointer));
result = new ExpressionResult(info);
return result;
}
// types that resolve to float
if( (kind == IASTExpression.Kind.PRIMARY_FLOAT_LITERAL)
|| (kind == IASTExpression.Kind.POSTFIX_SIMPLETYPE_FLOAT)){
info.setType(TypeInfo.t_float);
result = new ExpressionResult(info);
return result;
}
// types that resolve to double
if( kind == IASTExpression.Kind.POSTFIX_SIMPLETYPE_DOUBLE){
info.setType(TypeInfo.t_double);
result = new ExpressionResult(info);
return result;
}
// types that resolve to wchar
if(kind == IASTExpression.Kind.POSTFIX_SIMPLETYPE_WCHART){
info.setType(TypeInfo.t_wchar_t);
result = new ExpressionResult(info);
return result;
}
// types that resolve to bool
if( (kind == IASTExpression.Kind.PRIMARY_BOOLEAN_LITERAL)
|| (kind == IASTExpression.Kind.POSTFIX_SIMPLETYPE_BOOL)
|| (kind == IASTExpression.Kind.RELATIONAL_GREATERTHAN)
|| (kind == IASTExpression.Kind.RELATIONAL_GREATERTHANEQUALTO)
|| (kind == IASTExpression.Kind.RELATIONAL_LESSTHAN)
|| (kind == IASTExpression.Kind.RELATIONAL_LESSTHANEQUALTO)
|| (kind == IASTExpression.Kind.EQUALITY_EQUALS)
|| (kind == IASTExpression.Kind.EQUALITY_NOTEQUALS)
|| (kind == IASTExpression.Kind.LOGICALANDEXPRESSION)
|| (kind == IASTExpression.Kind.LOGICALOREXPRESSION)
)
{
info.setType(TypeInfo.t_bool);
result = new ExpressionResult(info);
return result;
}
// short added to a type
if (kind == IASTExpression.Kind.POSTFIX_SIMPLETYPE_SHORT ){
info = addToInfo((ASTExpression)lhs, true, TypeInfo.isShort);
result = new ExpressionResult(info);
return result;
}
// long added to a type
if (kind == IASTExpression.Kind.POSTFIX_SIMPLETYPE_LONG ){
info = addToInfo((ASTExpression)lhs, true, TypeInfo.isLong);
result = new ExpressionResult(info);
return result;
}
// signed added to a type
if (kind == IASTExpression.Kind.POSTFIX_SIMPLETYPE_SIGNED ){
info = addToInfo((ASTExpression)lhs, false, TypeInfo.isUnsigned);
result = new ExpressionResult(info);
return result;
}
// unsigned added to a type
if (kind == IASTExpression.Kind.POSTFIX_SIMPLETYPE_UNSIGNED ){
info = addToInfo((ASTExpression)lhs, true, TypeInfo.isUnsigned);
result = new ExpressionResult(info);
return result;
}
// Id expressions resolve to t_type, symbol already looked up
if( kind == IASTExpression.Kind.ID_EXPRESSION )
{
info.setType(TypeInfo.t_type);
info.setTypeSymbol(symbol);
result = new ExpressionResult(info);
if (symbol == null)
result.setFailedToDereference(true);
return result;
}
// an ampersand implies a pointer operation of type reference
if (kind == IASTExpression.Kind.UNARY_AMPSND_CASTEXPRESSION){
ASTExpression left =(ASTExpression)lhs;
if(left == null)
handleProblem( scope, IProblem.SEMANTIC_MALFORMED_EXPRESSION, null );
info = left.getResultType().getResult();
- if ((info != null) && (info.getTypeSymbol() != null)){
+ if (info != null){
info.addOperatorExpression( TypeInfo.OperatorExpression.addressof );
+ info = info.getFinalType( null );
} else
handleProblem( scope, IProblem.SEMANTIC_MALFORMED_EXPRESSION, null );
result = new ExpressionResult(info);
return result;
}
// a star implies a pointer operation of type pointer
if (kind == IASTExpression.Kind.UNARY_STAR_CASTEXPRESSION){
ASTExpression left =(ASTExpression)lhs;
if(left == null)
handleProblem( scope, IProblem.SEMANTIC_MALFORMED_EXPRESSION, null );
info = left.getResultType().getResult();
- if ((info != null)&& (info.getTypeSymbol() != null)){
+ if (info != null){
info.addOperatorExpression( TypeInfo.OperatorExpression.indirection );
+ info = info.getFinalType( null );
}else
handleProblem( scope, IProblem.SEMANTIC_MALFORMED_EXPRESSION, null );
result = new ExpressionResult(info);
return result;
}
// subscript
if (kind == IASTExpression.Kind.POSTFIX_SUBSCRIPT){
ASTExpression left =(ASTExpression)lhs;
if(left == null)
handleProblem( scope, IProblem.SEMANTIC_MALFORMED_EXPRESSION, null );
info = left.getResultType().getResult();
if ((info != null))
{
info.addOperatorExpression( TypeInfo.OperatorExpression.subscript );
info = info.getFinalType( null );
}else {
handleProblem( scope, IProblem.SEMANTIC_MALFORMED_EXPRESSION, null );
}
result = new ExpressionResult(info);
return result;
}
// the dot and the arrow resolves to the type of the member
if ((kind == IASTExpression.Kind.POSTFIX_DOT_IDEXPRESSION)
|| (kind == IASTExpression.Kind.POSTFIX_ARROW_IDEXPRESSION)
|| (kind == IASTExpression.Kind.POSTFIX_DOT_TEMPL_IDEXPRESS)
|| (kind == IASTExpression.Kind.POSTFIX_ARROW_TEMPL_IDEXP)
){
if(symbol != null){
info = new TypeInfo(symbol.getTypeInfo());
}
result = new ExpressionResult(info);
return result;
}
// the dot* and the arrow* are the same as dot/arrow + unary star
if ((kind == IASTExpression.Kind.PM_DOTSTAR)
|| (kind == IASTExpression.Kind.PM_ARROWSTAR)
){
ASTExpression right =(ASTExpression)rhs;
if (right == null)
handleProblem( scope, IProblem.SEMANTIC_MALFORMED_EXPRESSION, null );
info = right.getResultType().getResult();
if ((info != null) && (symbol != null)){
info.addOperatorExpression( TypeInfo.OperatorExpression.indirection );
info.setTypeSymbol(symbol);
} else
handleProblem( scope, IProblem.SEMANTIC_MALFORMED_EXPRESSION, null );
result = new ExpressionResult(info);
return result;
}
// this
if (kind == IASTExpression.Kind.PRIMARY_THIS){
if(symbol != null)
{
info.setType(TypeInfo.t_type);
info.setTypeSymbol(symbol);
} else
handleProblem( scope, IProblem.SEMANTIC_MALFORMED_EXPRESSION, null );
result = new ExpressionResult(info);
return result;
}
// conditional
if (kind == IASTExpression.Kind.CONDITIONALEXPRESSION){
ASTExpression right = (ASTExpression)rhs;
ASTExpression third = (ASTExpression)thirdExpression;
if((right != null ) && (third != null)){
TypeInfo rightType =right.getResultType().getResult();
TypeInfo thirdType =third.getResultType().getResult();
if((rightType != null) && (thirdType != null)){
info = conditionalExpressionConversions(rightType, thirdType);
} else
handleProblem( scope, IProblem.SEMANTIC_MALFORMED_EXPRESSION, null );
} else
handleProblem( scope, IProblem.SEMANTIC_MALFORMED_EXPRESSION, null );
result = new ExpressionResult(info);
return result;
}
// new
if( ( kind == IASTExpression.Kind.NEW_TYPEID )
|| ( kind == IASTExpression.Kind.NEW_NEWTYPEID ) )
{
try
{
info = typeId.getTypeSymbol().getTypeInfo();
info.addPtrOperator( new TypeInfo.PtrOp(TypeInfo.PtrOp.t_pointer));
}
catch (ASTNotImplementedException e)
{
// will never happen
}
result = new ExpressionResult(info);
return result;
}
// types that use the usual arithmetic conversions
if((kind == IASTExpression.Kind.MULTIPLICATIVE_MULTIPLY)
|| (kind == IASTExpression.Kind.MULTIPLICATIVE_DIVIDE)
|| (kind == IASTExpression.Kind.MULTIPLICATIVE_MODULUS)
|| (kind == IASTExpression.Kind.ADDITIVE_PLUS)
|| (kind == IASTExpression.Kind.ADDITIVE_MINUS)
|| (kind == IASTExpression.Kind.ANDEXPRESSION)
|| (kind == IASTExpression.Kind.EXCLUSIVEOREXPRESSION)
|| (kind == IASTExpression.Kind.INCLUSIVEOREXPRESSION)
){
ASTExpression left = (ASTExpression)lhs;
ASTExpression right = (ASTExpression)rhs;
if((left != null ) && (right != null)){
TypeInfo leftType =left.getResultType().getResult();
TypeInfo rightType =right.getResultType().getResult();
info = usualArithmeticConversions( scope, leftType, rightType);
}
else
handleProblem( scope, IProblem.SEMANTIC_MALFORMED_EXPRESSION, null );
result = new ExpressionResult(info);
return result;
}
// types that resolve to LHS types
if ((kind == IASTExpression.Kind.PRIMARY_BRACKETED_EXPRESSION)
|| (kind == IASTExpression.Kind.POSTFIX_INCREMENT)
|| (kind == IASTExpression.Kind.POSTFIX_DECREMENT)
|| (kind == IASTExpression.Kind.POSTFIX_TYPEID_EXPRESSION)
|| (kind == IASTExpression.Kind.UNARY_INCREMENT)
|| (kind == IASTExpression.Kind.UNARY_DECREMENT)
|| (kind == IASTExpression.Kind.UNARY_PLUS_CASTEXPRESSION)
|| (kind == IASTExpression.Kind.UNARY_MINUS_CASTEXPRESSION)
|| (kind == IASTExpression.Kind.UNARY_NOT_CASTEXPRESSION)
|| (kind == IASTExpression.Kind.UNARY_TILDE_CASTEXPRESSION)
|| (kind == IASTExpression.Kind.SHIFT_LEFT)
|| (kind == IASTExpression.Kind.SHIFT_RIGHT)
|| (kind == IASTExpression.Kind.ASSIGNMENTEXPRESSION_NORMAL)
|| (kind == IASTExpression.Kind.ASSIGNMENTEXPRESSION_PLUS)
|| (kind == IASTExpression.Kind.ASSIGNMENTEXPRESSION_MINUS)
|| (kind == IASTExpression.Kind.ASSIGNMENTEXPRESSION_MULT)
|| (kind == IASTExpression.Kind.ASSIGNMENTEXPRESSION_DIV)
|| (kind == IASTExpression.Kind.ASSIGNMENTEXPRESSION_MOD)
|| (kind == IASTExpression.Kind.ASSIGNMENTEXPRESSION_LSHIFT)
|| (kind == IASTExpression.Kind.ASSIGNMENTEXPRESSION_RSHIFT)
|| (kind == IASTExpression.Kind.ASSIGNMENTEXPRESSION_AND)
|| (kind == IASTExpression.Kind.ASSIGNMENTEXPRESSION_OR)
|| (kind == IASTExpression.Kind.ASSIGNMENTEXPRESSION_XOR)
){
ASTExpression left = (ASTExpression)lhs;
if(left != null){
info =left.getResultType().getResult();
} else
handleProblem( scope, IProblem.SEMANTIC_MALFORMED_EXPRESSION, null );
result = new ExpressionResult(info);
return result;
}
// the cast changes the types to the type looked up in typeId = symbol
if(( kind == IASTExpression.Kind.CASTEXPRESSION )
|| ( kind == IASTExpression.Kind.POSTFIX_DYNAMIC_CAST )
|| ( kind == IASTExpression.Kind.POSTFIX_STATIC_CAST )
|| ( kind == IASTExpression.Kind.POSTFIX_REINTERPRET_CAST )
|| ( kind == IASTExpression.Kind.POSTFIX_CONST_CAST )
){
try{
info = new TypeInfo(typeId.getTypeSymbol().getTypeInfo());
}catch (ASTNotImplementedException e)
{
// will never happen
}
result = new ExpressionResult(info);
return result;
}
// a list collects all types of left and right hand sides
if(kind == IASTExpression.Kind.EXPRESSIONLIST){
result = new ExpressionResultList();
if(lhs != null){
TypeInfo leftType = ((ASTExpression)lhs).getResultType().getResult();
result.setResult(leftType);
}
if(rhs != null){
TypeInfo rightType = ((ASTExpression)rhs).getResultType().getResult();
result.setResult(rightType);
}
return result;
}
// a function call type is the return type of the function
if(kind == IASTExpression.Kind.POSTFIX_FUNCTIONCALL){
if(symbol != null){
IParameterizedSymbol psymbol = (IParameterizedSymbol) symbol;
ISymbol returnTypeSymbol = psymbol.getReturnType();
if(returnTypeSymbol != null){
info.setType(returnTypeSymbol.getType());
info.setTypeSymbol(returnTypeSymbol);
}else {
// this is call to a constructor
}
}
result = new ExpressionResult(info);
if(symbol == null)
result.setFailedToDereference(true);
return result;
}
// typeid
if( kind == IASTExpression.Kind.POSTFIX_TYPEID_TYPEID )
{
try
{
info = typeId.getTypeSymbol().getTypeInfo();
}
catch (ASTNotImplementedException e)
{
// will not ever happen from within CompleteParseASTFactory
}
result = new ExpressionResult(info);
return result;
}
// typename
if ( ( kind == IASTExpression.Kind.POSTFIX_TYPENAME_IDENTIFIER )
|| ( kind == IASTExpression.Kind.POSTFIX_TYPENAME_TEMPLATEID ) )
{
if(symbol != null){
info.setType(TypeInfo.t_type);
info.setTypeSymbol(symbol);
} else
handleProblem( scope, IProblem.SEMANTIC_MALFORMED_EXPRESSION, null );
result = new ExpressionResult(info);
return result;
}
// assert false : this;
return null;
}
protected void getExpressionReferences(IASTExpression expression, List references)
{
if( expression != null )
{
List eRefs = ((ASTExpression)expression).getReferences();
if( eRefs != null && !eRefs.isEmpty())
{
for( int i = 0; i < eRefs.size(); ++i )
{
IASTReference r = (IASTReference)eRefs.get(i);
references.add( cache.getReference( r.getOffset(), r.getReferencedElement() ));
}
}
if( expression.getLHSExpression() != null )
getExpressionReferences( expression.getLHSExpression(), references );
if( expression.getRHSExpression() != null )
getExpressionReferences( expression.getRHSExpression(), references );
}
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.parser.ast.IASTFactory#createNewDescriptor()
*/
public IASTNewExpressionDescriptor createNewDescriptor(List newPlacementExpressions,List newTypeIdExpressions,List newInitializerExpressions)
{
return new ASTNewDescriptor(newPlacementExpressions, newTypeIdExpressions, newInitializerExpressions);
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.parser.ast.IASTFactory#createExceptionSpecification(java.util.List)
*/
public IASTExceptionSpecification createExceptionSpecification(IASTScope scope, List typeIds) throws ASTSemanticException
{
List newTypeIds = new ArrayList();
if( typeIds != null )
{
Iterator iter =typeIds.iterator();
while( iter.hasNext() )
newTypeIds.add( ((IASTTypeId)iter.next()).toString() );
}
return new ASTExceptionSpecification( newTypeIds );
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.parser.ast.IASTFactory#createConstructorMemberInitializer(org.eclipse.cdt.core.parser.ITokenDuple, org.eclipse.cdt.core.parser.ast.IASTExpression)
*/
public IASTConstructorMemberInitializer createConstructorMemberInitializer(
IASTScope scope,
ITokenDuple duple, IASTExpression expressionList)
{
List references = new ArrayList();
IContainerSymbol scopeSymbol = scopeToSymbol(scope);
boolean requireReferenceResolution = false;
ISymbol symbol = null;
if( duple != null )
{
try
{
symbol = lookupQualifiedName( scopeSymbol, duple, references, true );
} catch( ASTSemanticException ase )
{
requireReferenceResolution = true;
}
}
if( symbol != null ){
createConstructorReference( symbol, (ASTExpression) expressionList, duple, references );
}
getExpressionReferences( expressionList, references );
return new ASTConstructorMemberInitializer(
expressionList,
duple == null ? EMPTY_STRING : duple.toString(),
duple == null ? 0 : duple.getFirstToken().getOffset(),
references, requireReferenceResolution );
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.parser.ast.IASTFactory#createSimpleTypeSpecifier(org.eclipse.cdt.core.parser.ast.IASTSimpleTypeSpecifier.Type, org.eclipse.cdt.core.parser.ITokenDuple, boolean, boolean, boolean, boolean, boolean)
*/
public IASTSimpleTypeSpecifier createSimpleTypeSpecifier(
IASTScope scope,
Type kind,
ITokenDuple typeName,
boolean isShort,
boolean isLong,
boolean isSigned,
boolean isUnsigned,
boolean isTypename,
boolean isComplex,
boolean isImaginary,
boolean isGlobal, Map extensionParms ) throws ASTSemanticException
{
if( extension.overrideCreateSimpleTypeSpecifierMethod( kind ))
return extension.createSimpleTypeSpecifier(pst, scope, kind, typeName, isShort, isLong, isSigned, isUnsigned, isTypename, isComplex, isImaginary, isGlobal, extensionParms );
String typeNameAsString = typeName.toString();
if( kind != Type.CLASS_OR_TYPENAME )
{
IASTSimpleTypeSpecifier query = (IASTSimpleTypeSpecifier) simpleTypeSpecCache.get( typeNameAsString );
if( query != null )
return query;
}
TypeInfo.eType type = null;
if( kind == IASTSimpleTypeSpecifier.Type.CLASS_OR_TYPENAME )
type = TypeInfo.t_type;
else if( kind == IASTSimpleTypeSpecifier.Type.BOOL )
type = TypeInfo.t_bool;
else if( kind == IASTSimpleTypeSpecifier.Type.CHAR )
type = TypeInfo.t_char;
else if( kind == IASTSimpleTypeSpecifier.Type.DOUBLE ||kind == IASTSimpleTypeSpecifier.Type.FLOAT )
type = TypeInfo.t_double;
else if( kind == IASTSimpleTypeSpecifier.Type.INT )
type = TypeInfo.t_int;
else if( kind == IASTSimpleTypeSpecifier.Type.VOID )
type = TypeInfo.t_void;
else if( kind == IASTSimpleTypeSpecifier.Type.WCHAR_T)
type = TypeInfo.t_wchar_t;
else if( kind == IASTSimpleTypeSpecifier.Type._BOOL )
type = TypeInfo.t__Bool;
List references = ( kind == Type.CLASS_OR_TYPENAME ) ? new ArrayList( DEFAULT_QUALIFIEDNAME_REFERENCE_SIZE ): null;
ISymbol s = pst.newSymbol( EMPTY_STRING, type );
if( kind == IASTSimpleTypeSpecifier.Type.CLASS_OR_TYPENAME )
{
// lookup the duple
Iterator i = typeName.iterator();
IToken first = typeName.getFirstToken();
ISymbol typeSymbol = getScopeToSearchUpon( scope, first, i );
if( isGlobal )
typeSymbol = typeSymbol.getSymbolTable().getCompilationUnit();
List [] argLists = typeName.getTemplateIdArgLists();
int idx = 0;
while( i.hasNext() )
{
IToken current = (IToken)i.next();
if( current.getType() == IToken.tCOLONCOLON ){
idx++;
continue;
}
String image = current.getImage();
int offset = current.getOffset();
if( argLists != null && argLists[ idx ] != null ){
if( i.hasNext() && current.getNext().getType() == IToken.tLT )
current = TokenFactory.consumeTemplateIdArguments( (IToken) i.next(), i );
}
if( typeSymbol instanceof IDeferredTemplateInstance ){
typeSymbol = ((IDeferredTemplateInstance)typeSymbol).getTemplate().getTemplatedSymbol();
}
try
{
if( argLists != null && argLists[ idx ] != null )
typeSymbol = ((IContainerSymbol)typeSymbol).lookupTemplateId( image, getTemplateArgList( argLists[idx] ) );
else if( current != typeName.getLastToken() )
typeSymbol = ((IContainerSymbol)typeSymbol).lookupNestedNameSpecifier( image );
else
typeSymbol = ((IContainerSymbol)typeSymbol).lookup( image );
if( typeSymbol != null )
{
addReference( references, createReference( typeSymbol, image, offset ));
if( argLists != null && argLists[idx] != null )
{
addTemplateIdReferences( references, argLists[idx] );
typeName.freeReferences(cache);
}
}
else
handleProblem( IProblem.SEMANTIC_NAME_NOT_FOUND, image, -1, -1, current.getLineNumber(), true );
}
catch (ParserSymbolTableException e)
{
handleProblem( e.createProblemID(), image,typeName.getStartOffset(), typeName.getEndOffset(), typeName.getLineNumber(), true );
}
}
s.setTypeSymbol( typeSymbol );
}
s.getTypeInfo().setBit( isLong, TypeInfo.isLong );
s.getTypeInfo().setBit( isShort, TypeInfo.isShort);
s.getTypeInfo().setBit( isUnsigned, TypeInfo.isUnsigned );
s.getTypeInfo().setBit( isComplex, TypeInfo.isComplex );
s.getTypeInfo().setBit( isImaginary, TypeInfo.isImaginary );
s.getTypeInfo().setBit( isSigned, TypeInfo.isSigned );
IASTSimpleTypeSpecifier result = new ASTSimpleTypeSpecifier( s, false, typeNameAsString, references );
if( kind != Type.CLASS_OR_TYPENAME )
simpleTypeSpecCache.put( typeNameAsString, result );
return result;
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.parser.ast.IASTFactory#createFunction(org.eclipse.cdt.core.parser.ast.IASTScope, java.lang.String, java.util.List, org.eclipse.cdt.core.parser.ast.IASTAbstractDeclaration, org.eclipse.cdt.core.parser.ast.IASTExceptionSpecification, boolean, boolean, boolean, int, int, org.eclipse.cdt.core.parser.ast.IASTTemplate)
*/
public IASTFunction createFunction(
IASTScope scope,
ITokenDuple name,
List parameters,
IASTAbstractDeclaration returnType,
IASTExceptionSpecification exception,
boolean isInline,
boolean isFriend,
boolean isStatic,
int startOffset,
int startLine,
int nameOffset,
int nameEndOffset,
int nameLine,
IASTTemplate ownerTemplate,
boolean isConst,
boolean isVolatile,
boolean isVirtual,
boolean isExplicit,
boolean isPureVirtual, List constructorChain, boolean isFunctionDefinition, boolean hasFunctionTryBlock, boolean hasVariableArguments ) throws ASTSemanticException
{
List references = new ArrayList();
IContainerSymbol ownerScope = scopeToSymbol( scope );
// check if this is a method in a body file
if(name.getSegmentCount() > 1){
ISymbol symbol = lookupQualifiedName( ownerScope,
name.getLeadingSegments(),
references,
false,
LookupType.FORPARENTSCOPE );
IContainerSymbol parentScope = null;
if( symbol instanceof IContainerSymbol )
parentScope = (IContainerSymbol) symbol;
else if( symbol instanceof IDeferredTemplateInstance )
parentScope = ((IDeferredTemplateInstance) symbol).getTemplate().getTemplatedSymbol();
if((parentScope != null) &&
( (parentScope.getType() == TypeInfo.t_class)
|| (parentScope.getType() == TypeInfo.t_struct)
|| (parentScope.getType() == TypeInfo.t_union))
){
if( parentScope.getASTExtension().getPrimaryDeclaration() instanceof IASTElaboratedTypeSpecifier ){
//we are trying to define a member of a class for which we only have a forward declaration
handleProblem( scope, IProblem.SEMANTICS_RELATED, name.toString(), startOffset, nameEndOffset, startLine, true );
}
IASTScope methodParentScope = (IASTScope)parentScope.getASTExtension().getPrimaryDeclaration();
ITokenDuple newName = name.getLastSegment();
return createMethod(
methodParentScope,
newName,
parameters,
returnType,
exception,
isInline,
isFriend,
isStatic,
startOffset,
startLine,
newName.getFirstToken().getOffset(),
nameEndOffset,
nameLine,
ownerTemplate,
isConst,
isVolatile,
isVirtual,
isExplicit,
isPureVirtual,
ASTAccessVisibility.PRIVATE,
constructorChain, references, isFunctionDefinition, hasFunctionTryBlock, hasVariableArguments );
}
}
IParameterizedSymbol symbol = pst.newParameterizedSymbol( name.extractNameFromTemplateId(), TypeInfo.t_function );
setFunctionTypeInfoBits(isInline, isFriend, isStatic, symbol);
symbol.setHasVariableArgs( hasVariableArguments );
symbol.prepareForParameters( parameters.size() );
setParameter( symbol, returnType, false, references );
setParameters( symbol, references, parameters.iterator() );
symbol.setIsForwardDeclaration(!isFunctionDefinition);
boolean previouslyDeclared = false;
List functionParameters = new LinkedList();
// the lookup requires a list of type infos
// instead of a list of IASTParameterDeclaration
Iterator p = parameters.iterator();
while (p.hasNext()){
ASTParameterDeclaration param = (ASTParameterDeclaration)p.next();
if( param.getSymbol() == null )
handleProblem( IProblem.SEMANTICS_RELATED, param.getName(), param.getNameOffset(), param.getEndingOffset(), param.getStartingLine(), true );
functionParameters.add(param.getSymbol().getTypeInfo());
}
IParameterizedSymbol functionDeclaration = null;
functionDeclaration =
(IParameterizedSymbol) lookupQualifiedName(ownerScope, name.getFirstToken().getImage(), TypeInfo.t_function, functionParameters, 0, null, false, LookupType.FORDEFINITION );
if( functionDeclaration != null && symbol.isType( TypeInfo.t_function )){
previouslyDeclared = true;
if( isFunctionDefinition ){
functionDeclaration.setTypeSymbol( symbol );
}
}
if( previouslyDeclared == false || isFunctionDefinition ){
try
{
ownerScope.addSymbol( symbol );
}
catch (ParserSymbolTableException e)
{
handleProblem( e.createProblemID(), name.toString());
}
} else {
symbol = functionDeclaration;
}
ASTFunction function = new ASTFunction( symbol, nameEndOffset, parameters, returnType, exception, startOffset, startLine, nameOffset, nameLine, ownerTemplate, references, previouslyDeclared, hasFunctionTryBlock, isFriend );
attachSymbolExtension(symbol, function, isFunctionDefinition);
return function;
}
protected void setFunctionTypeInfoBits(
boolean isInline,
boolean isFriend,
boolean isStatic,
IParameterizedSymbol symbol)
{
symbol.getTypeInfo().setBit( isInline, TypeInfo.isInline );
symbol.getTypeInfo().setBit( isFriend, TypeInfo.isFriend );
symbol.getTypeInfo().setBit( isStatic, TypeInfo.isStatic );
}
/**
* @param symbol
* @param iterator
*/
protected void setParameters(IParameterizedSymbol symbol, List references, Iterator iterator) throws ASTSemanticException
{
while( iterator.hasNext() )
{
setParameter( symbol, (IASTParameterDeclaration)iterator.next(), true, references );
}
}
protected TypeInfo getParameterTypeInfo( IASTAbstractDeclaration absDecl)throws ASTSemanticException{
TypeInfo type = new TypeInfo();
if( absDecl.getTypeSpecifier() instanceof IASTSimpleTypeSpecifier )
{
IASTSimpleTypeSpecifier simpleType = ((IASTSimpleTypeSpecifier)absDecl.getTypeSpecifier());
IASTSimpleTypeSpecifier.Type kind = simpleType.getType();
if( kind == IASTSimpleTypeSpecifier.Type.BOOL )
type.setType(TypeInfo.t_bool);
else if( kind == IASTSimpleTypeSpecifier.Type.CHAR )
type.setType(TypeInfo.t_char);
else if( kind == IASTSimpleTypeSpecifier.Type.DOUBLE )
type.setType(TypeInfo.t_double);
else if( kind == IASTSimpleTypeSpecifier.Type.FLOAT )
type.setType(TypeInfo.t_float);
else if( kind == IASTSimpleTypeSpecifier.Type.INT )
type.setType(TypeInfo.t_int);
else if( kind == IASTSimpleTypeSpecifier.Type.VOID )
type.setType(TypeInfo.t_void);
else if( kind == IASTSimpleTypeSpecifier.Type.WCHAR_T)
type.setType(TypeInfo.t_wchar_t);
else if( kind == IASTSimpleTypeSpecifier.Type.CLASS_OR_TYPENAME )
type.setType(TypeInfo.t_type);
else if( kind == IASTSimpleTypeSpecifier.Type._BOOL ){
type.setType( TypeInfo.t__Bool );
}
// else
// assert false : "Unexpected IASTSimpleTypeSpecifier.Type";
setTypeBitFlags(type, simpleType);
}
else if( absDecl.getTypeSpecifier() instanceof IASTClassSpecifier )
{
type.setType( TypeInfo.t_type );
type.setTypeSymbol( ((ASTClassSpecifier)absDecl.getTypeSpecifier()).getSymbol() );
}
else if( absDecl.getTypeSpecifier() instanceof IASTEnumerationSpecifier )
{
type.setType( TypeInfo.t_type );
type.setTypeSymbol( ((ASTEnumerationSpecifier)absDecl.getTypeSpecifier()).getSymbol() );
}
else if( absDecl.getTypeSpecifier() instanceof IASTElaboratedTypeSpecifier )
{
type.setType( TypeInfo.t_type );
type.setTypeSymbol( ((ASTElaboratedTypeSpecifier)absDecl.getTypeSpecifier()).getSymbol() );
}
// else
// assert false : this;
return type;
}
/**
* @param type
* @param simpleType
*/
private void setTypeBitFlags(TypeInfo type, IASTSimpleTypeSpecifier simpleType) {
type.setBit( simpleType.isLong(), TypeInfo.isLong);
type.setBit( simpleType.isShort(), TypeInfo.isShort);
type.setBit( simpleType.isUnsigned(), TypeInfo.isUnsigned);
type.setBit( simpleType.isComplex(), TypeInfo.isComplex);
type.setBit( simpleType.isImaginary(), TypeInfo.isImaginary);
type.setBit( simpleType.isSigned(), TypeInfo.isSigned);
}
/**
* @param symbol
* @param returnType
*/
protected void setParameter(IParameterizedSymbol symbol, IASTAbstractDeclaration absDecl, boolean isParameter, List references) throws ASTSemanticException
{
if (absDecl.getTypeSpecifier() == null)
return;
// now determined by another function
TypeInfo info = getParameterTypeInfo( absDecl );
TypeInfo.eType type = info.getType();
ISymbol xrefSymbol = info.getTypeSymbol();
List newReferences = null;
int infoBits = 0;
if( absDecl.getTypeSpecifier() instanceof IASTSimpleTypeSpecifier )
{
if( ((IASTSimpleTypeSpecifier)absDecl.getTypeSpecifier()).getType() == IASTSimpleTypeSpecifier.Type.CLASS_OR_TYPENAME )
{
xrefSymbol = ((ASTSimpleTypeSpecifier)absDecl.getTypeSpecifier()).getSymbol();
newReferences = ((ASTSimpleTypeSpecifier)absDecl.getTypeSpecifier()).getReferences();
}
infoBits = ((ASTSimpleTypeSpecifier)absDecl.getTypeSpecifier()).getSymbol().getTypeInfo().getTypeInfo();
}
else if( absDecl.getTypeSpecifier() instanceof ASTElaboratedTypeSpecifier )
{
ASTElaboratedTypeSpecifier elab = (ASTElaboratedTypeSpecifier)absDecl.getTypeSpecifier();
xrefSymbol = elab.getSymbol();
List elabReferences = elab.getReferences();
newReferences = new ArrayList(elabReferences.size());
for( int i = 0; i < elabReferences.size(); ++i )
{
IASTReference r = (IASTReference)elabReferences.get(i);
newReferences.add( cache.getReference(r.getOffset(), r.getReferencedElement()));
}
if( xrefSymbol != null )
addReference( newReferences, createReference( xrefSymbol, elab.getName(), elab.getNameOffset()) );
}
String paramName = EMPTY_STRING;
if(absDecl instanceof IASTParameterDeclaration){
paramName = ((IASTParameterDeclaration)absDecl).getName();
}
ISymbol paramSymbol = pst.newSymbol( paramName, type );
if( xrefSymbol != null ){
if( absDecl.getTypeSpecifier() instanceof IASTSimpleTypeSpecifier )
paramSymbol.setTypeSymbol( xrefSymbol.getTypeSymbol() );
else
paramSymbol.setTypeSymbol( xrefSymbol );
}
paramSymbol.getTypeInfo().setTypeInfo( infoBits );
paramSymbol.getTypeInfo().setBit( absDecl.isConst(), TypeInfo.isConst );
paramSymbol.getTypeInfo().setBit( absDecl.isVolatile(), TypeInfo.isVolatile );
setPointerOperators( paramSymbol, absDecl.getPointerOperators(), absDecl.getArrayModifiers() );
if( isParameter)
symbol.addParameter( paramSymbol );
else
symbol.setReturnType( paramSymbol );
if( newReferences != null && !newReferences.isEmpty())
references.addAll( newReferences );
if( absDecl instanceof ASTParameterDeclaration )
{
ASTParameterDeclaration parm = (ASTParameterDeclaration)absDecl;
parm.setSymbol( paramSymbol );
attachSymbolExtension( paramSymbol, parm, true );
}
}
/**
* @param paramSymbol
* @param iterator
*/
protected void setPointerOperators(ISymbol symbol, Iterator pointerOpsIterator, Iterator arrayModsIterator) throws ASTSemanticException
{
while( pointerOpsIterator.hasNext() )
{
ASTPointerOperator pointerOperator = (ASTPointerOperator)pointerOpsIterator.next();
if( pointerOperator == ASTPointerOperator.REFERENCE )
symbol.addPtrOperator( new TypeInfo.PtrOp( TypeInfo.PtrOp.t_reference ));
else if( pointerOperator == ASTPointerOperator.POINTER )
symbol.addPtrOperator( new TypeInfo.PtrOp( TypeInfo.PtrOp.t_pointer ));
else if( pointerOperator == ASTPointerOperator.CONST_POINTER )
symbol.addPtrOperator( new TypeInfo.PtrOp( TypeInfo.PtrOp.t_pointer, true, false ));
else if( pointerOperator == ASTPointerOperator.VOLATILE_POINTER )
symbol.addPtrOperator( new TypeInfo.PtrOp( TypeInfo.PtrOp.t_pointer, false, true));
// else
// assert false : pointerOperator;
}
while( arrayModsIterator.hasNext() )
{
arrayModsIterator.next();
symbol.addPtrOperator( new TypeInfo.PtrOp( TypeInfo.PtrOp.t_array ));
}
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.parser.ast.IASTFactory#createMethod(org.eclipse.cdt.core.parser.ast.IASTScope, java.lang.String, java.util.List, org.eclipse.cdt.core.parser.ast.IASTAbstractDeclaration, org.eclipse.cdt.core.parser.ast.IASTExceptionSpecification, boolean, boolean, boolean, int, int, org.eclipse.cdt.core.parser.ast.IASTTemplate, boolean, boolean, boolean, boolean, boolean, boolean, boolean, org.eclipse.cdt.core.parser.ast.ASTAccessVisibility)
*/
public IASTMethod createMethod(
IASTScope scope,
ITokenDuple name,
List parameters,
IASTAbstractDeclaration returnType,
IASTExceptionSpecification exception,
boolean isInline,
boolean isFriend,
boolean isStatic,
int startOffset,
int startLine,
int nameOffset,
int nameEndOffset,
int nameLine,
IASTTemplate ownerTemplate,
boolean isConst,
boolean isVolatile,
boolean isVirtual,
boolean isExplicit, boolean isPureVirtual, ASTAccessVisibility visibility, List constructorChain, boolean isFunctionDefinition, boolean hasFunctionTryBlock, boolean hasVariableArguments ) throws ASTSemanticException
{
return createMethod(scope, name, parameters, returnType, exception,
isInline, isFriend, isStatic, startOffset, startLine, nameOffset,
nameEndOffset, nameLine, ownerTemplate, isConst, isVolatile, isVirtual,
isExplicit, isPureVirtual, visibility, constructorChain, null, isFunctionDefinition, hasFunctionTryBlock, hasVariableArguments );
}
public IASTMethod createMethod(
IASTScope scope,
ITokenDuple nameDuple,
List parameters,
IASTAbstractDeclaration returnType,
IASTExceptionSpecification exception,
boolean isInline,
boolean isFriend,
boolean isStatic,
int startOffset,
int startingLine,
int nameOffset,
int nameEndOffset,
int nameLine,
IASTTemplate ownerTemplate,
boolean isConst,
boolean isVolatile,
boolean isVirtual,
boolean isExplicit,
boolean isPureVirtual,
ASTAccessVisibility visibility, List constructorChain, List references, boolean isFunctionDefinition, boolean hasFunctionTryBlock, boolean hasVariableArguments ) throws ASTSemanticException
{
boolean isConstructor = false;
boolean isDestructor = false;
IContainerSymbol ownerScope = scopeToSymbol( ownerTemplate != null ? (IASTScope) ownerTemplate : scope );
IParameterizedSymbol symbol = null;
if( references == null )
{
references = new ArrayList();
if( nameDuple.length() > 2 ) // destructor
{
ITokenDuple leadingSegments = nameDuple.getLeadingSegments();
ISymbol test = lookupQualifiedName( ownerScope, leadingSegments, references, false );
if( test == ownerScope )
nameDuple = nameDuple.getLastSegment();
}
}
String methodName = null;
List templateIdArgList = null;
//template-id?
if( nameDuple.getTemplateIdArgLists() != null ){
templateIdArgList = nameDuple.getTemplateIdArgLists()[ 0 ];
methodName = nameDuple.extractNameFromTemplateId();
} else {
methodName = nameDuple.toString();
}
symbol = pst.newParameterizedSymbol( methodName, TypeInfo.t_function );
setFunctionTypeInfoBits(isInline, isFriend, isStatic, symbol);
setMethodTypeInfoBits( symbol, isConst, isVolatile, isVirtual, isExplicit );
symbol.setHasVariableArgs( hasVariableArguments );
symbol.prepareForParameters( parameters.size() );
if( returnType.getTypeSpecifier() != null )
setParameter( symbol, returnType, false, references );
setParameters( symbol, references, parameters.iterator() );
IASTClassSpecifier classifier = null;
if( scope instanceof IASTTemplateDeclaration ){
classifier = (IASTClassSpecifier) ((IASTTemplateDeclaration)scope).getOwnerScope();
} else {
classifier = (IASTClassSpecifier) scope;
}
String parentName = classifier.getName();
// check constructor / destructor if no return type
if ( returnType.getTypeSpecifier() == null ){
if(parentName.indexOf(DOUBLE_COLON) != -1){
parentName = parentName.substring(parentName.lastIndexOf(DOUBLE_COLON) + DOUBLE_COLON.length());
}
if( parentName.equals(methodName) ){
isConstructor = true;
} else if(methodName.equals( "~" + parentName )){ //$NON-NLS-1$
isDestructor = true;
}
}
symbol.setIsForwardDeclaration(!isFunctionDefinition);
boolean previouslyDeclared = false;
IParameterizedSymbol functionDeclaration = null;
if( isFunctionDefinition || isFriend )
{
List functionParameters = new LinkedList();
// the lookup requires a list of type infos
// instead of a list of IASTParameterDeclaration
Iterator p = parameters.iterator();
while (p.hasNext()){
ASTParameterDeclaration param = (ASTParameterDeclaration)p.next();
if( param.getSymbol() == null )
handleProblem( IProblem.SEMANTICS_RELATED, param.getName(), param.getNameOffset(), param.getEndingOffset(), param.getNameLineNumber(), true );
functionParameters.add(param.getSymbol().getTypeInfo());
}
functionDeclaration = (IParameterizedSymbol) lookupQualifiedName( ownerScope, nameDuple,
isConstructor ? TypeInfo.t_constructor : TypeInfo.t_function,
functionParameters, null, false,
isFriend ? LookupType.FORFRIENDSHIP : LookupType.FORDEFINITION );
previouslyDeclared = ( functionDeclaration != null ) && functionDeclaration.isType( isConstructor ? TypeInfo.t_constructor : TypeInfo.t_function );
if( isFriend )
{
if( functionDeclaration != null && functionDeclaration.isType( isConstructor ? TypeInfo.t_constructor : TypeInfo.t_function ))
{
symbol.setTypeSymbol( functionDeclaration );
// friend declaration, has no real visibility, set private
visibility = ASTAccessVisibility.PRIVATE;
} else if( ownerScope.getContainingSymbol().isType( TypeInfo.t_constructor ) ||
ownerScope.getContainingSymbol().isType( TypeInfo.t_function ) ||
ownerScope.getContainingSymbol().isType( TypeInfo.t_block ) )
{
//only needs to be previously declared if we are in a local class
handleProblem( IProblem.SEMANTIC_ILLFORMED_FRIEND, nameDuple.toString(), nameDuple.getStartOffset(), nameDuple.getEndOffset(), nameDuple.getLineNumber(), true );
}
} else if( functionDeclaration != null && functionDeclaration.isType( isConstructor ? TypeInfo.t_constructor : TypeInfo.t_function ) )
{
functionDeclaration.setTypeSymbol( symbol );
// set the definition visibility = declaration visibility
// ASTMethodReference reference = (ASTMethodReference) functionReferences.iterator().next();
visibility = ((IASTMethod)(functionDeclaration.getASTExtension().getPrimaryDeclaration())).getVisiblity();
}
}
try
{
if( isFriend )
{
if( functionDeclaration != null )
((IDerivableContainerSymbol)ownerScope).addFriend( functionDeclaration );
else
((IDerivableContainerSymbol)ownerScope).addFriend( symbol );
} else if( !isConstructor ){
if( templateIdArgList == null )
ownerScope.addSymbol( symbol );
else
ownerScope.addTemplateId( symbol, getTemplateArgList( templateIdArgList ) );
}
else
{
symbol.setType( TypeInfo.t_constructor );
((IDerivableContainerSymbol)ownerScope).addConstructor( symbol );
}
}
catch (ParserSymbolTableException e)
{
handleProblem(e.createProblemID(), nameDuple.toString(), nameDuple.getStartOffset(), nameDuple.getEndOffset(), nameDuple.getLineNumber(), true );
}
resolveLeftoverConstructorInitializerMembers( symbol, constructorChain );
ASTMethod method = new ASTMethod( symbol, parameters, returnType, exception, startOffset, startingLine, nameOffset, nameEndOffset, nameLine, ownerTemplate, references, previouslyDeclared, isConstructor, isDestructor, isPureVirtual, visibility, constructorChain, hasFunctionTryBlock, isFriend );
if( functionDeclaration != null && isFunctionDefinition )
attachSymbolExtension( symbol, (ASTSymbol) functionDeclaration.getASTExtension().getPrimaryDeclaration(), false );
attachSymbolExtension( symbol, method, isFunctionDefinition );
return method;
}
/**
* @param symbol
* @param constructorChain
*/
protected void resolveLeftoverConstructorInitializerMembers(IParameterizedSymbol symbol, List constructorChain) throws ASTSemanticException
{
if( constructorChain != null )
{
Iterator initializers = constructorChain.iterator();
while( initializers.hasNext())
{
IASTConstructorMemberInitializer initializer = (IASTConstructorMemberInitializer)initializers.next();
if( !initializer.getName().equals( EMPTY_STRING) &&
initializer instanceof ASTConstructorMemberInitializer &&
((ASTConstructorMemberInitializer)initializer).requiresNameResolution() )
{
ASTConstructorMemberInitializer realInitializer = ((ASTConstructorMemberInitializer)initializer);
IDerivableContainerSymbol container = (IDerivableContainerSymbol) symbol.getContainingSymbol();
lookupQualifiedName(container, initializer.getName(), TypeInfo.t_any, null, realInitializer.getNameOffset(), realInitializer.getReferences(), false, LookupType.QUALIFIED);
// TODO try and resolve parameter references now in the expression list
}
}
}
}
/**
* @param symbol
* @param isConst
* @param isVolatile
* @param isConstructor
* @param isDestructor
* @param isVirtual
* @param isExplicit
* @param isPureVirtual
*/
protected void setMethodTypeInfoBits(IParameterizedSymbol symbol, boolean isConst, boolean isVolatile, boolean isVirtual, boolean isExplicit)
{
symbol.getTypeInfo().setBit( isConst, TypeInfo.isConst );
symbol.getTypeInfo().setBit( isVolatile, TypeInfo.isVolatile );
symbol.getTypeInfo().setBit( isVirtual, TypeInfo.isVirtual );
symbol.getTypeInfo().setBit( isExplicit, TypeInfo.isExplicit );
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.parser.ast.IASTFactory#createVariable(org.eclipse.cdt.core.parser.ast.IASTScope, java.lang.String, boolean, org.eclipse.cdt.core.parser.ast.IASTInitializerClause, org.eclipse.cdt.core.parser.ast.IASTExpression, org.eclipse.cdt.core.parser.ast.IASTAbstractDeclaration, boolean, boolean, boolean, boolean, int, int)
*/
public IASTVariable createVariable(
IASTScope scope,
ITokenDuple name,
boolean isAuto,
IASTInitializerClause initializerClause,
IASTExpression bitfieldExpression,
IASTAbstractDeclaration abstractDeclaration,
boolean isMutable,
boolean isExtern,
boolean isRegister,
boolean isStatic,
int startingOffset,
int startingLine, int nameOffset, int nameEndOffset, int nameLine, IASTExpression constructorExpression) throws ASTSemanticException
{
List references = new ArrayList();
IContainerSymbol ownerScope = scopeToSymbol( scope );
if( name == null )
handleProblem( IProblem.SEMANTIC_NAME_NOT_PROVIDED, null, startingOffset, nameEndOffset, nameLine, true );
if(name.getSegmentCount() > 1)
{
ISymbol symbol = lookupQualifiedName( ownerScope,
name.getLeadingSegments(),
references,
false,
LookupType.FORPARENTSCOPE );
IContainerSymbol parentScope = null;
if( symbol instanceof IContainerSymbol )
parentScope = (IContainerSymbol) symbol;
else if( symbol instanceof IDeferredTemplateInstance )
parentScope = ((IDeferredTemplateInstance) symbol).getTemplate().getTemplatedSymbol();
if( (parentScope != null) && ( (parentScope.getType() == TypeInfo.t_class) ||
(parentScope.getType() == TypeInfo.t_struct)||
(parentScope.getType() == TypeInfo.t_union) ) )
{
IASTScope fieldParentScope = (IASTScope)parentScope.getASTExtension().getPrimaryDeclaration();
ITokenDuple newName = name.getLastSegment();
return createField(fieldParentScope, newName,isAuto, initializerClause, bitfieldExpression, abstractDeclaration, isMutable, isExtern,
isRegister, isStatic, startingOffset, startingLine, newName.getStartOffset(), nameEndOffset, nameLine, constructorExpression, ASTAccessVisibility.PRIVATE, references);
}
}
ISymbol newSymbol = cloneSimpleTypeSymbol(name.getFirstToken().getImage(), abstractDeclaration, references);
if( newSymbol == null )
handleProblem( IProblem.SEMANTICS_RELATED, name.toString() );
setVariableTypeInfoBits(
isAuto,
abstractDeclaration,
isMutable,
isExtern,
isRegister,
isStatic,
newSymbol);
int numPtrOps = ((ASTAbstractDeclaration)abstractDeclaration).getNumArrayModifiers() +
((ASTAbstractDeclaration)abstractDeclaration).getNumPointerOperators();
newSymbol.preparePtrOperatros( numPtrOps );
setPointerOperators( newSymbol, abstractDeclaration.getPointerOperators(), abstractDeclaration.getArrayModifiers() );
newSymbol.setIsForwardDeclaration( isStatic || isExtern );
boolean previouslyDeclared = false;
if(!isStatic){
ISymbol variableDeclaration = lookupQualifiedName(ownerScope, name.toString(), null, false, LookupType.UNQUALIFIED);
if( variableDeclaration != null && newSymbol.getType() == variableDeclaration.getType() )
{
if( !newSymbol.isType( TypeInfo.t_type ) ||
(newSymbol.isType( TypeInfo.t_type ) && newSymbol.getTypeSymbol() != variableDeclaration.getTypeSymbol() ) )
{
variableDeclaration.setTypeSymbol( newSymbol );
previouslyDeclared = true;
}
}
}
try
{
ownerScope.addSymbol( newSymbol );
}
catch (ParserSymbolTableException e)
{
handleProblem(e.createProblemID(), name.getFirstToken().getImage() );
}
ASTVariable variable = new ASTVariable( newSymbol, abstractDeclaration, initializerClause, bitfieldExpression, startingOffset, startingLine, nameOffset, nameEndOffset, nameLine, references, constructorExpression, previouslyDeclared );
if( variable.getInitializerClause() != null )
{
variable.getInitializerClause().setOwnerVariableDeclaration(variable);
addDesignatorReferences( (ASTInitializerClause)variable.getInitializerClause() );
}
attachSymbolExtension(newSymbol, variable, !isStatic );
return variable;
}
/**
* @param clause
*/
protected void addDesignatorReferences( ASTInitializerClause clause )
{
if( clause.getKind() == IASTInitializerClause.Kind.DESIGNATED_INITIALIZER_LIST ||
clause.getKind() == IASTInitializerClause.Kind.DESIGNATED_ASSIGNMENT_EXPRESSION )
{
ISymbol variableSymbol = ((ASTVariable)clause.getOwnerVariableDeclaration()).getSymbol();
ISymbol currentSymbol = variableSymbol.getTypeSymbol();
if( currentSymbol == null )
return;
TypeInfo currentTypeInfo = new TypeInfo( currentSymbol.getTypeInfo() );
Iterator designators = clause.getDesignators();
while( designators.hasNext() )
{
IASTDesignator designator = (IASTDesignator)designators.next();
if( designator.getKind() == IASTDesignator.DesignatorKind.FIELD )
{
ISymbol lookup = null;
if( ! ( currentSymbol instanceof IContainerSymbol ) )
break;
try
{
lookup = ((IContainerSymbol)currentSymbol).lookup( designator.fieldName() );
}
catch (ParserSymbolTableException e){
break;
}
if( lookup == null || lookup.getContainingSymbol() != currentSymbol )
break;
try
{
if( lookup != null )
addReference( clause.getReferences(), createReference( lookup, designator.fieldName(), designator.fieldOffset() ));
}
catch (ASTSemanticException e1)
{
// error
}
// we have found the correct field
currentTypeInfo = new TypeInfo( lookup.getTypeInfo() );
if( lookup.getTypeInfo() == null )
break;
currentSymbol = lookup.getTypeSymbol();
}
else if( designator.getKind() == IASTDesignator.DesignatorKind.SUBSCRIPT )
currentTypeInfo.applyOperatorExpressions( SUBSCRIPT );
}
}
if( clause.getKind() == IASTInitializerClause.Kind.DESIGNATED_INITIALIZER_LIST ||
clause.getKind() == IASTInitializerClause.Kind.INITIALIZER_LIST )
{
Iterator subInitializers = clause.getInitializers();
while( subInitializers.hasNext() )
addDesignatorReferences( (ASTInitializerClause)subInitializers.next() );
}
}
protected void setVariableTypeInfoBits(
boolean isAuto,
IASTAbstractDeclaration abstractDeclaration,
boolean isMutable,
boolean isExtern,
boolean isRegister,
boolean isStatic,
ISymbol newSymbol)
{
newSymbol.getTypeInfo().setBit( isMutable, TypeInfo.isMutable );
newSymbol.getTypeInfo().setBit( isAuto, TypeInfo.isAuto );
newSymbol.getTypeInfo().setBit( isExtern, TypeInfo.isExtern );
newSymbol.getTypeInfo().setBit( isRegister, TypeInfo.isRegister );
newSymbol.getTypeInfo().setBit( isStatic, TypeInfo.isStatic );
newSymbol.getTypeInfo().setBit( abstractDeclaration.isConst(), TypeInfo.isConst );
newSymbol.getTypeInfo().setBit( abstractDeclaration.isVolatile(), TypeInfo.isVolatile );
}
protected ISymbol cloneSimpleTypeSymbol(
String name,
IASTAbstractDeclaration abstractDeclaration,
List references) throws ASTSemanticException
{
// assert abstractDeclaration.getTypeSpecifier() != null : this;
ISymbol newSymbol = null;
ISymbol symbolToBeCloned = null;
if( abstractDeclaration.getTypeSpecifier() instanceof ASTSimpleTypeSpecifier )
{
symbolToBeCloned = ((ASTSimpleTypeSpecifier)abstractDeclaration.getTypeSpecifier()).getSymbol();
if( references != null )
{
List absRefs = ((ASTSimpleTypeSpecifier)abstractDeclaration.getTypeSpecifier()).getReferences();
for( int i = 0; i < absRefs.size(); ++i )
{
IASTReference r = (IASTReference) absRefs.get(i);
references.add( cache.getReference( r.getOffset(), r.getReferencedElement() ));
}
}
}
else if( abstractDeclaration.getTypeSpecifier() instanceof ASTClassSpecifier )
{
symbolToBeCloned = pst.newSymbol(name, TypeInfo.t_type);
symbolToBeCloned.setTypeSymbol(((ASTClassSpecifier)abstractDeclaration.getTypeSpecifier()).getSymbol());
}
else if( abstractDeclaration.getTypeSpecifier() instanceof ASTElaboratedTypeSpecifier )
{
ASTElaboratedTypeSpecifier elab = ((ASTElaboratedTypeSpecifier)abstractDeclaration.getTypeSpecifier());
symbolToBeCloned = pst.newSymbol(name, TypeInfo.t_type);
symbolToBeCloned.setTypeSymbol(elab.getSymbol());
if( elab.getSymbol() != null && references != null )
addReference( references, createReference( elab.getSymbol(), elab.getName(), elab.getNameOffset()) );
}
else if ( abstractDeclaration.getTypeSpecifier() instanceof ASTEnumerationSpecifier )
{
symbolToBeCloned = pst.newSymbol( name, TypeInfo.t_type );
symbolToBeCloned.setTypeSymbol(((ASTEnumerationSpecifier)abstractDeclaration.getTypeSpecifier()).getSymbol());
}
if( symbolToBeCloned != null ){
newSymbol = (ISymbol) symbolToBeCloned.clone();
newSymbol.setName( name );
}
return newSymbol;
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.parser.ast.IASTFactory#createField(org.eclipse.cdt.core.parser.ast.IASTScope, java.lang.String, boolean, org.eclipse.cdt.core.parser.ast.IASTInitializerClause, org.eclipse.cdt.core.parser.ast.IASTExpression, org.eclipse.cdt.core.parser.ast.IASTAbstractDeclaration, boolean, boolean, boolean, boolean, int, int, org.eclipse.cdt.core.parser.ast.ASTAccessVisibility)
*/
public IASTField createField(
IASTScope scope,
ITokenDuple name,
boolean isAuto,
IASTInitializerClause initializerClause,
IASTExpression bitfieldExpression,
IASTAbstractDeclaration abstractDeclaration,
boolean isMutable,
boolean isExtern,
boolean isRegister,
boolean isStatic,
int startingOffset,
int startingLine,
int nameOffset, int nameEndOffset, int nameLine, IASTExpression constructorExpression, ASTAccessVisibility visibility) throws ASTSemanticException
{
return createField(scope, name,isAuto, initializerClause, bitfieldExpression, abstractDeclaration, isMutable, isExtern,
isRegister, isStatic, startingOffset, startingLine, nameOffset, nameEndOffset, nameLine, constructorExpression, visibility, null);
}
public IASTField createField(
IASTScope scope,
ITokenDuple name,
boolean isAuto,
IASTInitializerClause initializerClause,
IASTExpression bitfieldExpression,
IASTAbstractDeclaration abstractDeclaration,
boolean isMutable,
boolean isExtern,
boolean isRegister,
boolean isStatic,
int startingOffset,
int startingLine,
int nameOffset,
int nameEndOffset,
int nameLine,
IASTExpression constructorExpression, ASTAccessVisibility visibility, List references) throws ASTSemanticException
{
IContainerSymbol ownerScope = scopeToSymbol( scope );
String image = ( name != null ) ? name.toString() : EMPTY_STRING;
if(references == null)
references = new ArrayList();
ISymbol newSymbol = cloneSimpleTypeSymbol(image, abstractDeclaration, references);
if( newSymbol == null )
handleProblem( IProblem.SEMANTICS_RELATED, image );
setVariableTypeInfoBits(
isAuto,
abstractDeclaration,
isMutable,
isExtern,
isRegister,
isStatic,
newSymbol);
setPointerOperators( newSymbol, abstractDeclaration.getPointerOperators(), abstractDeclaration.getArrayModifiers() );
newSymbol.setIsForwardDeclaration(isStatic);
boolean previouslyDeclared = false;
if( !isStatic && !image.equals( EMPTY_STRING ) ){
ISymbol fieldDeclaration = lookupQualifiedName(ownerScope, image, null, false, LookupType.FORDEFINITION);
if( fieldDeclaration != null && newSymbol.getType() == fieldDeclaration.getType() )
{
if( !newSymbol.isType( TypeInfo.t_type ) ||
(newSymbol.isType( TypeInfo.t_type ) && newSymbol.getTypeSymbol() != fieldDeclaration.getTypeSymbol() ) )
{
previouslyDeclared = true;
fieldDeclaration.setTypeSymbol( newSymbol );
// // set the definition visibility = declaration visibility
// ASTReference reference = (ASTReference) fieldReferences.iterator().next();
visibility = ((IASTField)fieldDeclaration.getASTExtension().getPrimaryDeclaration()).getVisiblity();
}
}
}
try
{
ownerScope.addSymbol( newSymbol );
}
catch (ParserSymbolTableException e)
{
handleProblem(e.createProblemID(), image );
}
ASTField field = new ASTField( newSymbol, abstractDeclaration, initializerClause, bitfieldExpression, startingOffset, startingLine, nameOffset, nameEndOffset, nameLine, references, previouslyDeclared, constructorExpression, visibility );
attachSymbolExtension(newSymbol, field, !isStatic );
return field;
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.parser.ast.IASTFactory#createTemplateDeclaration(org.eclipse.cdt.core.parser.ast.IASTScope, java.util.List, boolean, int)
*/
public IASTTemplateDeclaration createTemplateDeclaration(
IASTScope scope,
List templateParameters,
boolean exported,
int startingOffset, int startingLine) throws ASTSemanticException
{
ITemplateSymbol template = pst.newTemplateSymbol( ParserSymbolTable.EMPTY_NAME );
// the lookup requires a list of type infos
// instead of a list of IASTParameterDeclaration
Iterator iter = templateParameters.iterator();
while (iter.hasNext()){
ASTTemplateParameter param = (ASTTemplateParameter)iter.next();
try {
template.addTemplateParameter( param.getSymbol() );
} catch (ParserSymbolTableException e) {
handleProblem( e.createProblemID(), param.getName(), startingOffset, -1, startingLine, true );
}
}
ASTTemplateDeclaration ast = new ASTTemplateDeclaration( template, scope, templateParameters);
ast.setStartingOffsetAndLineNumber( startingOffset, startingLine );
attachSymbolExtension( template, ast, false );
return ast;
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.parser.ast.IASTFactory#createTemplateParameter(org.eclipse.cdt.core.parser.ast.IASTTemplateParameter.ParamKind, java.lang.String, java.lang.String, org.eclipse.cdt.core.parser.ast.IASTParameterDeclaration, java.util.List)
*/
public IASTTemplateParameter createTemplateParameter(
ParamKind kind,
String identifier,
IASTTypeId defaultValue,
IASTParameterDeclaration parameter,
List parms,
IASTCodeScope parameterScope,
int startingOffset, int startingLine, int nameOffset, int nameEndOffset, int nameLine, int endingOffset, int endingLine ) throws ASTSemanticException
{
ISymbol symbol = null;
if( kind == ParamKind.TEMPLATE_LIST ){
ITemplateSymbol template = pst.newTemplateSymbol( identifier );
template.setType( TypeInfo.t_templateParameter );
template.getTypeInfo().setTemplateParameterType( TypeInfo.t_template );
Iterator iter = parms.iterator();
while (iter.hasNext()){
ASTTemplateParameter param = (ASTTemplateParameter)iter.next();
try {
template.addTemplateParameter( param.getSymbol() );
} catch (ParserSymbolTableException e) {
handleProblem( e.createProblemID(), param.getName(), param.getStartingOffset(), param.getEndingOffset(), param.getStartingLine(), true ); //$NON-NLS-1$
}
}
symbol = template;
} else {
if( kind == ParamKind.CLASS || kind == ParamKind.TYPENAME ){
symbol = pst.newSymbol( identifier, TypeInfo.t_templateParameter );
symbol.getTypeInfo().setTemplateParameterType( TypeInfo.t_typeName );
} else /*ParamKind.PARAMETER*/ {
symbol = cloneSimpleTypeSymbol( parameter.getName(), parameter, null );
symbol.getTypeInfo().setTemplateParameterType( symbol.getType() );
symbol.setType( TypeInfo.t_templateParameter );
}
}
IContainerSymbol codeScope = ((ASTCodeScope)parameterScope).getContainerSymbol();
try {
codeScope.addSymbol( symbol );
} catch (ParserSymbolTableException e) {
}
if( defaultValue != null ){
try {
symbol.getTypeInfo().setDefault( defaultValue.getTypeSymbol().getTypeInfo() );
} catch (ASTNotImplementedException e1) {
}
}
ASTTemplateParameter ast = new ASTTemplateParameter( symbol, defaultValue, parameter, parms, startingOffset, startingLine, nameOffset, nameEndOffset, nameLine, endingOffset, endingLine );
attachSymbolExtension( symbol, ast, false );
return ast;
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.parser.ast.IASTFactory#createTemplateInstantiation(org.eclipse.cdt.core.parser.ast.IASTScope, int)
*/
public IASTTemplateInstantiation createTemplateInstantiation(
IASTScope scope,
int startingOffset, int startingLine)
{
ASTTemplateInstantiation inst = new ASTTemplateInstantiation( scope );
inst.setStartingOffsetAndLineNumber( startingOffset, startingLine );
return inst;
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.parser.ast.IASTFactory#createTemplateSpecialization(org.eclipse.cdt.core.parser.ast.IASTScope, int)
*/
public IASTTemplateSpecialization createTemplateSpecialization(
IASTScope scope,
int startingOffset, int startingLine)
{
ITemplateSymbol template = pst.newTemplateSymbol( ParserSymbolTable.EMPTY_NAME );
ASTTemplateSpecialization ast = new ASTTemplateSpecialization( template, scope );
ast.setStartingOffsetAndLineNumber( startingOffset, startingLine );
attachSymbolExtension( template, ast, false );
return ast;
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.parser.ast.IASTFactory#createTypedef(org.eclipse.cdt.core.parser.ast.IASTScope, java.lang.String, org.eclipse.cdt.core.parser.ast.IASTAbstractDeclaration, int, int)
*/
public IASTTypedefDeclaration createTypedef(
IASTScope scope,
String name,
IASTAbstractDeclaration mapping,
int startingOffset,
int startingLine, int nameOffset, int nameEndOffset, int nameLine) throws ASTSemanticException
{
IContainerSymbol containerSymbol = scopeToSymbol(scope);
ISymbol typeSymbol = cloneSimpleTypeSymbol( name, mapping, null );
if( typeSymbol == null )
handleProblem( scope, IProblem.SEMANTICS_RELATED, name, nameOffset, nameEndOffset, nameLine, true );
setPointerOperators( typeSymbol, mapping.getPointerOperators(), mapping.getArrayModifiers() );
if( typeSymbol.getType() != TypeInfo.t_type ){
ISymbol newSymbol = pst.newSymbol( name, TypeInfo.t_type);
newSymbol.getTypeInfo().setBit( true,TypeInfo.isTypedef );
newSymbol.setTypeSymbol( typeSymbol );
typeSymbol = newSymbol;
} else {
typeSymbol.getTypeInfo().setBit( true,TypeInfo.isTypedef );
}
List references = new ArrayList();
if( mapping.getTypeSpecifier() instanceof ASTSimpleTypeSpecifier )
{
List mappingReferences = ((ASTSimpleTypeSpecifier)mapping.getTypeSpecifier()).getReferences();
if( mappingReferences != null && !mappingReferences.isEmpty() )
{
for( int i = 0; i < mappingReferences.size(); ++i )
{
IASTReference r = (IASTReference) mappingReferences.get(i);
references.add( cache.getReference(r.getOffset(), r.getReferencedElement()));
}
}
}
try
{
containerSymbol.addSymbol( typeSymbol );
}
catch (ParserSymbolTableException e)
{
handleProblem(e.createProblemID(), name );
}
ASTTypedef d = new ASTTypedef( typeSymbol, mapping, startingOffset, startingLine, nameOffset, nameEndOffset, nameLine, references );
attachSymbolExtension(typeSymbol, d, true );
return d;
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.parser.ast.IASTFactory#createTypeSpecDeclaration(org.eclipse.cdt.core.parser.ast.IASTScope, org.eclipse.cdt.core.parser.ast.IASTTypeSpecifier, org.eclipse.cdt.core.parser.ast.IASTTemplate, int, int)
*/
public IASTAbstractTypeSpecifierDeclaration createTypeSpecDeclaration(
IASTScope scope,
IASTTypeSpecifier typeSpecifier,
IASTTemplate template,
int startingOffset,
int startingLine, int endingOffset, int endingLine, boolean isFriend)
{
return new ASTAbstractTypeSpecifierDeclaration( scopeToSymbol(scope), typeSpecifier, template, startingOffset, startingLine, endingOffset, endingLine, isFriend);
}
public IASTElaboratedTypeSpecifier createElaboratedTypeSpecifier(IASTScope scope, ASTClassKind kind, ITokenDuple name, int startingOffset, int startingLine, int endOffset, int endingLine, boolean isForewardDecl, boolean isFriend) throws ASTSemanticException
{
IContainerSymbol currentScopeSymbol = scopeToSymbol(scope);
IContainerSymbol originalScope = currentScopeSymbol;
TypeInfo.eType pstType = classKindToTypeInfo(kind);
List references = new ArrayList();
IToken nameToken = name.getFirstToken();
String newSymbolName = EMPTY_STRING;
List templateIdArgList = null;
boolean isTemplateId = false;
if (name.getSegmentCount() != 1) // qualified name
{
ITokenDuple containerSymbolName = name.getLeadingSegments();
if( containerSymbolName == null ){
//null means globally qualified
currentScopeSymbol = currentScopeSymbol.getSymbolTable().getCompilationUnit();
} else {
currentScopeSymbol = (IContainerSymbol) lookupQualifiedName(
currentScopeSymbol, containerSymbolName, references, true);
}
if (currentScopeSymbol == null)
handleProblem(IProblem.SEMANTIC_NAME_NOT_FOUND,
containerSymbolName.toString(), containerSymbolName
.getFirstToken().getOffset(),
containerSymbolName.getLastToken().getEndOffset(),
containerSymbolName.getLastToken().getLineNumber(), true);
nameToken = name.getLastSegment().getFirstToken();
}
//template-id
List[] array = name.getTemplateIdArgLists();
if (array != null) {
isTemplateId = true;
templateIdArgList = array[array.length - 1];
}
newSymbolName = nameToken.getImage();
ISymbol checkSymbol = null;
if (!isTemplateId) {
try {
if (isFriend) {
checkSymbol = ((IDerivableContainerSymbol) currentScopeSymbol)
.lookupForFriendship(newSymbolName);
} else {
checkSymbol = currentScopeSymbol.elaboratedLookup(pstType,
newSymbolName);
}
} catch (ParserSymbolTableException e) {
handleProblem(e.createProblemID(), nameToken.getImage(),
nameToken.getOffset(), nameToken.getEndOffset(),
nameToken.getLineNumber(), true);
}
}
List args = null;
if (isTemplateId) {
args = getTemplateArgList(templateIdArgList);
}
if (scope instanceof IASTTemplateInstantiation) {
if (isTemplateId) {
checkSymbol = pst.newDerivableContainerSymbol(newSymbolName,
pstType);
try {
currentScopeSymbol.addTemplateId(checkSymbol, args);
} catch (ParserSymbolTableException e) {
handleProblem(e.createProblemID(), nameToken.getImage(),
nameToken.getOffset(), nameToken.getEndOffset(),
nameToken.getLineNumber(), true);
}
} else {
handleProblem(IProblem.SEMANTIC_INVALID_TEMPLATE, nameToken
.getImage());
}
checkSymbol = ((ASTTemplateInstantiation) scope)
.getInstanceSymbol();
} else if (checkSymbol == null) {
checkSymbol = pst.newDerivableContainerSymbol(newSymbolName,
pstType);
checkSymbol.setIsForwardDeclaration(true);
try {
if (isFriend) {
((IDerivableContainerSymbol) originalScope).addFriend(checkSymbol);
} else {
if (!isTemplateId)
currentScopeSymbol.addSymbol(checkSymbol);
else
currentScopeSymbol.addTemplateId(checkSymbol, args);
}
} catch (ParserSymbolTableException e1) {
handleProblem(e1.createProblemID(), nameToken.getImage(),
nameToken.getOffset(), nameToken.getEndOffset(),
nameToken.getLineNumber(), true);
}
ASTElaboratedTypeSpecifier elab = new ASTElaboratedTypeSpecifier(
checkSymbol, kind, startingOffset, startingLine, name
.getFirstToken().getOffset(), name.getLastToken()
.getEndOffset(), name.getLastToken()
.getLineNumber(), endOffset, endingLine,
references, isForewardDecl);
attachSymbolExtension(checkSymbol, elab, !isForewardDecl);
} else if (isFriend) {
((IDerivableContainerSymbol) originalScope).addFriend(checkSymbol);
}
if (checkSymbol != null) {
if (scope instanceof IASTTemplateInstantiation) {
addReference(references, createReference(checkSymbol,
newSymbolName, nameToken.getOffset()));
}
if( checkSymbol instanceof ITemplateSymbol ){
checkSymbol = ((ITemplateSymbol)checkSymbol).getTemplatedSymbol();
}
if (checkSymbol.getASTExtension().getPrimaryDeclaration() instanceof IASTClassSpecifier
|| checkSymbol.getASTExtension().getPrimaryDeclaration() instanceof IASTEnumerationSpecifier) {
ASTElaboratedTypeSpecifier elab = new ASTElaboratedTypeSpecifier(
checkSymbol, kind, startingOffset, startingLine, name
.getFirstToken().getOffset(), name
.getLastToken().getEndOffset(), name
.getLastToken().getLineNumber(), endOffset,
endingLine, references, isForewardDecl);
attachSymbolExtension(checkSymbol, elab, !isForewardDecl);
return elab;
}
if (checkSymbol.getASTExtension().getPrimaryDeclaration() instanceof IASTElaboratedTypeSpecifier)
return (IASTElaboratedTypeSpecifier) checkSymbol
.getASTExtension().getPrimaryDeclaration();
} else {
handleProblem(IProblem.SEMANTIC_NAME_NOT_FOUND, newSymbolName,
nameToken.getOffset(), nameToken.getEndOffset(), nameToken
.getLineNumber(), true);
}
// assert false : this;
return null;
}
protected ParserSymbolTable pst;
/*
* (non-Javadoc)
*
* @see org.eclipse.cdt.core.parser.ast.IASTFactory#createNamespaceAlias(org.eclipse.cdt.core.parser.ast.IASTScope,
* java.lang.String, org.eclipse.cdt.core.parser.ITokenDuple, int, int,
* int)
*/
public IASTNamespaceAlias createNamespaceAlias(IASTScope scope, String identifier, ITokenDuple alias, int startingOffset, int startingLine, int nameOffset, int nameEndOffset, int nameLine, int endOffset, int endingLine) throws ASTSemanticException
{
IContainerSymbol startingSymbol = scopeToSymbol(scope);
List references = new ArrayList();
ISymbol namespaceSymbol = lookupQualifiedName( startingSymbol, alias, references, true );
if( namespaceSymbol.getType() != TypeInfo.t_namespace )
handleProblem( IProblem.SEMANTIC_INVALID_OVERLOAD, alias.toString(), startingOffset, endOffset, startingLine, true );
ISymbol newSymbol = pst.newContainerSymbol( identifier, TypeInfo.t_namespace );
newSymbol.setTypeSymbol( namespaceSymbol );
try
{
startingSymbol.addSymbol( newSymbol );
}
catch (ParserSymbolTableException e)
{
handleProblem( e.createProblemID(), identifier, startingOffset, endOffset, startingLine, true );
}
ASTNamespaceAlias astAlias = new ASTNamespaceAlias(
newSymbol, alias.toString(), (IASTNamespaceDefinition)namespaceSymbol.getASTExtension().getPrimaryDeclaration(),
startingOffset, startingLine, nameOffset, nameEndOffset, nameLine, endOffset, endingLine, references );
attachSymbolExtension( newSymbol, astAlias, true );
return astAlias;
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.parser.ast.IASTFactory#createNewCodeBlock(org.eclipse.cdt.core.parser.ast.IASTScope)
*/
public IASTCodeScope createNewCodeBlock(IASTScope scope) {
IContainerSymbol symbol = scopeToSymbol( scope );
IContainerSymbol newScope = pst.newContainerSymbol(EMPTY_STRING, TypeInfo.t_block);
newScope.setContainingSymbol(symbol);
newScope.setIsTemplateMember( symbol.isTemplateMember() );
ASTCodeScope codeScope = new ASTCodeScope( newScope );
attachSymbolExtension( newScope, codeScope, true );
return codeScope;
}
public IASTScope getDeclaratorScope(IASTScope scope, ITokenDuple duple){
if( duple != null && duple.getSegmentCount() > 1){
IContainerSymbol ownerScope = scopeToSymbol( scope );
ISymbol symbol;
try {
symbol = lookupQualifiedName( ownerScope, duple.getLeadingSegments(), null, false, LookupType.FORDEFINITION );
} catch (ASTSemanticException e) {
return scope;
}
IContainerSymbol parentScope = null;
if( symbol instanceof IContainerSymbol )
parentScope = (IContainerSymbol) symbol;
else if( symbol instanceof IDeferredTemplateInstance )
parentScope = ((IDeferredTemplateInstance) symbol).getTemplate().getTemplatedSymbol();
if( parentScope != null && parentScope.getASTExtension() != null ){
if( scope instanceof IASTTemplateDeclaration || scope instanceof IASTTemplateSpecialization ){
symbol = scopeToSymbol( scope );
if( symbol instanceof ITemplateFactory ){
symbol.setContainingSymbol( parentScope );
}
return scope;
}
return (IASTScope)parentScope.getASTExtension().getPrimaryDeclaration();
}
}
return scope;
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.parser.ast.IASTFactory#queryIsTypeName(org.eclipse.cdt.core.parser.ITokenDuple)
*/
public boolean queryIsTypeName(IASTScope scope, ITokenDuple nameInQuestion) {
ISymbol lookupSymbol = null;
try {
lookupSymbol =
lookupQualifiedName(
scopeToSymbol(scope),
nameInQuestion,
null,
false);
} catch (ASTSemanticException e) {
// won't get thrown
}
if( lookupSymbol == null ) return false;
if( lookupSymbol.isType( TypeInfo.t_type, TypeInfo.t_enumeration ) ||
(lookupSymbol.isType( TypeInfo.t_templateParameter ) && lookupSymbol.getTypeInfo().getTemplateParameterType() == TypeInfo.t_typeName ) ||
(lookupSymbol.getASTExtension() != null && lookupSymbol.getASTExtension().getPrimaryDeclaration() instanceof IASTTypedefDeclaration ) )
{
return true;
}
return false;
}
public IASTParameterDeclaration createParameterDeclaration(boolean isConst, boolean isVolatile, IASTTypeSpecifier typeSpecifier, List pointerOperators, List arrayModifiers, List parameters, ASTPointerOperator pointerOp, String parameterName, IASTInitializerClause initializerClause, int startingOffset, int startingLine, int nameOffset, int nameEndOffset, int nameLine, int endingOffset, int endingLine)
{
return new ASTParameterDeclaration( null, isConst, isVolatile, typeSpecifier, pointerOperators, arrayModifiers, parameters, pointerOp, parameterName, initializerClause, startingOffset, startingLine, nameOffset, nameEndOffset, nameLine, endingOffset, endingLine );
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.parser.ast.IASTFactory#createTypeId(org.eclipse.cdt.core.parser.ast.IASTSimpleTypeSpecifier.Type, org.eclipse.cdt.core.parser.ITokenDuple, java.util.List, java.util.List)
*/
public IASTTypeId createTypeId(IASTScope scope, Type kind, boolean isConst, boolean isVolatile, boolean isShort,
boolean isLong, boolean isSigned, boolean isUnsigned, boolean isTypename, ITokenDuple name, List pointerOps, List arrayMods, String completeSignature) throws ASTSemanticException
{
if( kind != Type.CLASS_OR_TYPENAME )
{
IASTTypeId check = (IASTTypeId) typeIdCache.get( completeSignature );
if( check != null )
return check;
}
ASTTypeId result =
new ASTTypeId( kind, name, pointerOps, arrayMods, completeSignature,
isConst, isVolatile, isUnsigned, isSigned, isShort, isLong, isTypename );
result.setTypeSymbol( createSymbolForTypeId( scope, result ) );
if( kind != Type.CLASS_OR_TYPENAME )
typeIdCache.put( completeSignature, result );
return result;
}
/**
* @param id
* @return
*/
public static TypeInfo.eType getTypeKind(IASTTypeId id)
{
IASTSimpleTypeSpecifier.Type type = id.getKind();
if( type == IASTSimpleTypeSpecifier.Type.BOOL )
return TypeInfo.t_bool;
else if( type == IASTSimpleTypeSpecifier.Type._BOOL )
return TypeInfo.t__Bool;
else if( type == IASTSimpleTypeSpecifier.Type.CHAR )
return TypeInfo.t_char;
else if ( type == IASTSimpleTypeSpecifier.Type.WCHAR_T )
return TypeInfo.t_wchar_t;
else if( type == IASTSimpleTypeSpecifier.Type.DOUBLE )
return TypeInfo.t_double;
else if( type == IASTSimpleTypeSpecifier.Type.FLOAT )
return TypeInfo.t_float;
else if( type == IASTSimpleTypeSpecifier.Type.INT )
return TypeInfo.t_int;
else if( type == IASTSimpleTypeSpecifier.Type.VOID )
return TypeInfo.t_void;
else if( id.isShort() || id.isLong() || id.isUnsigned() || id.isSigned() )
return TypeInfo.t_int;
else
return TypeInfo.t_type;
}
protected ISymbol createSymbolForTypeId( IASTScope scope, IASTTypeId id ) throws ASTSemanticException
{
if( id == null ) return null;
ASTTypeId typeId = (ASTTypeId)id;
ISymbol result = pst.newSymbol( EMPTY_STRING, CompleteParseASTFactory.getTypeKind(id));
result.getTypeInfo().setBit( id.isConst(), TypeInfo.isConst );
result.getTypeInfo().setBit( id.isVolatile(), TypeInfo.isVolatile );
result.getTypeInfo().setBit( id.isShort(), TypeInfo.isShort);
result.getTypeInfo().setBit( id.isLong(), TypeInfo.isLong);
result.getTypeInfo().setBit( id.isUnsigned(), TypeInfo.isUnsigned);
result.getTypeInfo().setBit( id.isSigned(), TypeInfo.isSigned );
List refs = new ArrayList();
if( result.getType() == TypeInfo.t_type )
{
ISymbol typeSymbol = lookupQualifiedName( scopeToSymbol(scope), typeId.getTokenDuple(), refs, true );
if( typeSymbol == null /*|| typeSymbol.getType() == TypeInfo.t_type*/ )
{
freeReferences( refs );
handleProblem( scope, IProblem.SEMANTIC_INVALID_TYPE, id.getTypeOrClassName() );
}
result.setTypeSymbol( typeSymbol );
typeId.addReferences( refs, cache );
}
setPointerOperators( result, id.getPointerOperators(), id.getArrayModifiers() );
return result;
}
/**
* @param refs
*/
private void freeReferences(List refs) {
if( refs == null || refs.isEmpty() ) return;
for( int i =0; i < refs.size(); ++i)
cache.returnReference((IASTReference) refs.get(i));
refs.clear();
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.parser.ast.IASTFactory#signalEndOfClassSpecifier(org.eclipse.cdt.core.parser.ast.IASTClassSpecifier)
*/
public void signalEndOfClassSpecifier(IASTClassSpecifier astClassSpecifier)
{
ASTClassSpecifier astImplementation = (ASTClassSpecifier)astClassSpecifier;
try
{
((IDerivableContainerSymbol)(astImplementation).getSymbol()).addCopyConstructor();
}
catch (ParserSymbolTableException e)
{
// do nothing, this is best effort
}
astImplementation.setProcessingUnresolvedReferences( true );
Iterator i = astImplementation.getUnresolvedReferences();
List references = new ArrayList();
while( i.hasNext() )
{
UnresolvedReferenceDuple duple = (UnresolvedReferenceDuple) i.next();
try
{
lookupQualifiedName( duple.getScope(), duple.getName(), references, false );
}
catch( ASTSemanticException ase )
{
}
}
astImplementation.setProcessingUnresolvedReferences( false );
if( ! references.isEmpty() )
astImplementation.setExtraReferences( references, cache );
}
public IASTInitializerClause createInitializerClause(IASTScope scope, IASTInitializerClause.Kind kind, IASTExpression assignmentExpression, List initializerClauses, List designators)
{
return new ASTInitializerClause( kind, assignmentExpression, initializerClauses, designators );
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.parser.ast.IASTFactory#lookupSymbolInContext(org.eclipse.cdt.core.parser.ast.IASTScope, org.eclipse.cdt.core.parser.ITokenDuple)
*/
public IASTNode lookupSymbolInContext(IASTScope scope, ITokenDuple duple, IASTNode reference) throws ASTNotImplementedException {
ISymbol s = null;
if( reference == null ) {
try {
s = lookupQualifiedName( scopeToSymbol( scope ), duple, null, false );
} catch (ASTSemanticException e) {
}
}
else
{
if( reference instanceof ASTExpression )
{
ASTExpression expression = (ASTExpression) reference;
if( expression.getExpressionKind() == IASTExpression.Kind.ID_EXPRESSION )
{
try {
s = lookupQualifiedName( scopeToSymbol( scope ), duple, null, false );
} catch (ASTSemanticException e1) {
}
}
else if( expression.getExpressionKind() == IASTExpression.Kind.NEW_NEWTYPEID ||
expression.getExpressionKind() == IASTExpression.Kind.NEW_TYPEID )
{
IContainerSymbol classSymbol = null;
try {
classSymbol = (IContainerSymbol) lookupQualifiedName(scopeToSymbol( scope ), duple, null, false );
} catch (ASTSemanticException e) {
}
if( classSymbol != null && classSymbol.getTypeInfo().checkBit( TypeInfo.isTypedef ) ){
TypeInfo info = classSymbol.getTypeInfo().getFinalType( pst.getTypeInfoProvider() );
classSymbol = (IContainerSymbol) info.getTypeSymbol();
pst.getTypeInfoProvider().returnTypeInfo( info );
}
if( classSymbol == null || ! (classSymbol instanceof IDerivableContainerSymbol ) ){
return null;
}
List parameters = new LinkedList();
Iterator newInitializerExpressions = expression.getNewExpressionDescriptor().getNewInitializerExpressions();
if( newInitializerExpressions.hasNext() )
{
ASTExpression expressionList = (ASTExpression) newInitializerExpressions.next();
while( expressionList != null ){
parameters.add( expressionList.getResultType().getResult() );
expressionList = (ASTExpression) expressionList.getRHSExpression();
}
}
try {
s = ((IDerivableContainerSymbol)classSymbol).lookupConstructor( parameters );
} catch (ParserSymbolTableException e1) {
return null;
}
}
else if( expression.getExpressionKind() == Kind.POSTFIX_FUNCTIONCALL )
{
try {
ISymbol symbol = getExpressionSymbol( scope, expression.getExpressionKind(), expression.getLHSExpression(), expression.getRHSExpression(), null, null );
if( symbol == null) return null;
return symbol.getASTExtension().getPrimaryDeclaration();
} catch (ASTSemanticException e) {
return null;
}
}
else
{
ASTExpression ownerExpression = expression.findOwnerExpressionForIDExpression( duple );
if( ownerExpression == null ) return null;
if( ownerExpression.getExpressionKind().isPostfixMemberReference() )
{
try {
s = lookupQualifiedName( getSearchScope(ownerExpression.getExpressionKind(), ownerExpression.getLHSExpression(), scopeToSymbol(scope)), duple, null, false );
} catch (ASTSemanticException e) {
return null;
}
}
else
{
try {
s = lookupQualifiedName( scopeToSymbol( scope ), duple, null, false );
} catch (ASTSemanticException e1) {
}
}
}
}
}
if ( s == null ) return null;
return s.getASTExtension().getPrimaryDeclaration();
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.parser.ast.IASTFactory#getNodeForThisExpression(org.eclipse.cdt.core.parser.ast.IASTExpression)
*/
public IASTNode expressionToMostPreciseASTNode(IASTScope scope, IASTExpression expression) {
if( expression == null ) return null;
if( expression.getExpressionKind() == IASTExpression.Kind.ID_EXPRESSION )
{
if( expression instanceof ASTExpression)
{
try {
return lookupSymbolInContext(scope, ((ASTIdExpression)expression).getIdExpressionTokenDuple(), null);
} catch (ASTNotImplementedException e) {
// assert false : e;
}
}
}
return expression;
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.parser.ast.IASTFactory#validateIndirectMemberOperation(org.eclipse.cdt.core.parser.ast.IASTNode)
*/
public boolean validateIndirectMemberOperation(IASTNode node) {
List pointerOps = null;
TypeInfoProvider provider = pst.getTypeInfoProvider();
TypeInfo typeInfo = null;
if( ( node instanceof ISymbolOwner ) )
{
ISymbol symbol = ((ISymbolOwner) node).getSymbol();
typeInfo = symbol.getTypeInfo().getFinalType( provider );
pointerOps = typeInfo.getPtrOperators();
provider.returnTypeInfo( typeInfo );
}
else if( node instanceof ASTExpression )
{
ISymbol typeSymbol = ((ASTExpression)node).getResultType().getResult().getTypeSymbol();
if( typeSymbol != null ){
typeInfo = typeSymbol.getTypeInfo().getFinalType( provider );
pointerOps = typeInfo.getPtrOperators();
provider.returnTypeInfo( typeInfo );
}
}
else
return false;
if( pointerOps == null || pointerOps.isEmpty() ) return false;
TypeInfo.PtrOp lastOperator = (PtrOp) pointerOps.get( pointerOps.size() - 1 );
if( lastOperator.getType() == TypeInfo.PtrOp.t_array || lastOperator.getType() == TypeInfo.PtrOp.t_pointer ) return true;
return false;
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.parser.ast.IASTFactory#validateDirectMemberOperation(org.eclipse.cdt.core.parser.ast.IASTNode)
*/
public boolean validateDirectMemberOperation(IASTNode node) {
List pointerOps = null;
if( ( node instanceof ISymbolOwner ) )
{
ISymbol symbol = ((ISymbolOwner) node).getSymbol();
TypeInfoProvider provider = pst.getTypeInfoProvider();
TypeInfo info = symbol.getTypeInfo().getFinalType( provider );
pointerOps = info.getPtrOperators();
provider.returnTypeInfo( info );
}
else if( node instanceof ASTExpression )
{
ISymbol typeSymbol = ((ASTExpression)node).getResultType().getResult().getTypeSymbol();
if( typeSymbol != null )
{
pointerOps = typeSymbol.getPtrOperators();
}
}
else
return false;
if( pointerOps == null || pointerOps.isEmpty() ) return true;
TypeInfo.PtrOp lastOperator = (PtrOp) pointerOps.get( pointerOps.size() - 1 );
if( lastOperator.getType() == TypeInfo.PtrOp.t_reference ) return true;
return false;
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.parser.ast.IASTFactory#constructExpressions(boolean)
*/
public void constructExpressions(boolean flag) {
//ignore
}
/* (non-Javadoc)
* @see org.eclipse.cdt.core.parser.ast.IASTFactory#getReferenceManager()
*/
public IReferenceManager getReferenceManager() {
return cache;
}
/**
* @return
*/
public boolean validateCaches() {
return cache.isBalanced() && (pst.getTypeInfoProvider().numAllocated() == 0);
}
}
| false | true | protected ExpressionResult getExpressionResultType(
IASTScope scope,
Kind kind, IASTExpression lhs,
IASTExpression rhs,
IASTExpression thirdExpression,
IASTTypeId typeId,
String literal,
ISymbol symbol) throws ASTSemanticException{
TypeInfo info = new TypeInfo();
if( extension.canHandleExpressionKind( kind ))
{
extension.getExpressionResultType( kind, lhs, rhs, typeId );
return new ExpressionResult( info );
}
ExpressionResult result = null;
if( literal != null && !literal.equals(EMPTY_STRING) && kind.isLiteral() ){
info.setDefault( literal );
}
// types that resolve to void
if ((kind == IASTExpression.Kind.PRIMARY_EMPTY)
|| (kind == IASTExpression.Kind.THROWEXPRESSION)
|| (kind == IASTExpression.Kind.POSTFIX_DOT_DESTRUCTOR)
|| (kind == IASTExpression.Kind.POSTFIX_ARROW_DESTRUCTOR)
|| (kind == IASTExpression.Kind.DELETE_CASTEXPRESSION)
|| (kind == IASTExpression.Kind.DELETE_VECTORCASTEXPRESSION)
){
info.setType(TypeInfo.t_void);
result = new ExpressionResult(info);
return result;
}
// types that resolve to int
if ((kind == IASTExpression.Kind.PRIMARY_INTEGER_LITERAL)
|| (kind == IASTExpression.Kind.POSTFIX_SIMPLETYPE_INT)
){
info.setType(TypeInfo.t_int);
result = new ExpressionResult(info);
return result;
}
// size of is always unsigned int
if ((kind == IASTExpression.Kind.UNARY_SIZEOF_TYPEID)
|| (kind == IASTExpression.Kind.UNARY_SIZEOF_UNARYEXPRESSION)
){
info.setType(TypeInfo.t_int);
info.setBit(true, TypeInfo.isUnsigned);
result = new ExpressionResult(info);
return result;
}
// types that resolve to char
if( (kind == IASTExpression.Kind.PRIMARY_CHAR_LITERAL)
|| (kind == IASTExpression.Kind.POSTFIX_SIMPLETYPE_CHAR)){
info.setType(TypeInfo.t_char);
// check that this is really only one literal
if(literal.length() > 1){
// this is a string
info.addPtrOperator(new TypeInfo.PtrOp(TypeInfo.PtrOp.t_pointer));
}
result = new ExpressionResult(info);
return result;
}
// types that resolve to string
if (kind == IASTExpression.Kind.PRIMARY_STRING_LITERAL){
info.setType(TypeInfo.t_char);
info.addPtrOperator(new TypeInfo.PtrOp(TypeInfo.PtrOp.t_pointer));
result = new ExpressionResult(info);
return result;
}
// types that resolve to float
if( (kind == IASTExpression.Kind.PRIMARY_FLOAT_LITERAL)
|| (kind == IASTExpression.Kind.POSTFIX_SIMPLETYPE_FLOAT)){
info.setType(TypeInfo.t_float);
result = new ExpressionResult(info);
return result;
}
// types that resolve to double
if( kind == IASTExpression.Kind.POSTFIX_SIMPLETYPE_DOUBLE){
info.setType(TypeInfo.t_double);
result = new ExpressionResult(info);
return result;
}
// types that resolve to wchar
if(kind == IASTExpression.Kind.POSTFIX_SIMPLETYPE_WCHART){
info.setType(TypeInfo.t_wchar_t);
result = new ExpressionResult(info);
return result;
}
// types that resolve to bool
if( (kind == IASTExpression.Kind.PRIMARY_BOOLEAN_LITERAL)
|| (kind == IASTExpression.Kind.POSTFIX_SIMPLETYPE_BOOL)
|| (kind == IASTExpression.Kind.RELATIONAL_GREATERTHAN)
|| (kind == IASTExpression.Kind.RELATIONAL_GREATERTHANEQUALTO)
|| (kind == IASTExpression.Kind.RELATIONAL_LESSTHAN)
|| (kind == IASTExpression.Kind.RELATIONAL_LESSTHANEQUALTO)
|| (kind == IASTExpression.Kind.EQUALITY_EQUALS)
|| (kind == IASTExpression.Kind.EQUALITY_NOTEQUALS)
|| (kind == IASTExpression.Kind.LOGICALANDEXPRESSION)
|| (kind == IASTExpression.Kind.LOGICALOREXPRESSION)
)
{
info.setType(TypeInfo.t_bool);
result = new ExpressionResult(info);
return result;
}
// short added to a type
if (kind == IASTExpression.Kind.POSTFIX_SIMPLETYPE_SHORT ){
info = addToInfo((ASTExpression)lhs, true, TypeInfo.isShort);
result = new ExpressionResult(info);
return result;
}
// long added to a type
if (kind == IASTExpression.Kind.POSTFIX_SIMPLETYPE_LONG ){
info = addToInfo((ASTExpression)lhs, true, TypeInfo.isLong);
result = new ExpressionResult(info);
return result;
}
// signed added to a type
if (kind == IASTExpression.Kind.POSTFIX_SIMPLETYPE_SIGNED ){
info = addToInfo((ASTExpression)lhs, false, TypeInfo.isUnsigned);
result = new ExpressionResult(info);
return result;
}
// unsigned added to a type
if (kind == IASTExpression.Kind.POSTFIX_SIMPLETYPE_UNSIGNED ){
info = addToInfo((ASTExpression)lhs, true, TypeInfo.isUnsigned);
result = new ExpressionResult(info);
return result;
}
// Id expressions resolve to t_type, symbol already looked up
if( kind == IASTExpression.Kind.ID_EXPRESSION )
{
info.setType(TypeInfo.t_type);
info.setTypeSymbol(symbol);
result = new ExpressionResult(info);
if (symbol == null)
result.setFailedToDereference(true);
return result;
}
// an ampersand implies a pointer operation of type reference
if (kind == IASTExpression.Kind.UNARY_AMPSND_CASTEXPRESSION){
ASTExpression left =(ASTExpression)lhs;
if(left == null)
handleProblem( scope, IProblem.SEMANTIC_MALFORMED_EXPRESSION, null );
info = left.getResultType().getResult();
if ((info != null) && (info.getTypeSymbol() != null)){
info.addOperatorExpression( TypeInfo.OperatorExpression.addressof );
} else
handleProblem( scope, IProblem.SEMANTIC_MALFORMED_EXPRESSION, null );
result = new ExpressionResult(info);
return result;
}
// a star implies a pointer operation of type pointer
if (kind == IASTExpression.Kind.UNARY_STAR_CASTEXPRESSION){
ASTExpression left =(ASTExpression)lhs;
if(left == null)
handleProblem( scope, IProblem.SEMANTIC_MALFORMED_EXPRESSION, null );
info = left.getResultType().getResult();
if ((info != null)&& (info.getTypeSymbol() != null)){
info.addOperatorExpression( TypeInfo.OperatorExpression.indirection );
}else
handleProblem( scope, IProblem.SEMANTIC_MALFORMED_EXPRESSION, null );
result = new ExpressionResult(info);
return result;
}
// subscript
if (kind == IASTExpression.Kind.POSTFIX_SUBSCRIPT){
ASTExpression left =(ASTExpression)lhs;
if(left == null)
handleProblem( scope, IProblem.SEMANTIC_MALFORMED_EXPRESSION, null );
info = left.getResultType().getResult();
if ((info != null))
{
info.addOperatorExpression( TypeInfo.OperatorExpression.subscript );
info = info.getFinalType( null );
}else {
handleProblem( scope, IProblem.SEMANTIC_MALFORMED_EXPRESSION, null );
}
result = new ExpressionResult(info);
return result;
}
// the dot and the arrow resolves to the type of the member
if ((kind == IASTExpression.Kind.POSTFIX_DOT_IDEXPRESSION)
|| (kind == IASTExpression.Kind.POSTFIX_ARROW_IDEXPRESSION)
|| (kind == IASTExpression.Kind.POSTFIX_DOT_TEMPL_IDEXPRESS)
|| (kind == IASTExpression.Kind.POSTFIX_ARROW_TEMPL_IDEXP)
){
if(symbol != null){
info = new TypeInfo(symbol.getTypeInfo());
}
result = new ExpressionResult(info);
return result;
}
// the dot* and the arrow* are the same as dot/arrow + unary star
if ((kind == IASTExpression.Kind.PM_DOTSTAR)
|| (kind == IASTExpression.Kind.PM_ARROWSTAR)
){
ASTExpression right =(ASTExpression)rhs;
if (right == null)
handleProblem( scope, IProblem.SEMANTIC_MALFORMED_EXPRESSION, null );
info = right.getResultType().getResult();
if ((info != null) && (symbol != null)){
info.addOperatorExpression( TypeInfo.OperatorExpression.indirection );
info.setTypeSymbol(symbol);
} else
handleProblem( scope, IProblem.SEMANTIC_MALFORMED_EXPRESSION, null );
result = new ExpressionResult(info);
return result;
}
// this
if (kind == IASTExpression.Kind.PRIMARY_THIS){
if(symbol != null)
{
info.setType(TypeInfo.t_type);
info.setTypeSymbol(symbol);
} else
handleProblem( scope, IProblem.SEMANTIC_MALFORMED_EXPRESSION, null );
result = new ExpressionResult(info);
return result;
}
// conditional
if (kind == IASTExpression.Kind.CONDITIONALEXPRESSION){
ASTExpression right = (ASTExpression)rhs;
ASTExpression third = (ASTExpression)thirdExpression;
if((right != null ) && (third != null)){
TypeInfo rightType =right.getResultType().getResult();
TypeInfo thirdType =third.getResultType().getResult();
if((rightType != null) && (thirdType != null)){
info = conditionalExpressionConversions(rightType, thirdType);
} else
handleProblem( scope, IProblem.SEMANTIC_MALFORMED_EXPRESSION, null );
} else
handleProblem( scope, IProblem.SEMANTIC_MALFORMED_EXPRESSION, null );
result = new ExpressionResult(info);
return result;
}
// new
if( ( kind == IASTExpression.Kind.NEW_TYPEID )
|| ( kind == IASTExpression.Kind.NEW_NEWTYPEID ) )
{
try
{
info = typeId.getTypeSymbol().getTypeInfo();
info.addPtrOperator( new TypeInfo.PtrOp(TypeInfo.PtrOp.t_pointer));
}
catch (ASTNotImplementedException e)
{
// will never happen
}
result = new ExpressionResult(info);
return result;
}
// types that use the usual arithmetic conversions
if((kind == IASTExpression.Kind.MULTIPLICATIVE_MULTIPLY)
|| (kind == IASTExpression.Kind.MULTIPLICATIVE_DIVIDE)
|| (kind == IASTExpression.Kind.MULTIPLICATIVE_MODULUS)
|| (kind == IASTExpression.Kind.ADDITIVE_PLUS)
|| (kind == IASTExpression.Kind.ADDITIVE_MINUS)
|| (kind == IASTExpression.Kind.ANDEXPRESSION)
|| (kind == IASTExpression.Kind.EXCLUSIVEOREXPRESSION)
|| (kind == IASTExpression.Kind.INCLUSIVEOREXPRESSION)
){
ASTExpression left = (ASTExpression)lhs;
ASTExpression right = (ASTExpression)rhs;
if((left != null ) && (right != null)){
TypeInfo leftType =left.getResultType().getResult();
TypeInfo rightType =right.getResultType().getResult();
info = usualArithmeticConversions( scope, leftType, rightType);
}
else
handleProblem( scope, IProblem.SEMANTIC_MALFORMED_EXPRESSION, null );
result = new ExpressionResult(info);
return result;
}
// types that resolve to LHS types
if ((kind == IASTExpression.Kind.PRIMARY_BRACKETED_EXPRESSION)
|| (kind == IASTExpression.Kind.POSTFIX_INCREMENT)
|| (kind == IASTExpression.Kind.POSTFIX_DECREMENT)
|| (kind == IASTExpression.Kind.POSTFIX_TYPEID_EXPRESSION)
|| (kind == IASTExpression.Kind.UNARY_INCREMENT)
|| (kind == IASTExpression.Kind.UNARY_DECREMENT)
|| (kind == IASTExpression.Kind.UNARY_PLUS_CASTEXPRESSION)
|| (kind == IASTExpression.Kind.UNARY_MINUS_CASTEXPRESSION)
|| (kind == IASTExpression.Kind.UNARY_NOT_CASTEXPRESSION)
|| (kind == IASTExpression.Kind.UNARY_TILDE_CASTEXPRESSION)
|| (kind == IASTExpression.Kind.SHIFT_LEFT)
|| (kind == IASTExpression.Kind.SHIFT_RIGHT)
|| (kind == IASTExpression.Kind.ASSIGNMENTEXPRESSION_NORMAL)
|| (kind == IASTExpression.Kind.ASSIGNMENTEXPRESSION_PLUS)
|| (kind == IASTExpression.Kind.ASSIGNMENTEXPRESSION_MINUS)
|| (kind == IASTExpression.Kind.ASSIGNMENTEXPRESSION_MULT)
|| (kind == IASTExpression.Kind.ASSIGNMENTEXPRESSION_DIV)
|| (kind == IASTExpression.Kind.ASSIGNMENTEXPRESSION_MOD)
|| (kind == IASTExpression.Kind.ASSIGNMENTEXPRESSION_LSHIFT)
|| (kind == IASTExpression.Kind.ASSIGNMENTEXPRESSION_RSHIFT)
|| (kind == IASTExpression.Kind.ASSIGNMENTEXPRESSION_AND)
|| (kind == IASTExpression.Kind.ASSIGNMENTEXPRESSION_OR)
|| (kind == IASTExpression.Kind.ASSIGNMENTEXPRESSION_XOR)
){
ASTExpression left = (ASTExpression)lhs;
if(left != null){
info =left.getResultType().getResult();
} else
handleProblem( scope, IProblem.SEMANTIC_MALFORMED_EXPRESSION, null );
result = new ExpressionResult(info);
return result;
}
// the cast changes the types to the type looked up in typeId = symbol
if(( kind == IASTExpression.Kind.CASTEXPRESSION )
|| ( kind == IASTExpression.Kind.POSTFIX_DYNAMIC_CAST )
|| ( kind == IASTExpression.Kind.POSTFIX_STATIC_CAST )
|| ( kind == IASTExpression.Kind.POSTFIX_REINTERPRET_CAST )
|| ( kind == IASTExpression.Kind.POSTFIX_CONST_CAST )
){
try{
info = new TypeInfo(typeId.getTypeSymbol().getTypeInfo());
}catch (ASTNotImplementedException e)
{
// will never happen
}
result = new ExpressionResult(info);
return result;
}
// a list collects all types of left and right hand sides
if(kind == IASTExpression.Kind.EXPRESSIONLIST){
result = new ExpressionResultList();
if(lhs != null){
TypeInfo leftType = ((ASTExpression)lhs).getResultType().getResult();
result.setResult(leftType);
}
if(rhs != null){
TypeInfo rightType = ((ASTExpression)rhs).getResultType().getResult();
result.setResult(rightType);
}
return result;
}
// a function call type is the return type of the function
if(kind == IASTExpression.Kind.POSTFIX_FUNCTIONCALL){
if(symbol != null){
IParameterizedSymbol psymbol = (IParameterizedSymbol) symbol;
ISymbol returnTypeSymbol = psymbol.getReturnType();
if(returnTypeSymbol != null){
info.setType(returnTypeSymbol.getType());
info.setTypeSymbol(returnTypeSymbol);
}else {
// this is call to a constructor
}
}
result = new ExpressionResult(info);
if(symbol == null)
result.setFailedToDereference(true);
return result;
}
// typeid
if( kind == IASTExpression.Kind.POSTFIX_TYPEID_TYPEID )
{
try
{
info = typeId.getTypeSymbol().getTypeInfo();
}
catch (ASTNotImplementedException e)
{
// will not ever happen from within CompleteParseASTFactory
}
result = new ExpressionResult(info);
return result;
}
// typename
if ( ( kind == IASTExpression.Kind.POSTFIX_TYPENAME_IDENTIFIER )
|| ( kind == IASTExpression.Kind.POSTFIX_TYPENAME_TEMPLATEID ) )
{
if(symbol != null){
info.setType(TypeInfo.t_type);
info.setTypeSymbol(symbol);
} else
handleProblem( scope, IProblem.SEMANTIC_MALFORMED_EXPRESSION, null );
result = new ExpressionResult(info);
return result;
}
// assert false : this;
return null;
}
| protected ExpressionResult getExpressionResultType(
IASTScope scope,
Kind kind, IASTExpression lhs,
IASTExpression rhs,
IASTExpression thirdExpression,
IASTTypeId typeId,
String literal,
ISymbol symbol) throws ASTSemanticException{
TypeInfo info = new TypeInfo();
if( extension.canHandleExpressionKind( kind ))
{
extension.getExpressionResultType( kind, lhs, rhs, typeId );
return new ExpressionResult( info );
}
ExpressionResult result = null;
if( literal != null && !literal.equals(EMPTY_STRING) && kind.isLiteral() ){
info.setDefault( literal );
}
// types that resolve to void
if ((kind == IASTExpression.Kind.PRIMARY_EMPTY)
|| (kind == IASTExpression.Kind.THROWEXPRESSION)
|| (kind == IASTExpression.Kind.POSTFIX_DOT_DESTRUCTOR)
|| (kind == IASTExpression.Kind.POSTFIX_ARROW_DESTRUCTOR)
|| (kind == IASTExpression.Kind.DELETE_CASTEXPRESSION)
|| (kind == IASTExpression.Kind.DELETE_VECTORCASTEXPRESSION)
){
info.setType(TypeInfo.t_void);
result = new ExpressionResult(info);
return result;
}
// types that resolve to int
if ((kind == IASTExpression.Kind.PRIMARY_INTEGER_LITERAL)
|| (kind == IASTExpression.Kind.POSTFIX_SIMPLETYPE_INT)
){
info.setType(TypeInfo.t_int);
result = new ExpressionResult(info);
return result;
}
// size of is always unsigned int
if ((kind == IASTExpression.Kind.UNARY_SIZEOF_TYPEID)
|| (kind == IASTExpression.Kind.UNARY_SIZEOF_UNARYEXPRESSION)
){
info.setType(TypeInfo.t_int);
info.setBit(true, TypeInfo.isUnsigned);
result = new ExpressionResult(info);
return result;
}
// types that resolve to char
if( (kind == IASTExpression.Kind.PRIMARY_CHAR_LITERAL)
|| (kind == IASTExpression.Kind.POSTFIX_SIMPLETYPE_CHAR)){
info.setType(TypeInfo.t_char);
// check that this is really only one literal
if(literal.length() > 1){
// this is a string
info.addPtrOperator(new TypeInfo.PtrOp(TypeInfo.PtrOp.t_pointer));
}
result = new ExpressionResult(info);
return result;
}
// types that resolve to string
if (kind == IASTExpression.Kind.PRIMARY_STRING_LITERAL){
info.setType(TypeInfo.t_char);
info.addPtrOperator(new TypeInfo.PtrOp(TypeInfo.PtrOp.t_pointer));
result = new ExpressionResult(info);
return result;
}
// types that resolve to float
if( (kind == IASTExpression.Kind.PRIMARY_FLOAT_LITERAL)
|| (kind == IASTExpression.Kind.POSTFIX_SIMPLETYPE_FLOAT)){
info.setType(TypeInfo.t_float);
result = new ExpressionResult(info);
return result;
}
// types that resolve to double
if( kind == IASTExpression.Kind.POSTFIX_SIMPLETYPE_DOUBLE){
info.setType(TypeInfo.t_double);
result = new ExpressionResult(info);
return result;
}
// types that resolve to wchar
if(kind == IASTExpression.Kind.POSTFIX_SIMPLETYPE_WCHART){
info.setType(TypeInfo.t_wchar_t);
result = new ExpressionResult(info);
return result;
}
// types that resolve to bool
if( (kind == IASTExpression.Kind.PRIMARY_BOOLEAN_LITERAL)
|| (kind == IASTExpression.Kind.POSTFIX_SIMPLETYPE_BOOL)
|| (kind == IASTExpression.Kind.RELATIONAL_GREATERTHAN)
|| (kind == IASTExpression.Kind.RELATIONAL_GREATERTHANEQUALTO)
|| (kind == IASTExpression.Kind.RELATIONAL_LESSTHAN)
|| (kind == IASTExpression.Kind.RELATIONAL_LESSTHANEQUALTO)
|| (kind == IASTExpression.Kind.EQUALITY_EQUALS)
|| (kind == IASTExpression.Kind.EQUALITY_NOTEQUALS)
|| (kind == IASTExpression.Kind.LOGICALANDEXPRESSION)
|| (kind == IASTExpression.Kind.LOGICALOREXPRESSION)
)
{
info.setType(TypeInfo.t_bool);
result = new ExpressionResult(info);
return result;
}
// short added to a type
if (kind == IASTExpression.Kind.POSTFIX_SIMPLETYPE_SHORT ){
info = addToInfo((ASTExpression)lhs, true, TypeInfo.isShort);
result = new ExpressionResult(info);
return result;
}
// long added to a type
if (kind == IASTExpression.Kind.POSTFIX_SIMPLETYPE_LONG ){
info = addToInfo((ASTExpression)lhs, true, TypeInfo.isLong);
result = new ExpressionResult(info);
return result;
}
// signed added to a type
if (kind == IASTExpression.Kind.POSTFIX_SIMPLETYPE_SIGNED ){
info = addToInfo((ASTExpression)lhs, false, TypeInfo.isUnsigned);
result = new ExpressionResult(info);
return result;
}
// unsigned added to a type
if (kind == IASTExpression.Kind.POSTFIX_SIMPLETYPE_UNSIGNED ){
info = addToInfo((ASTExpression)lhs, true, TypeInfo.isUnsigned);
result = new ExpressionResult(info);
return result;
}
// Id expressions resolve to t_type, symbol already looked up
if( kind == IASTExpression.Kind.ID_EXPRESSION )
{
info.setType(TypeInfo.t_type);
info.setTypeSymbol(symbol);
result = new ExpressionResult(info);
if (symbol == null)
result.setFailedToDereference(true);
return result;
}
// an ampersand implies a pointer operation of type reference
if (kind == IASTExpression.Kind.UNARY_AMPSND_CASTEXPRESSION){
ASTExpression left =(ASTExpression)lhs;
if(left == null)
handleProblem( scope, IProblem.SEMANTIC_MALFORMED_EXPRESSION, null );
info = left.getResultType().getResult();
if (info != null){
info.addOperatorExpression( TypeInfo.OperatorExpression.addressof );
info = info.getFinalType( null );
} else
handleProblem( scope, IProblem.SEMANTIC_MALFORMED_EXPRESSION, null );
result = new ExpressionResult(info);
return result;
}
// a star implies a pointer operation of type pointer
if (kind == IASTExpression.Kind.UNARY_STAR_CASTEXPRESSION){
ASTExpression left =(ASTExpression)lhs;
if(left == null)
handleProblem( scope, IProblem.SEMANTIC_MALFORMED_EXPRESSION, null );
info = left.getResultType().getResult();
if (info != null){
info.addOperatorExpression( TypeInfo.OperatorExpression.indirection );
info = info.getFinalType( null );
}else
handleProblem( scope, IProblem.SEMANTIC_MALFORMED_EXPRESSION, null );
result = new ExpressionResult(info);
return result;
}
// subscript
if (kind == IASTExpression.Kind.POSTFIX_SUBSCRIPT){
ASTExpression left =(ASTExpression)lhs;
if(left == null)
handleProblem( scope, IProblem.SEMANTIC_MALFORMED_EXPRESSION, null );
info = left.getResultType().getResult();
if ((info != null))
{
info.addOperatorExpression( TypeInfo.OperatorExpression.subscript );
info = info.getFinalType( null );
}else {
handleProblem( scope, IProblem.SEMANTIC_MALFORMED_EXPRESSION, null );
}
result = new ExpressionResult(info);
return result;
}
// the dot and the arrow resolves to the type of the member
if ((kind == IASTExpression.Kind.POSTFIX_DOT_IDEXPRESSION)
|| (kind == IASTExpression.Kind.POSTFIX_ARROW_IDEXPRESSION)
|| (kind == IASTExpression.Kind.POSTFIX_DOT_TEMPL_IDEXPRESS)
|| (kind == IASTExpression.Kind.POSTFIX_ARROW_TEMPL_IDEXP)
){
if(symbol != null){
info = new TypeInfo(symbol.getTypeInfo());
}
result = new ExpressionResult(info);
return result;
}
// the dot* and the arrow* are the same as dot/arrow + unary star
if ((kind == IASTExpression.Kind.PM_DOTSTAR)
|| (kind == IASTExpression.Kind.PM_ARROWSTAR)
){
ASTExpression right =(ASTExpression)rhs;
if (right == null)
handleProblem( scope, IProblem.SEMANTIC_MALFORMED_EXPRESSION, null );
info = right.getResultType().getResult();
if ((info != null) && (symbol != null)){
info.addOperatorExpression( TypeInfo.OperatorExpression.indirection );
info.setTypeSymbol(symbol);
} else
handleProblem( scope, IProblem.SEMANTIC_MALFORMED_EXPRESSION, null );
result = new ExpressionResult(info);
return result;
}
// this
if (kind == IASTExpression.Kind.PRIMARY_THIS){
if(symbol != null)
{
info.setType(TypeInfo.t_type);
info.setTypeSymbol(symbol);
} else
handleProblem( scope, IProblem.SEMANTIC_MALFORMED_EXPRESSION, null );
result = new ExpressionResult(info);
return result;
}
// conditional
if (kind == IASTExpression.Kind.CONDITIONALEXPRESSION){
ASTExpression right = (ASTExpression)rhs;
ASTExpression third = (ASTExpression)thirdExpression;
if((right != null ) && (third != null)){
TypeInfo rightType =right.getResultType().getResult();
TypeInfo thirdType =third.getResultType().getResult();
if((rightType != null) && (thirdType != null)){
info = conditionalExpressionConversions(rightType, thirdType);
} else
handleProblem( scope, IProblem.SEMANTIC_MALFORMED_EXPRESSION, null );
} else
handleProblem( scope, IProblem.SEMANTIC_MALFORMED_EXPRESSION, null );
result = new ExpressionResult(info);
return result;
}
// new
if( ( kind == IASTExpression.Kind.NEW_TYPEID )
|| ( kind == IASTExpression.Kind.NEW_NEWTYPEID ) )
{
try
{
info = typeId.getTypeSymbol().getTypeInfo();
info.addPtrOperator( new TypeInfo.PtrOp(TypeInfo.PtrOp.t_pointer));
}
catch (ASTNotImplementedException e)
{
// will never happen
}
result = new ExpressionResult(info);
return result;
}
// types that use the usual arithmetic conversions
if((kind == IASTExpression.Kind.MULTIPLICATIVE_MULTIPLY)
|| (kind == IASTExpression.Kind.MULTIPLICATIVE_DIVIDE)
|| (kind == IASTExpression.Kind.MULTIPLICATIVE_MODULUS)
|| (kind == IASTExpression.Kind.ADDITIVE_PLUS)
|| (kind == IASTExpression.Kind.ADDITIVE_MINUS)
|| (kind == IASTExpression.Kind.ANDEXPRESSION)
|| (kind == IASTExpression.Kind.EXCLUSIVEOREXPRESSION)
|| (kind == IASTExpression.Kind.INCLUSIVEOREXPRESSION)
){
ASTExpression left = (ASTExpression)lhs;
ASTExpression right = (ASTExpression)rhs;
if((left != null ) && (right != null)){
TypeInfo leftType =left.getResultType().getResult();
TypeInfo rightType =right.getResultType().getResult();
info = usualArithmeticConversions( scope, leftType, rightType);
}
else
handleProblem( scope, IProblem.SEMANTIC_MALFORMED_EXPRESSION, null );
result = new ExpressionResult(info);
return result;
}
// types that resolve to LHS types
if ((kind == IASTExpression.Kind.PRIMARY_BRACKETED_EXPRESSION)
|| (kind == IASTExpression.Kind.POSTFIX_INCREMENT)
|| (kind == IASTExpression.Kind.POSTFIX_DECREMENT)
|| (kind == IASTExpression.Kind.POSTFIX_TYPEID_EXPRESSION)
|| (kind == IASTExpression.Kind.UNARY_INCREMENT)
|| (kind == IASTExpression.Kind.UNARY_DECREMENT)
|| (kind == IASTExpression.Kind.UNARY_PLUS_CASTEXPRESSION)
|| (kind == IASTExpression.Kind.UNARY_MINUS_CASTEXPRESSION)
|| (kind == IASTExpression.Kind.UNARY_NOT_CASTEXPRESSION)
|| (kind == IASTExpression.Kind.UNARY_TILDE_CASTEXPRESSION)
|| (kind == IASTExpression.Kind.SHIFT_LEFT)
|| (kind == IASTExpression.Kind.SHIFT_RIGHT)
|| (kind == IASTExpression.Kind.ASSIGNMENTEXPRESSION_NORMAL)
|| (kind == IASTExpression.Kind.ASSIGNMENTEXPRESSION_PLUS)
|| (kind == IASTExpression.Kind.ASSIGNMENTEXPRESSION_MINUS)
|| (kind == IASTExpression.Kind.ASSIGNMENTEXPRESSION_MULT)
|| (kind == IASTExpression.Kind.ASSIGNMENTEXPRESSION_DIV)
|| (kind == IASTExpression.Kind.ASSIGNMENTEXPRESSION_MOD)
|| (kind == IASTExpression.Kind.ASSIGNMENTEXPRESSION_LSHIFT)
|| (kind == IASTExpression.Kind.ASSIGNMENTEXPRESSION_RSHIFT)
|| (kind == IASTExpression.Kind.ASSIGNMENTEXPRESSION_AND)
|| (kind == IASTExpression.Kind.ASSIGNMENTEXPRESSION_OR)
|| (kind == IASTExpression.Kind.ASSIGNMENTEXPRESSION_XOR)
){
ASTExpression left = (ASTExpression)lhs;
if(left != null){
info =left.getResultType().getResult();
} else
handleProblem( scope, IProblem.SEMANTIC_MALFORMED_EXPRESSION, null );
result = new ExpressionResult(info);
return result;
}
// the cast changes the types to the type looked up in typeId = symbol
if(( kind == IASTExpression.Kind.CASTEXPRESSION )
|| ( kind == IASTExpression.Kind.POSTFIX_DYNAMIC_CAST )
|| ( kind == IASTExpression.Kind.POSTFIX_STATIC_CAST )
|| ( kind == IASTExpression.Kind.POSTFIX_REINTERPRET_CAST )
|| ( kind == IASTExpression.Kind.POSTFIX_CONST_CAST )
){
try{
info = new TypeInfo(typeId.getTypeSymbol().getTypeInfo());
}catch (ASTNotImplementedException e)
{
// will never happen
}
result = new ExpressionResult(info);
return result;
}
// a list collects all types of left and right hand sides
if(kind == IASTExpression.Kind.EXPRESSIONLIST){
result = new ExpressionResultList();
if(lhs != null){
TypeInfo leftType = ((ASTExpression)lhs).getResultType().getResult();
result.setResult(leftType);
}
if(rhs != null){
TypeInfo rightType = ((ASTExpression)rhs).getResultType().getResult();
result.setResult(rightType);
}
return result;
}
// a function call type is the return type of the function
if(kind == IASTExpression.Kind.POSTFIX_FUNCTIONCALL){
if(symbol != null){
IParameterizedSymbol psymbol = (IParameterizedSymbol) symbol;
ISymbol returnTypeSymbol = psymbol.getReturnType();
if(returnTypeSymbol != null){
info.setType(returnTypeSymbol.getType());
info.setTypeSymbol(returnTypeSymbol);
}else {
// this is call to a constructor
}
}
result = new ExpressionResult(info);
if(symbol == null)
result.setFailedToDereference(true);
return result;
}
// typeid
if( kind == IASTExpression.Kind.POSTFIX_TYPEID_TYPEID )
{
try
{
info = typeId.getTypeSymbol().getTypeInfo();
}
catch (ASTNotImplementedException e)
{
// will not ever happen from within CompleteParseASTFactory
}
result = new ExpressionResult(info);
return result;
}
// typename
if ( ( kind == IASTExpression.Kind.POSTFIX_TYPENAME_IDENTIFIER )
|| ( kind == IASTExpression.Kind.POSTFIX_TYPENAME_TEMPLATEID ) )
{
if(symbol != null){
info.setType(TypeInfo.t_type);
info.setTypeSymbol(symbol);
} else
handleProblem( scope, IProblem.SEMANTIC_MALFORMED_EXPRESSION, null );
result = new ExpressionResult(info);
return result;
}
// assert false : this;
return null;
}
|
diff --git a/atlas-web/src/test/java/uk/ac/ebi/gxa/requesthandlers/experimentpage/SimilarGeneListTest.java b/atlas-web/src/test/java/uk/ac/ebi/gxa/requesthandlers/experimentpage/SimilarGeneListTest.java
index 9140227db..3bd3a325f 100644
--- a/atlas-web/src/test/java/uk/ac/ebi/gxa/requesthandlers/experimentpage/SimilarGeneListTest.java
+++ b/atlas-web/src/test/java/uk/ac/ebi/gxa/requesthandlers/experimentpage/SimilarGeneListTest.java
@@ -1,126 +1,126 @@
/*
* Copyright 2008-2010 Microarray Informatics Team, EMBL-European Bioinformatics Institute
*
* 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.
*
*
* For further details of the Gene Expression Atlas project, including source code,
* downloads and documentation, please see:
*
* http://gxa.github.com/gxa
*/
package uk.ac.ebi.gxa.requesthandlers.experimentpage;
import junit.framework.TestCase;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import uk.ac.ebi.gxa.R.AtlasRFactory;
import uk.ac.ebi.gxa.R.AtlasRFactoryBuilder;
import uk.ac.ebi.gxa.analytics.compute.AtlasComputeService;
import uk.ac.ebi.gxa.analytics.compute.ComputeException;
import uk.ac.ebi.gxa.analytics.compute.ComputeTask;
import uk.ac.ebi.gxa.requesthandlers.experimentpage.result.SimilarityResultSet;
import uk.ac.ebi.rcloud.server.RServices;
import uk.ac.ebi.rcloud.server.RType.RDataFrame;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.rmi.RemoteException;
import java.util.ArrayList;
/**
* Javadocs go here!
*
* @author Tony Burdett
* @date 17-Nov-2009
*/
public class SimilarGeneListTest extends TestCase {
private AtlasComputeService svc;
@Before
public void setUp() {
try {
// build default rFactory - reads R.properties from classpath
AtlasRFactory rFactory = AtlasRFactoryBuilder.getAtlasRFactoryBuilder().buildAtlasRFactory();
// build service
svc = new AtlasComputeService();
svc.setAtlasRFactory(rFactory);
}
catch (Exception e) {
e.printStackTrace();
fail("Caught exception whilst setting up");
}
}
@After
public void tearDown() {
svc.shutdown();
}
@Test
public void testComputeSimilarityTask() {
// do a similarity over E-AFMX-5 for an arbitrary design element/array design
// TODO: fix similarity result test!
- final SimilarityResultSet simRS = new SimilarityResultSet("226010852", "153094131", "153069949", "");
+ final SimilarityResultSet simRS = new SimilarityResultSet("226010852", "153094131", "153069949", "/ebi/ArrayExpress-files/NetCDFs.ATLAS");
final String callSim = "sim.nc(" + simRS.getTargetDesignElementId() + ",'" + simRS.getSourceNetCDF() + "')";
RDataFrame sim = null;
try {
sim = svc.computeTask(new ComputeTask<RDataFrame>() {
public RDataFrame compute(RServices R) throws RemoteException {
try {
R.sourceFromBuffer(getRCodeFromResource("sim.R"));
} catch (IOException e) {
fail("Couldn't read sim.R");
}
return (RDataFrame) R.getObject(callSim);
}
});
}
catch (ComputeException e) {
fail("Failed calling: " + callSim + "\n" + e.getMessage());
e.printStackTrace();
}
if (null != sim) {
simRS.loadResult(sim);
ArrayList<String> simGeneIds = simRS.getSimGeneIDs();
assertEquals(simGeneIds.get(0), "153069988");
}
else {
fail("Similarity search returned null");
}
}
private String getRCodeFromResource(String resourcePath) throws IOException {
// open a stream to the resource
InputStream in = getClass().getClassLoader().getResourceAsStream(resourcePath);
// create a reader to read in code
BufferedReader reader = new BufferedReader(new InputStreamReader(in));
StringBuilder sb = new StringBuilder();
String line;
while ((line = reader.readLine()) != null) {
sb.append(line).append("\n");
}
in.close();
return sb.toString();
}
}
| true | true | public void testComputeSimilarityTask() {
// do a similarity over E-AFMX-5 for an arbitrary design element/array design
// TODO: fix similarity result test!
final SimilarityResultSet simRS = new SimilarityResultSet("226010852", "153094131", "153069949", "");
final String callSim = "sim.nc(" + simRS.getTargetDesignElementId() + ",'" + simRS.getSourceNetCDF() + "')";
RDataFrame sim = null;
try {
sim = svc.computeTask(new ComputeTask<RDataFrame>() {
public RDataFrame compute(RServices R) throws RemoteException {
try {
R.sourceFromBuffer(getRCodeFromResource("sim.R"));
} catch (IOException e) {
fail("Couldn't read sim.R");
}
return (RDataFrame) R.getObject(callSim);
}
});
}
catch (ComputeException e) {
fail("Failed calling: " + callSim + "\n" + e.getMessage());
e.printStackTrace();
}
if (null != sim) {
simRS.loadResult(sim);
ArrayList<String> simGeneIds = simRS.getSimGeneIDs();
assertEquals(simGeneIds.get(0), "153069988");
}
else {
fail("Similarity search returned null");
}
}
| public void testComputeSimilarityTask() {
// do a similarity over E-AFMX-5 for an arbitrary design element/array design
// TODO: fix similarity result test!
final SimilarityResultSet simRS = new SimilarityResultSet("226010852", "153094131", "153069949", "/ebi/ArrayExpress-files/NetCDFs.ATLAS");
final String callSim = "sim.nc(" + simRS.getTargetDesignElementId() + ",'" + simRS.getSourceNetCDF() + "')";
RDataFrame sim = null;
try {
sim = svc.computeTask(new ComputeTask<RDataFrame>() {
public RDataFrame compute(RServices R) throws RemoteException {
try {
R.sourceFromBuffer(getRCodeFromResource("sim.R"));
} catch (IOException e) {
fail("Couldn't read sim.R");
}
return (RDataFrame) R.getObject(callSim);
}
});
}
catch (ComputeException e) {
fail("Failed calling: " + callSim + "\n" + e.getMessage());
e.printStackTrace();
}
if (null != sim) {
simRS.loadResult(sim);
ArrayList<String> simGeneIds = simRS.getSimGeneIDs();
assertEquals(simGeneIds.get(0), "153069988");
}
else {
fail("Similarity search returned null");
}
}
|
diff --git a/Model/src/java/fr/cg95/cvq/util/admin/UserReferentialMigration.java b/Model/src/java/fr/cg95/cvq/util/admin/UserReferentialMigration.java
index 22fb7a681..bc719aea1 100644
--- a/Model/src/java/fr/cg95/cvq/util/admin/UserReferentialMigration.java
+++ b/Model/src/java/fr/cg95/cvq/util/admin/UserReferentialMigration.java
@@ -1,343 +1,344 @@
package fr.cg95.cvq.util.admin;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang3.ArrayUtils;
import org.hibernate.criterion.Restrictions;
import org.hibernate.transform.Transformers;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import com.google.gson.Gson;
import com.google.gson.JsonObject;
import fr.cg95.cvq.business.QoS;
import fr.cg95.cvq.business.request.Request;
import fr.cg95.cvq.business.request.RequestAction;
import fr.cg95.cvq.business.request.RequestActionType;
import fr.cg95.cvq.business.request.RequestState;
import fr.cg95.cvq.business.request.ecitizen.HomeFolderModificationRequestData;
import fr.cg95.cvq.business.request.ecitizen.VoCardRequestData;
import fr.cg95.cvq.business.users.Adult;
import fr.cg95.cvq.business.users.HomeFolder;
import fr.cg95.cvq.business.users.Individual;
import fr.cg95.cvq.business.users.IndividualRole;
import fr.cg95.cvq.business.users.UserAction;
import fr.cg95.cvq.business.users.UserState;
import fr.cg95.cvq.dao.hibernate.GenericDAO;
import fr.cg95.cvq.dao.hibernate.HibernateUtil;
import fr.cg95.cvq.exception.CvqException;
import fr.cg95.cvq.exception.CvqObjectNotFoundException;
import fr.cg95.cvq.service.authority.impl.LocalAuthorityRegistry;
import fr.cg95.cvq.service.request.IRequestSearchService;
import fr.cg95.cvq.service.users.IUserSearchService;
import fr.cg95.cvq.util.Critere;
import fr.cg95.cvq.util.JSONUtils;
import fr.cg95.cvq.util.UserUtils;
public class UserReferentialMigration {
private LocalAuthorityRegistry localAuthorityRegistry;
private IRequestSearchService requestSearchService;
private IUserSearchService userSearchService;
private CustomDAO customDAO = new CustomDAO();
private Set<Long> archived = new HashSet<Long>();
private Map<Long, UserState> states = new HashMap<Long, UserState>();
private Map<Long, List<Long>> creationActions = new HashMap<Long, List<Long>>();
private Map<Long, Date> creationNotifications = new HashMap<Long, Date>();
private Comparator<UserAction> comparator = new Comparator<UserAction>() {
@Override
public int compare(UserAction o1, UserAction o2) {
return o1.getDate().compareTo(o2.getDate());
}
};
public static void main(final String[] args) {
ClassPathXmlApplicationContext context = SpringApplicationContextLoader.loadContext(null);
UserReferentialMigration userReferentialMigration = new UserReferentialMigration();
userReferentialMigration.localAuthorityRegistry = (LocalAuthorityRegistry)context.getBean("localAuthorityRegistry");
userReferentialMigration.requestSearchService = (IRequestSearchService)context.getBean("requestSearchService");
userReferentialMigration.userSearchService = (IUserSearchService)context.getBean("userSearchService");
userReferentialMigration.localAuthorityRegistry.browseAndCallback(userReferentialMigration, "migrate", new Object[0]);
System.exit(0);
}
public void migrate()
throws CvqException {
for (DTO dto : (List<DTO>)HibernateUtil.getSession().createSQLQuery(
"select r.requester_id as requesterId, r.home_folder_id as homeFolderId, r.creation_date as date, i.id as individualId from individual i, request r, history_entry he where r.id = he.request_id and i.id = he.object_id and property = 'homeFolder' and old_value is not null and new_value is null")
.addScalar("requesterId").addScalar("homeFolderId").addScalar("date")
.addScalar("individualId").setResultTransformer(Transformers.aliasToBean(DTO.class))
.list()) {
Individual i = userSearchService.getById(dto.individualId);
HomeFolder homeFolder = userSearchService.getHomeFolderById(dto.homeFolderId);
i.setHomeFolder(homeFolder);
homeFolder.getIndividuals().add(i);
i.setState(UserState.ARCHIVED);
archived.add(i.getId());
RequestAction fake = new RequestAction();
fake.setDate(dto.date);
fake.setAgentId(dto.requesterId);
JsonObject payload = new JsonObject();
payload.addProperty("state", UserState.ARCHIVED.toString());
add(homeFolder, new UserAction(UserAction.Type.STATE_CHANGE, dto.individualId, payload), fake);
}
for (HomeFolder homeFolder : customDAO.all(HomeFolder.class)) {
Set<Critere> criterias = new HashSet<Critere>();
criterias.add(new Critere(Request.SEARCH_BY_HOME_FOLDER_ID, homeFolder.getId(), Critere.EQUALS));
- List<Request> requests = requestSearchService.get(criterias, null, null, 0, 0, true);
- Request first = requests.get(requests.size() - 1);
+ List<Request> requests = requestSearchService.get(criterias, Request.SEARCH_BY_CREATION_DATE, null, 0, 0, true);
+ if (requests.isEmpty()) continue;
+ Request first = requests.get(0);
if (homeFolder.isTemporary()) {
List<RequestAction> actions = new ArrayList<RequestAction>(first.getActions());
Collections.reverse(actions);
for (RequestAction requestAction : actions) {
convert(requestAction);
}
} else {
for (RequestAction requestAction :
(List<RequestAction>)HibernateUtil.getSession().createSQLQuery(
"select * from request_action where request_id in (select id from request where home_folder_id = :homeFolderId and specific_data_class='fr.cg95.cvq.business.request.ecitizen.HomeFolderModificationRequestData') or request_id = :firstId order by date asc")
.addEntity(RequestAction.class).setLong("homeFolderId", homeFolder.getId())
.setLong("firstId", first.getId()).list()) {
convert(requestAction);
}
}
}
HibernateUtil.getSession().flush();
for (HomeFolder homeFolder : customDAO.all(HomeFolder.class)) {
if (!customDAO.hasCreationAction(homeFolder.getId()))
createFakeCreationAction(homeFolder, homeFolder.getId());
for (Individual i : homeFolder.getIndividuals())
if (!customDAO.hasCreationAction(i.getId()))
createFakeCreationAction(homeFolder, i.getId());
}
HibernateUtil.getSession().flush();
for (Map.Entry<Long, Date> creationNotification : creationNotifications.entrySet()) {
for (Long id : creationActions.get(creationNotification.getKey())) {
UserAction action = (UserAction) customDAO.findById(UserAction.class, id);
JsonObject payload = JSONUtils.deserialize(action.getData());
payload.addProperty("notificationDate", creationNotification.getValue().toString());
action.setData(new Gson().toJson(payload));
customDAO.update(action);
}
}
for (Long id : archived) {
states.put(id, UserState.ARCHIVED);
}
for (Map.Entry<Long, UserState> state : states.entrySet()) {
try {
Individual i = userSearchService.getById(state.getKey());
i.setState(state.getValue());
customDAO.update(i);
} catch (CvqObjectNotFoundException e) {
HomeFolder homeFolder = userSearchService.getHomeFolderById(state.getKey());
homeFolder.setState(state.getValue());
customDAO.update(homeFolder);
}
}
for (Adult external : customDAO.findBySimpleProperty(Adult.class, "homeFolder", null)) {
HomeFolder homeFolder = null;
for (IndividualRole role : (List<IndividualRole>) HibernateUtil.getSession()
.createSQLQuery("select * from individual_role where owner_id = :id")
.addEntity(IndividualRole.class).setLong("id", external.getId()).list()) {
if (role.getHomeFolderId() != null) {
try {
homeFolder = userSearchService.getHomeFolderById(role.getHomeFolderId());
} catch (CvqObjectNotFoundException e) {
// what a wonderful model
}
} else if (role.getIndividualId() != null) {
try {
homeFolder = userSearchService.getById(role.getIndividualId()).getHomeFolder();
} catch (CvqObjectNotFoundException e) {
// what a wonderful model
}
}
if (homeFolder != null) {
createFakeCreationAction(homeFolder, external.getId());
break;
}
}
}
}
private void convert(RequestAction requestAction)
throws CvqObjectNotFoundException {
Long requestId = ((BigInteger)HibernateUtil.getSession().createSQLQuery(
"select request_id from request_action where id = :id")
.setLong("id", requestAction.getId()).uniqueResult()).longValue();
Request request = requestSearchService.getById(requestId, true);
HomeFolder homeFolder = userSearchService.getHomeFolderById(request.getHomeFolderId());
if (RequestActionType.CREATION.equals(requestAction.getType())) {
UserAction.Type type =
HomeFolderModificationRequestData.class.equals(request.getRequestData().getSpecificDataClass()) ?
UserAction.Type.MODIFICATION : UserAction.Type.CREATION;
List<Long> actionIds = new ArrayList<Long>();
actionIds.add(add(homeFolder, new UserAction(type, homeFolder.getId()), requestAction));
states.put(homeFolder.getId(),
HomeFolderModificationRequestData.class.equals(request.getRequestData().getSpecificDataClass()) ?
UserState.MODIFIED : UserState.NEW);
for (Individual individual : homeFolder.getIndividuals()) {
if (isConcerned(individual, request)) {
individual.setLastModificationDate(requestAction.getDate());
actionIds.add(add(homeFolder, new UserAction(
UserState.NEW.equals(individual.getState()) ? UserAction.Type.CREATION : type,
individual.getId()), requestAction));
states.put(individual.getId(),
HomeFolderModificationRequestData.class.equals(request.getRequestData().getSpecificDataClass())
&& !UserState.NEW.equals(individual.getState()) ? UserState.MODIFIED : UserState.NEW);
}
}
creationActions.put(requestId, actionIds);
} else if (RequestActionType.STATE_CHANGE.equals(requestAction.getType())) {
UserState state = convert(requestAction.getResultingState(),
HomeFolderModificationRequestData.class.equals(request.getRequestData().getSpecificDataClass()));
if (state == null || state.equals(states.get(homeFolder.getId()))
|| (UserState.ARCHIVED.equals(state) && !homeFolder.isTemporary()))
return;
states.put(homeFolder.getId(), state);
JsonObject payload = new JsonObject();
payload.addProperty("state", state.toString());
add(homeFolder, new UserAction(UserAction.Type.STATE_CHANGE, homeFolder.getId(), payload), requestAction);
for (Individual individual : homeFolder.getIndividuals()) {
if (isConcerned(individual, request) && !state.equals(states.get(individual.getId()))) {
individual.setLastModificationDate(requestAction.getDate());
add(homeFolder, new UserAction(UserAction.Type.STATE_CHANGE, individual.getId(), payload), requestAction);
states.put(individual.getId(), state);
}
}
} else if (RequestActionType.CONTACT_CITIZEN.equals(requestAction.getType())
&& (VoCardRequestData.class.equals(request.getRequestData().getSpecificDataClass())
|| HomeFolderModificationRequestData.class.equals(request.getRequestData().getSpecificDataClass()))) {
JsonObject payload = new JsonObject();
JsonObject contact = new JsonObject();
if (requestAction.getFile() != null) {
contact.addProperty("file", new Gson().toJson(requestAction.getFile()));
}
if (requestAction.getFilename() != null) {
contact.addProperty("filename", new Gson().toJson(requestAction.getFilename()));
}
contact.addProperty("message", requestAction.getMessage());
payload.add("contact", contact);
UserAction action = new UserAction(UserAction.Type.CONTACT, userSearchService.getHomeFolderResponsible(homeFolder.getId()).getId(), payload);
action.setNote(requestAction.getNote());
add(homeFolder, action, requestAction);
} else if (RequestActionType.ORANGE_ALERT_NOTIFICATION.equals(requestAction.getType())
|| RequestActionType.RED_ALERT_NOTIFICATION.equals(requestAction.getType())) {
JsonObject payload = new JsonObject();
payload.addProperty("quality",
RequestActionType.ORANGE_ALERT_NOTIFICATION.equals(requestAction.getType()) ?
QoS.URGENT.toString() : QoS.LATE.toString());
payload.addProperty("notified", true);
add(homeFolder, new UserAction(UserAction.Type.QoS, homeFolder.getId(), payload), requestAction);
for (Individual individual : homeFolder.getIndividuals()) {
if (isConcerned(individual, request))
add(homeFolder, new UserAction(UserAction.Type.QoS, individual.getId(), payload), requestAction);
}
} else if (RequestActionType.CREATION_NOTIFICATION.equals(requestAction.getType())) {
creationNotifications.put(requestId, requestAction.getDate());
}
}
private Long add(HomeFolder homeFolder, UserAction userAction, RequestAction requestAction) {
userAction.setUserId(requestAction.getAgentId());
JsonObject payload = JSONUtils.deserialize(userAction.getData());
payload.get("user").getAsJsonObject().addProperty("id", requestAction.getAgentId());
payload.get("user").getAsJsonObject().addProperty("name", UserUtils.getDisplayName(requestAction.getAgentId()));
userAction.setData(new Gson().toJson(payload));
userAction.setDate(requestAction.getDate());
List<UserAction> actions = new ArrayList<UserAction>(homeFolder.getActions());
actions.add(userAction);
Collections.sort(actions, comparator);
homeFolder.setActions(actions);
return customDAO.create(userAction);
}
private boolean isConcerned(Individual individual, Request request) {
if (individual == null) return false;
if (!ArrayUtils.contains(new RequestState[] {
RequestState.DRAFT, RequestState.PENDING, RequestState.UNCOMPLETE, RequestState.COMPLETE
}, request.getState()))
return !UserState.NEW.equals(individual.getState());
return !HomeFolderModificationRequestData.class.equals(request.getRequestData().getSpecificDataClass())
|| UserState.MODIFIED.equals(individual.getState())
|| UserState.NEW.equals(individual.getState());
}
private void createFakeCreationAction(HomeFolder homeFolder, Long targetId) {
Date responsibleCreation = userSearchService.getHomeFolderResponsible(homeFolder.getId()).getCreationDate();
Date firstAction = homeFolder.getActions().isEmpty() ? null : homeFolder.getActions().get(0).getDate();
Date homeFolderCreation =
firstAction != null && responsibleCreation.compareTo(firstAction) > 0 ? firstAction
: responsibleCreation;
RequestAction fake = new RequestAction();
fake.setAgentId(-1L);
fake.setDate(homeFolderCreation);
add(homeFolder, new UserAction(UserAction.Type.CREATION, targetId), fake);
}
private UserState convert(RequestState state, boolean modification) {
if (RequestState.ARCHIVED.equals(state)) {
return UserState.ARCHIVED;
} else if (RequestState.CANCELLED.equals(state)) {
return UserState.INVALID;
} else if (RequestState.CLOSED.equals(state)) {
return null;
} else if (RequestState.COMPLETE.equals(state)) {
return null;
} else if (RequestState.DRAFT.equals(state)) {
return null;
} else if (RequestState.NOTIFIED.equals(state)) {
return UserState.VALID;
} else if (RequestState.PENDING.equals(state)) {
return modification ? UserState.MODIFIED : null;
} else if (RequestState.REJECTED.equals(state)) {
return UserState.INVALID;
} else if (RequestState.UNCOMPLETE.equals(state)) {
return UserState.INVALID;
} else if (RequestState.VALIDATED.equals(state)) {
return UserState.VALID;
}
return null;
}
private class CustomDAO extends GenericDAO {
public boolean hasCreationAction(Long targetId) {
return HibernateUtil.getSession().createCriteria(UserAction.class)
.add(Restrictions.eq("targetId", targetId))
.add(Restrictions.eq("type", UserAction.Type.CREATION)).uniqueResult() != null;
}
}
public static class DTO {
private Long homeFolderId;
private Long individualId;
private Long requesterId;
public Date date;
public void setHomeFolderId(BigInteger homeFolderId) {
this.homeFolderId = homeFolderId.longValue();
}
public void setIndividualId(BigInteger individualId) {
this.individualId = individualId.longValue();
}
public void setRequesterId(BigInteger requesterId) {
this.requesterId = requesterId.longValue();
}
}
}
| true | true | public void migrate()
throws CvqException {
for (DTO dto : (List<DTO>)HibernateUtil.getSession().createSQLQuery(
"select r.requester_id as requesterId, r.home_folder_id as homeFolderId, r.creation_date as date, i.id as individualId from individual i, request r, history_entry he where r.id = he.request_id and i.id = he.object_id and property = 'homeFolder' and old_value is not null and new_value is null")
.addScalar("requesterId").addScalar("homeFolderId").addScalar("date")
.addScalar("individualId").setResultTransformer(Transformers.aliasToBean(DTO.class))
.list()) {
Individual i = userSearchService.getById(dto.individualId);
HomeFolder homeFolder = userSearchService.getHomeFolderById(dto.homeFolderId);
i.setHomeFolder(homeFolder);
homeFolder.getIndividuals().add(i);
i.setState(UserState.ARCHIVED);
archived.add(i.getId());
RequestAction fake = new RequestAction();
fake.setDate(dto.date);
fake.setAgentId(dto.requesterId);
JsonObject payload = new JsonObject();
payload.addProperty("state", UserState.ARCHIVED.toString());
add(homeFolder, new UserAction(UserAction.Type.STATE_CHANGE, dto.individualId, payload), fake);
}
for (HomeFolder homeFolder : customDAO.all(HomeFolder.class)) {
Set<Critere> criterias = new HashSet<Critere>();
criterias.add(new Critere(Request.SEARCH_BY_HOME_FOLDER_ID, homeFolder.getId(), Critere.EQUALS));
List<Request> requests = requestSearchService.get(criterias, null, null, 0, 0, true);
Request first = requests.get(requests.size() - 1);
if (homeFolder.isTemporary()) {
List<RequestAction> actions = new ArrayList<RequestAction>(first.getActions());
Collections.reverse(actions);
for (RequestAction requestAction : actions) {
convert(requestAction);
}
} else {
for (RequestAction requestAction :
(List<RequestAction>)HibernateUtil.getSession().createSQLQuery(
"select * from request_action where request_id in (select id from request where home_folder_id = :homeFolderId and specific_data_class='fr.cg95.cvq.business.request.ecitizen.HomeFolderModificationRequestData') or request_id = :firstId order by date asc")
.addEntity(RequestAction.class).setLong("homeFolderId", homeFolder.getId())
.setLong("firstId", first.getId()).list()) {
convert(requestAction);
}
}
}
HibernateUtil.getSession().flush();
for (HomeFolder homeFolder : customDAO.all(HomeFolder.class)) {
if (!customDAO.hasCreationAction(homeFolder.getId()))
createFakeCreationAction(homeFolder, homeFolder.getId());
for (Individual i : homeFolder.getIndividuals())
if (!customDAO.hasCreationAction(i.getId()))
createFakeCreationAction(homeFolder, i.getId());
}
HibernateUtil.getSession().flush();
for (Map.Entry<Long, Date> creationNotification : creationNotifications.entrySet()) {
for (Long id : creationActions.get(creationNotification.getKey())) {
UserAction action = (UserAction) customDAO.findById(UserAction.class, id);
JsonObject payload = JSONUtils.deserialize(action.getData());
payload.addProperty("notificationDate", creationNotification.getValue().toString());
action.setData(new Gson().toJson(payload));
customDAO.update(action);
}
}
for (Long id : archived) {
states.put(id, UserState.ARCHIVED);
}
for (Map.Entry<Long, UserState> state : states.entrySet()) {
try {
Individual i = userSearchService.getById(state.getKey());
i.setState(state.getValue());
customDAO.update(i);
} catch (CvqObjectNotFoundException e) {
HomeFolder homeFolder = userSearchService.getHomeFolderById(state.getKey());
homeFolder.setState(state.getValue());
customDAO.update(homeFolder);
}
}
for (Adult external : customDAO.findBySimpleProperty(Adult.class, "homeFolder", null)) {
HomeFolder homeFolder = null;
for (IndividualRole role : (List<IndividualRole>) HibernateUtil.getSession()
.createSQLQuery("select * from individual_role where owner_id = :id")
.addEntity(IndividualRole.class).setLong("id", external.getId()).list()) {
if (role.getHomeFolderId() != null) {
try {
homeFolder = userSearchService.getHomeFolderById(role.getHomeFolderId());
} catch (CvqObjectNotFoundException e) {
// what a wonderful model
}
} else if (role.getIndividualId() != null) {
try {
homeFolder = userSearchService.getById(role.getIndividualId()).getHomeFolder();
} catch (CvqObjectNotFoundException e) {
// what a wonderful model
}
}
if (homeFolder != null) {
createFakeCreationAction(homeFolder, external.getId());
break;
}
}
}
}
| public void migrate()
throws CvqException {
for (DTO dto : (List<DTO>)HibernateUtil.getSession().createSQLQuery(
"select r.requester_id as requesterId, r.home_folder_id as homeFolderId, r.creation_date as date, i.id as individualId from individual i, request r, history_entry he where r.id = he.request_id and i.id = he.object_id and property = 'homeFolder' and old_value is not null and new_value is null")
.addScalar("requesterId").addScalar("homeFolderId").addScalar("date")
.addScalar("individualId").setResultTransformer(Transformers.aliasToBean(DTO.class))
.list()) {
Individual i = userSearchService.getById(dto.individualId);
HomeFolder homeFolder = userSearchService.getHomeFolderById(dto.homeFolderId);
i.setHomeFolder(homeFolder);
homeFolder.getIndividuals().add(i);
i.setState(UserState.ARCHIVED);
archived.add(i.getId());
RequestAction fake = new RequestAction();
fake.setDate(dto.date);
fake.setAgentId(dto.requesterId);
JsonObject payload = new JsonObject();
payload.addProperty("state", UserState.ARCHIVED.toString());
add(homeFolder, new UserAction(UserAction.Type.STATE_CHANGE, dto.individualId, payload), fake);
}
for (HomeFolder homeFolder : customDAO.all(HomeFolder.class)) {
Set<Critere> criterias = new HashSet<Critere>();
criterias.add(new Critere(Request.SEARCH_BY_HOME_FOLDER_ID, homeFolder.getId(), Critere.EQUALS));
List<Request> requests = requestSearchService.get(criterias, Request.SEARCH_BY_CREATION_DATE, null, 0, 0, true);
if (requests.isEmpty()) continue;
Request first = requests.get(0);
if (homeFolder.isTemporary()) {
List<RequestAction> actions = new ArrayList<RequestAction>(first.getActions());
Collections.reverse(actions);
for (RequestAction requestAction : actions) {
convert(requestAction);
}
} else {
for (RequestAction requestAction :
(List<RequestAction>)HibernateUtil.getSession().createSQLQuery(
"select * from request_action where request_id in (select id from request where home_folder_id = :homeFolderId and specific_data_class='fr.cg95.cvq.business.request.ecitizen.HomeFolderModificationRequestData') or request_id = :firstId order by date asc")
.addEntity(RequestAction.class).setLong("homeFolderId", homeFolder.getId())
.setLong("firstId", first.getId()).list()) {
convert(requestAction);
}
}
}
HibernateUtil.getSession().flush();
for (HomeFolder homeFolder : customDAO.all(HomeFolder.class)) {
if (!customDAO.hasCreationAction(homeFolder.getId()))
createFakeCreationAction(homeFolder, homeFolder.getId());
for (Individual i : homeFolder.getIndividuals())
if (!customDAO.hasCreationAction(i.getId()))
createFakeCreationAction(homeFolder, i.getId());
}
HibernateUtil.getSession().flush();
for (Map.Entry<Long, Date> creationNotification : creationNotifications.entrySet()) {
for (Long id : creationActions.get(creationNotification.getKey())) {
UserAction action = (UserAction) customDAO.findById(UserAction.class, id);
JsonObject payload = JSONUtils.deserialize(action.getData());
payload.addProperty("notificationDate", creationNotification.getValue().toString());
action.setData(new Gson().toJson(payload));
customDAO.update(action);
}
}
for (Long id : archived) {
states.put(id, UserState.ARCHIVED);
}
for (Map.Entry<Long, UserState> state : states.entrySet()) {
try {
Individual i = userSearchService.getById(state.getKey());
i.setState(state.getValue());
customDAO.update(i);
} catch (CvqObjectNotFoundException e) {
HomeFolder homeFolder = userSearchService.getHomeFolderById(state.getKey());
homeFolder.setState(state.getValue());
customDAO.update(homeFolder);
}
}
for (Adult external : customDAO.findBySimpleProperty(Adult.class, "homeFolder", null)) {
HomeFolder homeFolder = null;
for (IndividualRole role : (List<IndividualRole>) HibernateUtil.getSession()
.createSQLQuery("select * from individual_role where owner_id = :id")
.addEntity(IndividualRole.class).setLong("id", external.getId()).list()) {
if (role.getHomeFolderId() != null) {
try {
homeFolder = userSearchService.getHomeFolderById(role.getHomeFolderId());
} catch (CvqObjectNotFoundException e) {
// what a wonderful model
}
} else if (role.getIndividualId() != null) {
try {
homeFolder = userSearchService.getById(role.getIndividualId()).getHomeFolder();
} catch (CvqObjectNotFoundException e) {
// what a wonderful model
}
}
if (homeFolder != null) {
createFakeCreationAction(homeFolder, external.getId());
break;
}
}
}
}
|
diff --git a/src/main/java/pl/psnc/dl/wf4ever/evo/CopyOperation.java b/src/main/java/pl/psnc/dl/wf4ever/evo/CopyOperation.java
index 9f02217b..0f77552c 100644
--- a/src/main/java/pl/psnc/dl/wf4ever/evo/CopyOperation.java
+++ b/src/main/java/pl/psnc/dl/wf4ever/evo/CopyOperation.java
@@ -1,209 +1,209 @@
package pl.psnc.dl.wf4ever.evo;
import java.net.URI;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.apache.log4j.Logger;
import pl.psnc.dl.wf4ever.common.HibernateUtil;
import pl.psnc.dl.wf4ever.common.ResearchObject;
import pl.psnc.dl.wf4ever.dl.AccessDeniedException;
import pl.psnc.dl.wf4ever.dl.ConflictException;
import pl.psnc.dl.wf4ever.dl.DigitalLibraryException;
import pl.psnc.dl.wf4ever.dl.NotFoundException;
import pl.psnc.dl.wf4ever.rosrs.ROSRService;
import pl.psnc.dl.wf4ever.vocabulary.AO;
import pl.psnc.dl.wf4ever.vocabulary.ORE;
import pl.psnc.dl.wf4ever.vocabulary.RO;
import com.hp.hpl.jena.ontology.Individual;
import com.hp.hpl.jena.ontology.OntModel;
import com.hp.hpl.jena.ontology.OntModelSpec;
import com.hp.hpl.jena.rdf.model.ModelFactory;
import com.hp.hpl.jena.rdf.model.RDFNode;
import com.hp.hpl.jena.rdf.model.Resource;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
/**
* Copy one research object to another.
*
* @author piotrekhol
*
*/
public class CopyOperation implements Operation {
/** logger. */
private static final Logger LOGGER = Logger.getLogger(CopyOperation.class);
/** operation id. */
private String id;
/**
* Constructor.
*
* @param id
* operation id
*/
public CopyOperation(String id) {
this.id = id;
}
@Override
public void execute(JobStatus status)
throws OperationFailedException {
HibernateUtil.getSessionFactory().getCurrentSession().beginTransaction();
try {
URI target = status.getCopyfrom().resolve("../" + id + "/");
int i = 1;
String sufix = "";
- while (ROSRService.SMS.get().containsNamedGraph(target)) {
+ while (ROSRService.SMS.get().containsNamedGraph(target.resolve(ResearchObject.MANIFEST_PATH))) {
sufix = "-" + Integer.toString(i);
target = status.getCopyfrom().resolve("../" + id + "-" + (i++) + "/");
}
status.setTarget(id + sufix);
ResearchObject targetRO = ResearchObject.create(target);
ResearchObject sourceRO = ResearchObject.create(status.getCopyfrom());
try {
ROSRService.createResearchObject(targetRO, status.getType(), sourceRO);
} catch (ConflictException | DigitalLibraryException | NotFoundException | AccessDeniedException e) {
throw new OperationFailedException("Could not create the target research object", e);
}
OntModel model = ModelFactory.createOntologyModel(OntModelSpec.OWL_LITE_MEM);
model.read(sourceRO.getManifestUri().toString());
Individual source = model.getIndividual(sourceRO.getUri().toString());
if (source == null) {
throw new OperationFailedException("The manifest does not describe the research object");
}
List<RDFNode> aggregatedResources = source.listPropertyValues(ORE.aggregates).toList();
Map<URI, URI> changedURIs = new HashMap<>();
changedURIs.put(sourceRO.getManifestUri(), targetRO.getManifestUri());
for (RDFNode aggregatedResource : aggregatedResources) {
if (Thread.interrupted()) {
try {
ROSRService.deleteResearchObject(targetRO);
} catch (DigitalLibraryException | NotFoundException e) {
LOGGER.error("Could not delete the target when aborting: " + target, e);
}
return;
}
if (!aggregatedResource.isURIResource()) {
LOGGER.warn("Aggregated node " + aggregatedResource.toString() + " is not a URI resource");
continue;
}
Individual resource = aggregatedResource.as(Individual.class);
URI resourceURI = URI.create(resource.getURI());
if (resource.hasRDFType(RO.AggregatedAnnotation)) {
Resource annBody = resource.getPropertyResourceValue(AO.body);
List<URI> targets = new ArrayList<>();
List<RDFNode> annotationTargets = resource.listPropertyValues(RO.annotatesAggregatedResource)
.toList();
for (RDFNode annTarget : annotationTargets) {
if (!annTarget.isURIResource()) {
LOGGER.warn("Annotation target " + annTarget.toString() + " is not a URI resource");
continue;
}
targets.add(URI.create(annTarget.asResource().getURI()));
}
try {
//FIXME use a dedicated class for an Annotation
String[] segments = resource.getURI().split("/");
if (segments.length > 0) {
ROSRService.addAnnotation(targetRO, URI.create(annBody.getURI()), targets,
segments[segments.length - 1]);
} else {
ROSRService.addAnnotation(targetRO, URI.create(annBody.getURI()), targets);
}
} catch (AccessDeniedException | DigitalLibraryException | NotFoundException e1) {
LOGGER.error("Could not add the annotation", e1);
}
} else {
if (isInternalResource(resourceURI, status.getCopyfrom())) {
try {
Client client = Client.create();
WebResource webResource = client.resource(resourceURI.toString());
ClientResponse response = webResource.get(ClientResponse.class);
URI resourcePath = status.getCopyfrom().relativize(resourceURI);
URI targetURI = target.resolve(resourcePath);
ROSRService.aggregateInternalResource(targetRO, targetURI, response.getEntityInputStream(),
response.getType().toString(), null);
//TODO improve resource type detection mechanism!!
if (!resource.hasRDFType(RO.Resource)) {
ROSRService.convertAggregatedResourceToAnnotationBody(targetRO, targetURI);
}
changedURIs.put(resourceURI, targetURI);
} catch (AccessDeniedException | DigitalLibraryException | NotFoundException e) {
throw new OperationFailedException("Could not create aggregate internal resource: "
+ resourceURI, e);
}
} else {
try {
ROSRService.aggregateExternalResource(targetRO, resourceURI);
} catch (AccessDeniedException | DigitalLibraryException | NotFoundException e) {
throw new OperationFailedException("Could not create aggregate external resource: "
+ resourceURI, e);
}
}
}
}
for (Map.Entry<URI, URI> e : changedURIs.entrySet()) {
ROSRService.SMS.get().changeURIInManifestAndAnnotationBodies(targetRO, e.getKey(), e.getValue(), false);
}
for (Map.Entry<URI, URI> e : changedURIs.entrySet()) {
ROSRService.SMS.get().changeURIInManifestAndAnnotationBodies(targetRO, e.getKey(), e.getValue(), true);
}
} finally {
HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().commit();
}
}
/**
* Small hack done for manifest annotation problem. If the annotation is the manifest annotation the the target must
* be changed.
*
* @param status
* @param targets
* @param annBodyUri
* @return
*/
private List<URI> changeManifestAnnotationTarget(JobStatus status, List<URI> targets, URI annBodyUri) {
List<URI> results = new ArrayList<URI>();
if (status.getCopyfrom() != null && annBodyUri != null && annBodyUri.toString().contains("manifest.rdf")) {
for (URI t : targets) {
if (t.toString().equals(status.getCopyfrom().toString())) {
results.add(status.getCopyfrom().resolve("../" + status.getTarget()));
} else {
results.add(t);
}
}
}
return results;
}
/**
* Check if a resource is internal to the RO. This will not work if they have different domains, for example if the
* RO URI uses purl.
*
* @param resource
* resource URI
* @param ro
* RO URI
* @return true if the resource URI starts with the RO URI, false otherwise
*/
private boolean isInternalResource(URI resource, URI ro) {
return resource.normalize().toString().startsWith(ro.normalize().toString());
}
}
| true | true | public void execute(JobStatus status)
throws OperationFailedException {
HibernateUtil.getSessionFactory().getCurrentSession().beginTransaction();
try {
URI target = status.getCopyfrom().resolve("../" + id + "/");
int i = 1;
String sufix = "";
while (ROSRService.SMS.get().containsNamedGraph(target)) {
sufix = "-" + Integer.toString(i);
target = status.getCopyfrom().resolve("../" + id + "-" + (i++) + "/");
}
status.setTarget(id + sufix);
ResearchObject targetRO = ResearchObject.create(target);
ResearchObject sourceRO = ResearchObject.create(status.getCopyfrom());
try {
ROSRService.createResearchObject(targetRO, status.getType(), sourceRO);
} catch (ConflictException | DigitalLibraryException | NotFoundException | AccessDeniedException e) {
throw new OperationFailedException("Could not create the target research object", e);
}
OntModel model = ModelFactory.createOntologyModel(OntModelSpec.OWL_LITE_MEM);
model.read(sourceRO.getManifestUri().toString());
Individual source = model.getIndividual(sourceRO.getUri().toString());
if (source == null) {
throw new OperationFailedException("The manifest does not describe the research object");
}
List<RDFNode> aggregatedResources = source.listPropertyValues(ORE.aggregates).toList();
Map<URI, URI> changedURIs = new HashMap<>();
changedURIs.put(sourceRO.getManifestUri(), targetRO.getManifestUri());
for (RDFNode aggregatedResource : aggregatedResources) {
if (Thread.interrupted()) {
try {
ROSRService.deleteResearchObject(targetRO);
} catch (DigitalLibraryException | NotFoundException e) {
LOGGER.error("Could not delete the target when aborting: " + target, e);
}
return;
}
if (!aggregatedResource.isURIResource()) {
LOGGER.warn("Aggregated node " + aggregatedResource.toString() + " is not a URI resource");
continue;
}
Individual resource = aggregatedResource.as(Individual.class);
URI resourceURI = URI.create(resource.getURI());
if (resource.hasRDFType(RO.AggregatedAnnotation)) {
Resource annBody = resource.getPropertyResourceValue(AO.body);
List<URI> targets = new ArrayList<>();
List<RDFNode> annotationTargets = resource.listPropertyValues(RO.annotatesAggregatedResource)
.toList();
for (RDFNode annTarget : annotationTargets) {
if (!annTarget.isURIResource()) {
LOGGER.warn("Annotation target " + annTarget.toString() + " is not a URI resource");
continue;
}
targets.add(URI.create(annTarget.asResource().getURI()));
}
try {
//FIXME use a dedicated class for an Annotation
String[] segments = resource.getURI().split("/");
if (segments.length > 0) {
ROSRService.addAnnotation(targetRO, URI.create(annBody.getURI()), targets,
segments[segments.length - 1]);
} else {
ROSRService.addAnnotation(targetRO, URI.create(annBody.getURI()), targets);
}
} catch (AccessDeniedException | DigitalLibraryException | NotFoundException e1) {
LOGGER.error("Could not add the annotation", e1);
}
} else {
if (isInternalResource(resourceURI, status.getCopyfrom())) {
try {
Client client = Client.create();
WebResource webResource = client.resource(resourceURI.toString());
ClientResponse response = webResource.get(ClientResponse.class);
URI resourcePath = status.getCopyfrom().relativize(resourceURI);
URI targetURI = target.resolve(resourcePath);
ROSRService.aggregateInternalResource(targetRO, targetURI, response.getEntityInputStream(),
response.getType().toString(), null);
//TODO improve resource type detection mechanism!!
if (!resource.hasRDFType(RO.Resource)) {
ROSRService.convertAggregatedResourceToAnnotationBody(targetRO, targetURI);
}
changedURIs.put(resourceURI, targetURI);
} catch (AccessDeniedException | DigitalLibraryException | NotFoundException e) {
throw new OperationFailedException("Could not create aggregate internal resource: "
+ resourceURI, e);
}
} else {
try {
ROSRService.aggregateExternalResource(targetRO, resourceURI);
} catch (AccessDeniedException | DigitalLibraryException | NotFoundException e) {
throw new OperationFailedException("Could not create aggregate external resource: "
+ resourceURI, e);
}
}
}
}
for (Map.Entry<URI, URI> e : changedURIs.entrySet()) {
ROSRService.SMS.get().changeURIInManifestAndAnnotationBodies(targetRO, e.getKey(), e.getValue(), false);
}
for (Map.Entry<URI, URI> e : changedURIs.entrySet()) {
ROSRService.SMS.get().changeURIInManifestAndAnnotationBodies(targetRO, e.getKey(), e.getValue(), true);
}
} finally {
HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().commit();
}
}
| public void execute(JobStatus status)
throws OperationFailedException {
HibernateUtil.getSessionFactory().getCurrentSession().beginTransaction();
try {
URI target = status.getCopyfrom().resolve("../" + id + "/");
int i = 1;
String sufix = "";
while (ROSRService.SMS.get().containsNamedGraph(target.resolve(ResearchObject.MANIFEST_PATH))) {
sufix = "-" + Integer.toString(i);
target = status.getCopyfrom().resolve("../" + id + "-" + (i++) + "/");
}
status.setTarget(id + sufix);
ResearchObject targetRO = ResearchObject.create(target);
ResearchObject sourceRO = ResearchObject.create(status.getCopyfrom());
try {
ROSRService.createResearchObject(targetRO, status.getType(), sourceRO);
} catch (ConflictException | DigitalLibraryException | NotFoundException | AccessDeniedException e) {
throw new OperationFailedException("Could not create the target research object", e);
}
OntModel model = ModelFactory.createOntologyModel(OntModelSpec.OWL_LITE_MEM);
model.read(sourceRO.getManifestUri().toString());
Individual source = model.getIndividual(sourceRO.getUri().toString());
if (source == null) {
throw new OperationFailedException("The manifest does not describe the research object");
}
List<RDFNode> aggregatedResources = source.listPropertyValues(ORE.aggregates).toList();
Map<URI, URI> changedURIs = new HashMap<>();
changedURIs.put(sourceRO.getManifestUri(), targetRO.getManifestUri());
for (RDFNode aggregatedResource : aggregatedResources) {
if (Thread.interrupted()) {
try {
ROSRService.deleteResearchObject(targetRO);
} catch (DigitalLibraryException | NotFoundException e) {
LOGGER.error("Could not delete the target when aborting: " + target, e);
}
return;
}
if (!aggregatedResource.isURIResource()) {
LOGGER.warn("Aggregated node " + aggregatedResource.toString() + " is not a URI resource");
continue;
}
Individual resource = aggregatedResource.as(Individual.class);
URI resourceURI = URI.create(resource.getURI());
if (resource.hasRDFType(RO.AggregatedAnnotation)) {
Resource annBody = resource.getPropertyResourceValue(AO.body);
List<URI> targets = new ArrayList<>();
List<RDFNode> annotationTargets = resource.listPropertyValues(RO.annotatesAggregatedResource)
.toList();
for (RDFNode annTarget : annotationTargets) {
if (!annTarget.isURIResource()) {
LOGGER.warn("Annotation target " + annTarget.toString() + " is not a URI resource");
continue;
}
targets.add(URI.create(annTarget.asResource().getURI()));
}
try {
//FIXME use a dedicated class for an Annotation
String[] segments = resource.getURI().split("/");
if (segments.length > 0) {
ROSRService.addAnnotation(targetRO, URI.create(annBody.getURI()), targets,
segments[segments.length - 1]);
} else {
ROSRService.addAnnotation(targetRO, URI.create(annBody.getURI()), targets);
}
} catch (AccessDeniedException | DigitalLibraryException | NotFoundException e1) {
LOGGER.error("Could not add the annotation", e1);
}
} else {
if (isInternalResource(resourceURI, status.getCopyfrom())) {
try {
Client client = Client.create();
WebResource webResource = client.resource(resourceURI.toString());
ClientResponse response = webResource.get(ClientResponse.class);
URI resourcePath = status.getCopyfrom().relativize(resourceURI);
URI targetURI = target.resolve(resourcePath);
ROSRService.aggregateInternalResource(targetRO, targetURI, response.getEntityInputStream(),
response.getType().toString(), null);
//TODO improve resource type detection mechanism!!
if (!resource.hasRDFType(RO.Resource)) {
ROSRService.convertAggregatedResourceToAnnotationBody(targetRO, targetURI);
}
changedURIs.put(resourceURI, targetURI);
} catch (AccessDeniedException | DigitalLibraryException | NotFoundException e) {
throw new OperationFailedException("Could not create aggregate internal resource: "
+ resourceURI, e);
}
} else {
try {
ROSRService.aggregateExternalResource(targetRO, resourceURI);
} catch (AccessDeniedException | DigitalLibraryException | NotFoundException e) {
throw new OperationFailedException("Could not create aggregate external resource: "
+ resourceURI, e);
}
}
}
}
for (Map.Entry<URI, URI> e : changedURIs.entrySet()) {
ROSRService.SMS.get().changeURIInManifestAndAnnotationBodies(targetRO, e.getKey(), e.getValue(), false);
}
for (Map.Entry<URI, URI> e : changedURIs.entrySet()) {
ROSRService.SMS.get().changeURIInManifestAndAnnotationBodies(targetRO, e.getKey(), e.getValue(), true);
}
} finally {
HibernateUtil.getSessionFactory().getCurrentSession().getTransaction().commit();
}
}
|
diff --git a/org.eclipse.mylyn.monitor.ui/src/org/eclipse/mylyn/monitor/ui/preferences/MylarMonitorPreferencePage.java b/org.eclipse.mylyn.monitor.ui/src/org/eclipse/mylyn/monitor/ui/preferences/MylarMonitorPreferencePage.java
index bb89a624..42939c50 100644
--- a/org.eclipse.mylyn.monitor.ui/src/org/eclipse/mylyn/monitor/ui/preferences/MylarMonitorPreferencePage.java
+++ b/org.eclipse.mylyn.monitor.ui/src/org/eclipse/mylyn/monitor/ui/preferences/MylarMonitorPreferencePage.java
@@ -1,117 +1,117 @@
/*******************************************************************************
* Copyright (c) 2004 - 2005 University Of British Columbia 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:
* University Of British Columbia - initial API and implementation
*******************************************************************************/
package org.eclipse.mylar.monitor.ui.preferences;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.jface.preference.IntegerFieldEditor;
import org.eclipse.jface.preference.PreferencePage;
import org.eclipse.mylar.core.MylarPlugin;
import org.eclipse.mylar.monitor.MylarMonitorPlugin;
import org.eclipse.swt.SWT;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Label;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchPreferencePage;
/**
* @author Ken Sueda
*/
public class MylarMonitorPreferencePage extends PreferencePage implements
IWorkbenchPreferencePage {
private IntegerFieldEditor userStudyId;
public MylarMonitorPreferencePage() {
super();
setPreferenceStore(MylarMonitorPlugin.getPrefs());
}
@Override
protected Control createContents(Composite parent) {
Composite container = new Composite(parent, SWT.NULL);
GridLayout layout = new GridLayout(1, false);
container.setLayout (layout);
createStatisticsSection(container);
createUserStudyIdSection(container);
return container;
}
public void init(IWorkbench workbench) {
// Nothing to init
}
private void createStatisticsSection(Composite parent) {
Composite container = new Composite(parent, SWT.NULL);
GridData gridData = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
container.setLayoutData(gridData);
GridLayout gl = new GridLayout(1, false);
container.setLayout(gl);
Label label = new Label(container, SWT.NULL);
label.setText("Number of user events: " + getPreferenceStore().getInt(MylarMonitorPlugin.PREF_NUM_USER_EVENTS));
// label = new Label(container, SWT.NULL);
// label.setText("Number of total events: " + MylarMonitorPlugin.getDefault().getTotalNumberEvents());
}
private void createUserStudyIdSection(Composite parent) {
Composite container = new Composite(parent, SWT.NULL);
GridData gridData = new GridData(GridData.HORIZONTAL_ALIGN_FILL);
container.setLayoutData(gridData);
GridLayout gl = new GridLayout(1, false);
container.setLayout(gl);
userStudyId = new IntegerFieldEditor("", " User ID:", container); // HACK
userStudyId.setErrorMessage("Your user id must be an integer");
int uidNum = MylarPlugin.getDefault().getPreferenceStore().getInt(MylarPlugin.USER_ID);
if (uidNum == 0)
uidNum = -1;
userStudyId.setEmptyStringAllowed(false);
userStudyId.setStringValue(uidNum + "");
}
@Override
public boolean performOk() {
int uidNum = -1;
try{
- if(userStudyId.getStringValue() == ""){
+ if(userStudyId.getStringValue() == null || userStudyId.getStringValue().equals("")){
uidNum = -1;
userStudyId.setStringValue(uidNum + "");
}
else{
uidNum = userStudyId.getIntValue();
}
if(uidNum <= 0 && uidNum != -1){
MessageDialog.openError(Display.getDefault().getActiveShell(), "User Study ID Incorrect", "The user study id must be a posative integer");
return false;
}
if(uidNum != -1 && uidNum % 17 != 1){
MessageDialog.openError(Display.getDefault().getActiveShell(), "User Study ID Incorrect", "Your user study id is not valid, please make sure it is correct or get a new id");
return false;
}
}catch(NumberFormatException e){
MessageDialog.openError(Display.getDefault().getActiveShell(), "User Study ID Incorrect", "The user study id must be a posative integer");
return false;
}
MylarPlugin.getDefault().getPreferenceStore().setValue(MylarPlugin.USER_ID, uidNum);
return true;
}
@Override
public boolean performCancel() {
userStudyId.setStringValue(MylarPlugin.getDefault().getPreferenceStore().getInt(MylarPlugin.USER_ID)+"");
return true;
}
}
| true | true | public boolean performOk() {
int uidNum = -1;
try{
if(userStudyId.getStringValue() == ""){
uidNum = -1;
userStudyId.setStringValue(uidNum + "");
}
else{
uidNum = userStudyId.getIntValue();
}
if(uidNum <= 0 && uidNum != -1){
MessageDialog.openError(Display.getDefault().getActiveShell(), "User Study ID Incorrect", "The user study id must be a posative integer");
return false;
}
if(uidNum != -1 && uidNum % 17 != 1){
MessageDialog.openError(Display.getDefault().getActiveShell(), "User Study ID Incorrect", "Your user study id is not valid, please make sure it is correct or get a new id");
return false;
}
}catch(NumberFormatException e){
MessageDialog.openError(Display.getDefault().getActiveShell(), "User Study ID Incorrect", "The user study id must be a posative integer");
return false;
}
MylarPlugin.getDefault().getPreferenceStore().setValue(MylarPlugin.USER_ID, uidNum);
return true;
}
| public boolean performOk() {
int uidNum = -1;
try{
if(userStudyId.getStringValue() == null || userStudyId.getStringValue().equals("")){
uidNum = -1;
userStudyId.setStringValue(uidNum + "");
}
else{
uidNum = userStudyId.getIntValue();
}
if(uidNum <= 0 && uidNum != -1){
MessageDialog.openError(Display.getDefault().getActiveShell(), "User Study ID Incorrect", "The user study id must be a posative integer");
return false;
}
if(uidNum != -1 && uidNum % 17 != 1){
MessageDialog.openError(Display.getDefault().getActiveShell(), "User Study ID Incorrect", "Your user study id is not valid, please make sure it is correct or get a new id");
return false;
}
}catch(NumberFormatException e){
MessageDialog.openError(Display.getDefault().getActiveShell(), "User Study ID Incorrect", "The user study id must be a posative integer");
return false;
}
MylarPlugin.getDefault().getPreferenceStore().setValue(MylarPlugin.USER_ID, uidNum);
return true;
}
|
diff --git a/src/com/vaadin/demo/sampler/SamplerApplication.java b/src/com/vaadin/demo/sampler/SamplerApplication.java
index cf06d929e..ea35d986a 100644
--- a/src/com/vaadin/demo/sampler/SamplerApplication.java
+++ b/src/com/vaadin/demo/sampler/SamplerApplication.java
@@ -1,777 +1,778 @@
package com.vaadin.demo.sampler;
import java.net.URI;
import java.net.URL;
import java.util.Collection;
import java.util.HashMap;
import java.util.Iterator;
import com.vaadin.Application;
import com.vaadin.data.Property;
import com.vaadin.data.Property.ValueChangeEvent;
import com.vaadin.data.util.HierarchicalContainer;
import com.vaadin.data.util.ObjectProperty;
import com.vaadin.demo.sampler.ActiveLink.LinkActivatedEvent;
import com.vaadin.demo.sampler.ModeSwitch.ModeSwitchEvent;
import com.vaadin.event.ItemClickEvent;
import com.vaadin.event.ItemClickEvent.ItemClickListener;
import com.vaadin.terminal.ClassResource;
import com.vaadin.terminal.DownloadStream;
import com.vaadin.terminal.ExternalResource;
import com.vaadin.terminal.Resource;
import com.vaadin.terminal.ThemeResource;
import com.vaadin.terminal.URIHandler;
import com.vaadin.ui.Alignment;
import com.vaadin.ui.Button;
import com.vaadin.ui.ComboBox;
import com.vaadin.ui.Component;
import com.vaadin.ui.CustomComponent;
import com.vaadin.ui.Embedded;
import com.vaadin.ui.GridLayout;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.Panel;
import com.vaadin.ui.PopupView;
import com.vaadin.ui.SplitPanel;
import com.vaadin.ui.Table;
import com.vaadin.ui.Tree;
import com.vaadin.ui.UriFragmentUtility;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.Window;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.PopupView.PopupVisibilityEvent;
import com.vaadin.ui.UriFragmentUtility.FragmentChangedEvent;
import com.vaadin.ui.UriFragmentUtility.FragmentChangedListener;
@SuppressWarnings("serial")
public class SamplerApplication extends Application {
// All features in one container
private static final HierarchicalContainer allFeatures = FeatureSet.FEATURES
.getContainer(true);
// init() inits
private static final String THEME_NAME = "sampler";
// used when trying to guess theme location
private static String APP_URL = null;
@Override
public void init() {
setTheme("sampler");
setMainWindow(new SamplerWindow());
APP_URL = getURL().toString();
}
/**
* Tries to guess theme location.
*
* @return
*/
public static String getThemeBase() {
try {
URI uri = new URI(APP_URL + "../VAADIN/themes/" + THEME_NAME + "/");
return uri.normalize().toString();
} catch (Exception e) {
System.err.println("Theme location could not be resolved:" + e);
}
return "/VAADIN/themes/" + THEME_NAME + "/";
}
// Supports multiple browser windows
@Override
public Window getWindow(String name) {
Window w = super.getWindow(name);
if (w == null) {
if (name.startsWith("src")) {
w = new SourceWindow();
} else {
w = new SamplerWindow();
w.setName(name);
}
addWindow(w);
}
return w;
}
/**
* Gets absolute path for given Feature
*
* @param f
* the Feature whose path to get, of null if not found
* @return the path of the Feature
*/
public static String getPathFor(Feature f) {
if (f == null) {
return "";
}
if (allFeatures.containsId(f)) {
String path = f.getPathName();
f = (Feature) allFeatures.getParent(f);
while (f != null) {
path = f.getPathName() + "/" + path;
f = (Feature) allFeatures.getParent(f);
}
return path;
}
return "";
}
/**
* Gets the instance for the given Feature class, e.g DummyFeature.class.
*
* @param clazz
* @return
*/
public static Feature getFeatureFor(Class clazz) {
for (Iterator it = allFeatures.getItemIds().iterator(); it.hasNext();) {
Feature f = (Feature) it.next();
if (f.getClass() == clazz) {
return f;
}
}
return null;
}
/**
* The main window for Sampler, contains the full application UI.
*
*/
class SamplerWindow extends Window {
private FeatureList currentList = new FeatureGrid();
private FeatureView featureView = new FeatureView();
private ObjectProperty currentFeature = new ObjectProperty(null,
Feature.class);
private ModeSwitch mode;
private SplitPanel mainSplit;
private Tree navigationTree;
// itmill: UA-658457-6
private GoogleAnalytics webAnalytics = new GoogleAnalytics(
"UA-658457-6", "none");
// "backbutton"
UriFragmentUtility uriFragmentUtility = new UriFragmentUtility();
// breadcrumbs
BreadCrumbs breadcrumbs = new BreadCrumbs();
Button previousSample;
Button nextSample;
private ComboBox search;
@Override
public void detach() {
super.detach();
search.setContainerDataSource(null);
navigationTree.setContainerDataSource(null);
}
SamplerWindow() {
// Main top/expanded-bottom layout
VerticalLayout mainExpand = new VerticalLayout();
setLayout(mainExpand);
setSizeFull();
mainExpand.setSizeFull();
+ setCaption("Vaadin Sampler");
// topbar (navigation)
HorizontalLayout nav = new HorizontalLayout();
mainExpand.addComponent(nav);
nav.setHeight("44px");
nav.setWidth("100%");
nav.setStyleName("topbar");
nav.setSpacing(true);
nav.setMargin(false, true, false, false);
// Upper left logo
Component logo = createLogo();
nav.addComponent(logo);
nav.setComponentAlignment(logo, Alignment.MIDDLE_LEFT);
// Breadcrumbs
nav.addComponent(breadcrumbs);
nav.setExpandRatio(breadcrumbs, 1);
nav.setComponentAlignment(breadcrumbs, Alignment.MIDDLE_LEFT);
// invisible analytics -component
nav.addComponent(webAnalytics);
// "backbutton"
nav.addComponent(uriFragmentUtility);
uriFragmentUtility.addListener(new FragmentChangedListener() {
public void fragmentChanged(FragmentChangedEvent source) {
String frag = source.getUriFragmentUtility().getFragment();
setFeature(frag);
}
});
// Main left/right split; hidden menu tree
mainSplit = new SplitPanel(SplitPanel.ORIENTATION_HORIZONTAL);
mainSplit.setSizeFull();
mainSplit.setStyleName("main-split");
mainExpand.addComponent(mainSplit);
mainExpand.setExpandRatio(mainSplit, 1);
// List/grid/coverflow
mode = createModeSwitch();
mode.setMode(currentList);
nav.addComponent(mode);
nav.setComponentAlignment(mode, Alignment.MIDDLE_LEFT);
// Layouts for top area buttons
HorizontalLayout quicknav = new HorizontalLayout();
HorizontalLayout arrows = new HorizontalLayout();
nav.addComponent(quicknav);
nav.addComponent(arrows);
nav.setComponentAlignment(quicknav, Alignment.MIDDLE_LEFT);
nav.setComponentAlignment(arrows, Alignment.MIDDLE_LEFT);
quicknav.setStyleName("segment");
arrows.setStyleName("segment");
// Previous sample
previousSample = createPrevButton();
arrows.addComponent(previousSample);
// Next sample
nextSample = createNextButton();
arrows.addComponent(nextSample);
// "Search" combobox
// TODO add input prompt
Component searchComponent = createSearch();
quicknav.addComponent(searchComponent);
// Menu tree, initially hidden
navigationTree = createMenuTree();
mainSplit.setFirstComponent(navigationTree);
// Show / hide tree
Component treeSwitch = createTreeSwitch();
quicknav.addComponent(treeSwitch);
addListener(new CloseListener() {
public void windowClose(CloseEvent e) {
if (getMainWindow() != SamplerWindow.this) {
SamplerApplication.this
.removeWindow(SamplerWindow.this);
}
}
});
}
@SuppressWarnings("unchecked")
public void removeSubwindows() {
Collection<Window> wins = getChildWindows();
if (null != wins) {
for (Window w : wins) {
removeWindow(w);
}
}
}
/**
* Displays a Feature(Set)
*
* @param f
* the Feature(Set) to show
*/
public void setFeature(Feature f) {
removeSubwindows();
currentFeature.setValue(f);
String path = getPathFor(f);
webAnalytics.trackPageview(path);
uriFragmentUtility.setFragment(path, false);
breadcrumbs.setPath(path);
previousSample.setEnabled(f != null);
nextSample.setEnabled(!allFeatures.isLastId(f));
updateFeatureList(currentList);
}
/**
* Displays a Feature(Set) matching the given path, or the main view if
* no matching Feature(Set) is found.
*
* @param path
* the path of the Feature(Set) to show
*/
public void setFeature(String path) {
Feature f = FeatureSet.FEATURES.getFeatureByPath(path);
setFeature(f);
}
/*
* SamplerWindow helpers
*/
private Component createSearch() {
search = new ComboBox();
search.setWidth("160px");
search.setNewItemsAllowed(false);
search.setFilteringMode(ComboBox.FILTERINGMODE_CONTAINS);
search.setNullSelectionAllowed(true);
search.setImmediate(true);
search.setContainerDataSource(allFeatures);
for (Iterator it = allFeatures.getItemIds().iterator(); it
.hasNext();) {
Object id = it.next();
if (id instanceof FeatureSet) {
search.setItemIcon(id, new ClassResource("folder.gif",
SamplerApplication.this));
}
}
search.addListener(new ComboBox.ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
Feature f = (Feature) event.getProperty().getValue();
if (f != null) {
SamplerWindow.this.setFeature(f);
event.getProperty().setValue(null);
}
}
});
// TODO add icons for section/sample
/*
* PopupView pv = new PopupView("", search) { public void
* changeVariables(Object source, Map variables) {
* super.changeVariables(source, variables); if (isPopupVisible()) {
* search.focus(); } } };
*/
PopupView pv = new PopupView("<span></span>", search);
pv.addListener(new PopupView.PopupVisibilityListener() {
public void popupVisibilityChange(PopupVisibilityEvent event) {
if (event.isPopupVisible()) {
search.focus();
}
}
});
pv.setStyleName("quickjump");
pv.setDescription("Quick jump");
return pv;
}
private Component createLogo() {
Button logo = new Button("", new Button.ClickListener() {
public void buttonClick(ClickEvent event) {
setFeature((Feature) null);
}
});
logo.setDescription("↶ Home");
logo.setStyleName(Button.STYLE_LINK);
logo.addStyleName("logo");
logo.setIcon(new ThemeResource("sampler/sampler.png"));
return logo;
}
private Button createNextButton() {
Button b = new Button("", new ClickListener() {
public void buttonClick(ClickEvent event) {
Object curr = currentFeature.getValue();
Object next = allFeatures.nextItemId(curr);
while (next != null && next instanceof FeatureSet) {
next = allFeatures.nextItemId(next);
}
if (next != null) {
currentFeature.setValue(next);
} else {
// could potentially occur if there is an empty section
showNotification("Last sample");
}
}
});
b.setStyleName("next");
b.setDescription("Jump to the next sample");
return b;
}
private Button createPrevButton() {
Button b = new Button("", new ClickListener() {
public void buttonClick(ClickEvent event) {
Object curr = currentFeature.getValue();
Object prev = allFeatures.prevItemId(curr);
while (prev != null && prev instanceof FeatureSet) {
prev = allFeatures.prevItemId(prev);
}
currentFeature.setValue(prev);
}
});
b.setEnabled(false);
b.setStyleName("previous");
b.setDescription("Jump to the previous sample");
return b;
}
private Component createTreeSwitch() {
final Button b = new Button();
b.setStyleName("tree-switch");
b.setDescription("Toggle sample tree visibility");
b.addListener(new Button.ClickListener() {
public void buttonClick(ClickEvent event) {
if (b.getStyleName().contains("down")) {
b.removeStyleName("down");
mainSplit.setSplitPosition(0);
navigationTree.setVisible(false);
mainSplit.setLocked(true);
} else {
b.addStyleName("down");
mainSplit.setSplitPosition(20);
mainSplit.setLocked(false);
navigationTree.setVisible(true);
}
}
});
mainSplit.setSplitPosition(0);
navigationTree.setVisible(false);
mainSplit.setLocked(true);
return b;
}
private ModeSwitch createModeSwitch() {
ModeSwitch m = new ModeSwitch();
m.addMode(currentList, "", "View as Icons", new ThemeResource(
"sampler/grid.png"));
/*- no CoverFlow yet
m.addMode(coverFlow, "", "View as Icons", new ThemeResource(
"sampler/flow.gif"));
*/
m.addMode(new FeatureTable(), "", "View as List",
new ThemeResource("sampler/list.png"));
m.addListener(new ModeSwitch.ModeSwitchListener() {
public void componentEvent(Event event) {
if (event instanceof ModeSwitchEvent) {
updateFeatureList((FeatureList) ((ModeSwitchEvent) event)
.getMode());
}
}
});
return m;
}
private Tree createMenuTree() {
final Tree tree = new Tree();
tree.setImmediate(true);
tree.setStyleName("menu");
tree.setContainerDataSource(allFeatures);
currentFeature.addListener(new Property.ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
Feature f = (Feature) event.getProperty().getValue();
Feature v = (Feature) tree.getValue();
if ((f != null && !f.equals(v)) || (f == null && v != null)) {
tree.setValue(f);
}
}
});
for (int i = 0; i < FeatureSet.FEATURES.getFeatures().length; i++) {
tree
.expandItemsRecursively(FeatureSet.FEATURES
.getFeatures()[i]);
}
tree.expandItemsRecursively(FeatureSet.FEATURES);
tree.addListener(new Tree.ValueChangeListener() {
public void valueChange(ValueChangeEvent event) {
Feature f = (Feature) event.getProperty().getValue();
setFeature(f);
}
});
return tree;
}
private void updateFeatureList(FeatureList list) {
currentList = list;
Feature val = (Feature) currentFeature.getValue();
if (val == null) {
currentList.setFeatureContainer(allFeatures);
mainSplit.setSecondComponent(currentList);
mode.setVisible(true);
} else if (val instanceof FeatureSet) {
currentList.setFeatureContainer(((FeatureSet) val)
.getContainer(true));
mainSplit.setSecondComponent(currentList);
mode.setVisible(true);
} else {
mainSplit.setSecondComponent(featureView);
featureView.setFeature(val);
mode.setVisible(false);
}
}
}
private class BreadCrumbs extends CustomComponent implements
ActiveLink.LinkActivatedListener {
HorizontalLayout layout;
BreadCrumbs() {
layout = new HorizontalLayout();
layout.setSpacing(true);
setCompositionRoot(layout);
setStyleName("breadcrumbs");
setPath(null);
}
public void setPath(String path) {
// could be optimized: always builds path from scratch
layout.removeAllComponents();
{ // home
ActiveLink link = new ActiveLink("Home", new ExternalResource(
"#"));
link.addListener(this);
layout.addComponent(link);
}
if (path != null && !"".equals(path)) {
String parts[] = path.split("/");
String current = "";
ActiveLink link = null;
for (int i = 0; i < parts.length; i++) {
layout.addComponent(new Label("»",
Label.CONTENT_XHTML));
current += (i > 0 ? "/" : "") + parts[i];
Feature f = FeatureSet.FEATURES.getFeatureByPath(current);
link = new ActiveLink(f.getName(), new ExternalResource("#"
+ getPathFor(f)));
link.setData(f);
link.addListener(this);
layout.addComponent(link);
}
if (link != null) {
link.setStyleName("bold");
}
}
}
public void linkActivated(LinkActivatedEvent event) {
if (!event.isLinkOpened()) {
((SamplerWindow) getWindow()).setFeature((Feature) event
.getActiveLink().getData());
}
}
}
/**
* Components capable of listing Features should implement this.
*
*/
interface FeatureList extends Component {
/**
* Shows the given Features
*
* @param c
* Container with Features to show.
*/
public void setFeatureContainer(HierarchicalContainer c);
}
/**
* Table -mode FeatureList. Displays the features in a Table.
*/
private class FeatureTable extends Table implements FeatureList {
private HashMap<Object, Resource> iconCache = new HashMap<Object, Resource>();
FeatureTable() {
setStyleName("featuretable");
alwaysRecalculateColumnWidths = true;
setSelectable(false);
setSizeFull();
setColumnHeaderMode(Table.COLUMN_HEADER_MODE_HIDDEN);
addGeneratedColumn(Feature.PROPERTY_ICON,
new Table.ColumnGenerator() {
public Component generateCell(Table source,
Object itemId, Object columnId) {
Feature f = (Feature) itemId;
if (f instanceof FeatureSet) {
// no icon for sections
return null;
}
String resId = "75-" + f.getIconName();
Resource res = iconCache.get(resId);
if (res == null) {
res = new ClassResource(f.getClass(), resId,
SamplerApplication.this);
iconCache.put(resId, res);
}
Embedded emb = new Embedded("", res);
emb.setWidth("48px");
emb.setHeight("48px");
emb.setType(Embedded.TYPE_IMAGE);
return emb;
}
});
addGeneratedColumn("", new Table.ColumnGenerator() {
public Component generateCell(Table source, Object itemId,
Object columnId) {
final Feature feature = (Feature) itemId;
if (feature instanceof FeatureSet) {
return null;
} else {
ActiveLink b = new ActiveLink("View sample ‣",
new ExternalResource("#" + getPathFor(feature)));
b.addListener(new ActiveLink.LinkActivatedListener() {
public void linkActivated(LinkActivatedEvent event) {
if (!event.isLinkOpened()) {
((SamplerWindow) getWindow())
.setFeature(feature);
}
}
});
b.setStyleName(Button.STYLE_LINK);
return b;
}
}
});
addListener(new ItemClickListener() {
public void itemClick(ItemClickEvent event) {
Feature f = (Feature) event.getItemId();
if (event.getButton() == ItemClickEvent.BUTTON_MIDDLE
|| event.isCtrlKey() || event.isShiftKey()) {
getWindow().open(
new ExternalResource(getURL() + "#"
+ getPathFor(f)), "_blank");
} else {
((SamplerWindow) getWindow()).setFeature(f);
}
}
});
setCellStyleGenerator(new CellStyleGenerator() {
public String getStyle(Object itemId, Object propertyId) {
if (propertyId == null && itemId instanceof FeatureSet) {
if (allFeatures.isRoot(itemId)) {
return "section";
} else {
return "subsection";
}
}
return null;
}
});
}
public void setFeatureContainer(HierarchicalContainer c) {
setContainerDataSource(c);
setVisibleColumns(new Object[] { Feature.PROPERTY_ICON,
Feature.PROPERTY_NAME, "" });
setColumnWidth(Feature.PROPERTY_ICON, 60);
}
}
private class FeatureGrid extends Panel implements FeatureList {
GridLayout grid = new GridLayout(11, 1);
private HashMap<Object, Resource> iconCache = new HashMap<Object, Resource>();
FeatureGrid() {
setSizeFull();
setLayout(grid);
grid.setSizeUndefined();
grid.setSpacing(true);
setStyleName(Panel.STYLE_LIGHT);
}
public void setFeatureContainer(HierarchicalContainer c) {
grid.removeAllComponents();
Collection features = c.getItemIds();
for (Iterator it = features.iterator(); it.hasNext();) {
final Feature f = (Feature) it.next();
if (f instanceof FeatureSet) {
grid.newLine();
Label title = new Label(f.getName());
if (c.isRoot(f)) {
title.setWidth("100%");
title.setStyleName("section");
grid.setRows(grid.getCursorY() + 1);
grid.addComponent(title, 0, grid.getCursorY(), grid
.getColumns() - 1, grid.getCursorY());
grid
.setComponentAlignment(title,
Alignment.MIDDLE_LEFT);
} else {
title.setStyleName("subsection");
grid.addComponent(title);
grid
.setComponentAlignment(title,
Alignment.MIDDLE_LEFT);
}
} else {
if (grid.getCursorX() == 0) {
grid.space();
}
Button b = new Button();
b.setStyleName(Button.STYLE_LINK);
b.addStyleName("screenshot");
String resId = "75-" + f.getIconName();
Resource res = iconCache.get(resId);
if (res == null) {
res = new ClassResource(f.getClass(), resId,
SamplerApplication.this);
iconCache.put(resId, res);
}
b.setIcon(res);
b.setWidth("75px");
b.setHeight("75px");
b.setDescription("<h3>" + f.getName() + "</h3>");
b.addListener(new Button.ClickListener() {
public void buttonClick(ClickEvent event) {
((SamplerWindow) getWindow()).setFeature(f);
}
});
grid.addComponent(b);
}
}
}
}
public static HierarchicalContainer getAllFeatures() {
return allFeatures;
}
public class SourceWindow extends Window {
public SourceWindow() {
addURIHandler(new URIHandler() {
public DownloadStream handleURI(URL context, String relativeUri) {
Feature f = FeatureSet.FEATURES
.getFeatureByPath(relativeUri);
if (f != null) {
addComponent(new CodeLabel(f.getSource()));
} else {
addComponent(new Label("Sorry, no source found for "
+ relativeUri));
}
return null;
}
});
addListener(new CloseListener() {
public void windowClose(CloseEvent e) {
SamplerApplication.this.removeWindow(SourceWindow.this);
}
});
}
}
@Override
public void close() {
removeWindow(getMainWindow());
super.close();
}
}
| true | true | SamplerWindow() {
// Main top/expanded-bottom layout
VerticalLayout mainExpand = new VerticalLayout();
setLayout(mainExpand);
setSizeFull();
mainExpand.setSizeFull();
// topbar (navigation)
HorizontalLayout nav = new HorizontalLayout();
mainExpand.addComponent(nav);
nav.setHeight("44px");
nav.setWidth("100%");
nav.setStyleName("topbar");
nav.setSpacing(true);
nav.setMargin(false, true, false, false);
// Upper left logo
Component logo = createLogo();
nav.addComponent(logo);
nav.setComponentAlignment(logo, Alignment.MIDDLE_LEFT);
// Breadcrumbs
nav.addComponent(breadcrumbs);
nav.setExpandRatio(breadcrumbs, 1);
nav.setComponentAlignment(breadcrumbs, Alignment.MIDDLE_LEFT);
// invisible analytics -component
nav.addComponent(webAnalytics);
// "backbutton"
nav.addComponent(uriFragmentUtility);
uriFragmentUtility.addListener(new FragmentChangedListener() {
public void fragmentChanged(FragmentChangedEvent source) {
String frag = source.getUriFragmentUtility().getFragment();
setFeature(frag);
}
});
// Main left/right split; hidden menu tree
mainSplit = new SplitPanel(SplitPanel.ORIENTATION_HORIZONTAL);
mainSplit.setSizeFull();
mainSplit.setStyleName("main-split");
mainExpand.addComponent(mainSplit);
mainExpand.setExpandRatio(mainSplit, 1);
// List/grid/coverflow
mode = createModeSwitch();
mode.setMode(currentList);
nav.addComponent(mode);
nav.setComponentAlignment(mode, Alignment.MIDDLE_LEFT);
// Layouts for top area buttons
HorizontalLayout quicknav = new HorizontalLayout();
HorizontalLayout arrows = new HorizontalLayout();
nav.addComponent(quicknav);
nav.addComponent(arrows);
nav.setComponentAlignment(quicknav, Alignment.MIDDLE_LEFT);
nav.setComponentAlignment(arrows, Alignment.MIDDLE_LEFT);
quicknav.setStyleName("segment");
arrows.setStyleName("segment");
// Previous sample
previousSample = createPrevButton();
arrows.addComponent(previousSample);
// Next sample
nextSample = createNextButton();
arrows.addComponent(nextSample);
// "Search" combobox
// TODO add input prompt
Component searchComponent = createSearch();
quicknav.addComponent(searchComponent);
// Menu tree, initially hidden
navigationTree = createMenuTree();
mainSplit.setFirstComponent(navigationTree);
// Show / hide tree
Component treeSwitch = createTreeSwitch();
quicknav.addComponent(treeSwitch);
addListener(new CloseListener() {
public void windowClose(CloseEvent e) {
if (getMainWindow() != SamplerWindow.this) {
SamplerApplication.this
.removeWindow(SamplerWindow.this);
}
}
});
}
| SamplerWindow() {
// Main top/expanded-bottom layout
VerticalLayout mainExpand = new VerticalLayout();
setLayout(mainExpand);
setSizeFull();
mainExpand.setSizeFull();
setCaption("Vaadin Sampler");
// topbar (navigation)
HorizontalLayout nav = new HorizontalLayout();
mainExpand.addComponent(nav);
nav.setHeight("44px");
nav.setWidth("100%");
nav.setStyleName("topbar");
nav.setSpacing(true);
nav.setMargin(false, true, false, false);
// Upper left logo
Component logo = createLogo();
nav.addComponent(logo);
nav.setComponentAlignment(logo, Alignment.MIDDLE_LEFT);
// Breadcrumbs
nav.addComponent(breadcrumbs);
nav.setExpandRatio(breadcrumbs, 1);
nav.setComponentAlignment(breadcrumbs, Alignment.MIDDLE_LEFT);
// invisible analytics -component
nav.addComponent(webAnalytics);
// "backbutton"
nav.addComponent(uriFragmentUtility);
uriFragmentUtility.addListener(new FragmentChangedListener() {
public void fragmentChanged(FragmentChangedEvent source) {
String frag = source.getUriFragmentUtility().getFragment();
setFeature(frag);
}
});
// Main left/right split; hidden menu tree
mainSplit = new SplitPanel(SplitPanel.ORIENTATION_HORIZONTAL);
mainSplit.setSizeFull();
mainSplit.setStyleName("main-split");
mainExpand.addComponent(mainSplit);
mainExpand.setExpandRatio(mainSplit, 1);
// List/grid/coverflow
mode = createModeSwitch();
mode.setMode(currentList);
nav.addComponent(mode);
nav.setComponentAlignment(mode, Alignment.MIDDLE_LEFT);
// Layouts for top area buttons
HorizontalLayout quicknav = new HorizontalLayout();
HorizontalLayout arrows = new HorizontalLayout();
nav.addComponent(quicknav);
nav.addComponent(arrows);
nav.setComponentAlignment(quicknav, Alignment.MIDDLE_LEFT);
nav.setComponentAlignment(arrows, Alignment.MIDDLE_LEFT);
quicknav.setStyleName("segment");
arrows.setStyleName("segment");
// Previous sample
previousSample = createPrevButton();
arrows.addComponent(previousSample);
// Next sample
nextSample = createNextButton();
arrows.addComponent(nextSample);
// "Search" combobox
// TODO add input prompt
Component searchComponent = createSearch();
quicknav.addComponent(searchComponent);
// Menu tree, initially hidden
navigationTree = createMenuTree();
mainSplit.setFirstComponent(navigationTree);
// Show / hide tree
Component treeSwitch = createTreeSwitch();
quicknav.addComponent(treeSwitch);
addListener(new CloseListener() {
public void windowClose(CloseEvent e) {
if (getMainWindow() != SamplerWindow.this) {
SamplerApplication.this
.removeWindow(SamplerWindow.this);
}
}
});
}
|
diff --git a/core/carrot2-source-boss/src/org/carrot2/source/boss/YSearchResponse.java b/core/carrot2-source-boss/src/org/carrot2/source/boss/YSearchResponse.java
index bcc4b1b37..700594709 100644
--- a/core/carrot2-source-boss/src/org/carrot2/source/boss/YSearchResponse.java
+++ b/core/carrot2-source-boss/src/org/carrot2/source/boss/YSearchResponse.java
@@ -1,164 +1,164 @@
/*
* Carrot2 project.
*
* Copyright (C) 2002-2011, Dawid Weiss, Stanisław Osiński.
* All rights reserved.
*
* Refer to the full license file "carrot2.LICENSE"
* in the root folder of the repository checkout or at:
* http://www.carrot2.org/carrot2.LICENSE
*/
package org.carrot2.source.boss;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
import org.carrot2.core.Document;
import org.carrot2.core.LanguageCode;
import org.carrot2.source.SearchEngineResponse;
import org.simpleframework.xml.*;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;
/**
* Search response model for Yahoo Boss.
*/
@Root(name = "ysearchresponse", strict = false)
final class YSearchResponse
{
@Attribute(name = "responsecode", required = false)
public Integer responseCode;
@Element(name = "nextpage", required = false)
public String nextPageURI;
@Element(name = "resultset_web", required = false)
public WebResultSet webResultSet;
@Element(name = "resultset_news", required = false)
public NewsResultSet newsResultSet;
@Element(name = "resultset_images", required = false)
public ImagesResultSet imagesResultSet;
@Element(name = "language", required = false)
public String language;
/**
* Populate {@link SearchEngineResponse} depending on the type of the search result
* returned.
*
* @param response
* @param requestedLanguage the language requested by the user, mapped from
* {@link BossLanguageCodes} to {@link LanguageCode}.
*/
public void populate(SearchEngineResponse response, LanguageCode requestedLanguage)
{
if (webResultSet != null)
{
response.metadata.put(SearchEngineResponse.RESULTS_TOTAL_KEY,
webResultSet.deephits);
if (webResultSet.results != null)
{
for (WebResult result : webResultSet.results)
{
final Document document = new Document(result.title, result.summary,
result.url);
document.setField(Document.CLICK_URL, result.clickURL);
try
{
document.setField(Document.SIZE, Long.parseLong(result.size));
}
catch (NumberFormatException e)
{
// Ignore if cannot parse.
}
response.results.add(document);
}
}
}
else if (newsResultSet != null)
{
response.metadata.put(SearchEngineResponse.RESULTS_TOTAL_KEY,
newsResultSet.deephits);
if (newsResultSet.results != null)
{
final Set<String> unknownLanguages = Sets.newHashSet();
for (NewsResult result : newsResultSet.results)
{
final Document document = new Document(result.title, result.summary,
result.url);
document.setField(Document.CLICK_URL, result.clickURL);
if (StringUtils.isNotBlank(result.source))
{
document.setField(Document.SOURCES, Lists.newArrayList(result.source));
}
// BOSS news returns language name as a string, but there is no list
// of supported values in the documentation. It seems that the strings
// are parallel to LanguageCode enum names, so we use them here.
if (StringUtils.isNotBlank(result.language))
{
try
{
- document.setLanguage(LanguageCode.valueOf(result.language));
+ document.setLanguage(LanguageCode.valueOf(result.language.toUpperCase()));
}
catch (IllegalArgumentException ignored)
{
unknownLanguages.add(result.language);
}
}
response.results.add(document);
}
// Log unknown languages, if any
if (!unknownLanguages.isEmpty())
{
org.slf4j.LoggerFactory.getLogger(this.getClass().getName()).warn(
"Unknown language: " + unknownLanguages.toString());
}
}
}
else if (imagesResultSet != null)
{
response.metadata.put(SearchEngineResponse.RESULTS_TOTAL_KEY,
imagesResultSet.deephits);
if (imagesResultSet.results != null)
{
for (ImageResult result : imagesResultSet.results)
{
final Document document = new Document(result.title, result.summary, result.refererURL);
// We use the image's referer page as the target click for the title.
document.setField(Document.CLICK_URL, result.refererClickURL);
// Attach thumbnail URL.
document.setField(Document.THUMBNAIL_URL, result.thumbnailURL);
response.results.add(document);
}
}
}
// If language has not been set based on the response, set it based on the request
if (requestedLanguage != null) {
for (Document document : response.results)
{
if (document.getLanguage() == null)
{
document.setLanguage(requestedLanguage);
}
}
}
}
}
| true | true | public void populate(SearchEngineResponse response, LanguageCode requestedLanguage)
{
if (webResultSet != null)
{
response.metadata.put(SearchEngineResponse.RESULTS_TOTAL_KEY,
webResultSet.deephits);
if (webResultSet.results != null)
{
for (WebResult result : webResultSet.results)
{
final Document document = new Document(result.title, result.summary,
result.url);
document.setField(Document.CLICK_URL, result.clickURL);
try
{
document.setField(Document.SIZE, Long.parseLong(result.size));
}
catch (NumberFormatException e)
{
// Ignore if cannot parse.
}
response.results.add(document);
}
}
}
else if (newsResultSet != null)
{
response.metadata.put(SearchEngineResponse.RESULTS_TOTAL_KEY,
newsResultSet.deephits);
if (newsResultSet.results != null)
{
final Set<String> unknownLanguages = Sets.newHashSet();
for (NewsResult result : newsResultSet.results)
{
final Document document = new Document(result.title, result.summary,
result.url);
document.setField(Document.CLICK_URL, result.clickURL);
if (StringUtils.isNotBlank(result.source))
{
document.setField(Document.SOURCES, Lists.newArrayList(result.source));
}
// BOSS news returns language name as a string, but there is no list
// of supported values in the documentation. It seems that the strings
// are parallel to LanguageCode enum names, so we use them here.
if (StringUtils.isNotBlank(result.language))
{
try
{
document.setLanguage(LanguageCode.valueOf(result.language));
}
catch (IllegalArgumentException ignored)
{
unknownLanguages.add(result.language);
}
}
response.results.add(document);
}
// Log unknown languages, if any
if (!unknownLanguages.isEmpty())
{
org.slf4j.LoggerFactory.getLogger(this.getClass().getName()).warn(
"Unknown language: " + unknownLanguages.toString());
}
}
}
else if (imagesResultSet != null)
{
response.metadata.put(SearchEngineResponse.RESULTS_TOTAL_KEY,
imagesResultSet.deephits);
if (imagesResultSet.results != null)
{
for (ImageResult result : imagesResultSet.results)
{
final Document document = new Document(result.title, result.summary, result.refererURL);
// We use the image's referer page as the target click for the title.
document.setField(Document.CLICK_URL, result.refererClickURL);
// Attach thumbnail URL.
document.setField(Document.THUMBNAIL_URL, result.thumbnailURL);
response.results.add(document);
}
}
}
// If language has not been set based on the response, set it based on the request
if (requestedLanguage != null) {
for (Document document : response.results)
{
if (document.getLanguage() == null)
{
document.setLanguage(requestedLanguage);
}
}
}
}
| public void populate(SearchEngineResponse response, LanguageCode requestedLanguage)
{
if (webResultSet != null)
{
response.metadata.put(SearchEngineResponse.RESULTS_TOTAL_KEY,
webResultSet.deephits);
if (webResultSet.results != null)
{
for (WebResult result : webResultSet.results)
{
final Document document = new Document(result.title, result.summary,
result.url);
document.setField(Document.CLICK_URL, result.clickURL);
try
{
document.setField(Document.SIZE, Long.parseLong(result.size));
}
catch (NumberFormatException e)
{
// Ignore if cannot parse.
}
response.results.add(document);
}
}
}
else if (newsResultSet != null)
{
response.metadata.put(SearchEngineResponse.RESULTS_TOTAL_KEY,
newsResultSet.deephits);
if (newsResultSet.results != null)
{
final Set<String> unknownLanguages = Sets.newHashSet();
for (NewsResult result : newsResultSet.results)
{
final Document document = new Document(result.title, result.summary,
result.url);
document.setField(Document.CLICK_URL, result.clickURL);
if (StringUtils.isNotBlank(result.source))
{
document.setField(Document.SOURCES, Lists.newArrayList(result.source));
}
// BOSS news returns language name as a string, but there is no list
// of supported values in the documentation. It seems that the strings
// are parallel to LanguageCode enum names, so we use them here.
if (StringUtils.isNotBlank(result.language))
{
try
{
document.setLanguage(LanguageCode.valueOf(result.language.toUpperCase()));
}
catch (IllegalArgumentException ignored)
{
unknownLanguages.add(result.language);
}
}
response.results.add(document);
}
// Log unknown languages, if any
if (!unknownLanguages.isEmpty())
{
org.slf4j.LoggerFactory.getLogger(this.getClass().getName()).warn(
"Unknown language: " + unknownLanguages.toString());
}
}
}
else if (imagesResultSet != null)
{
response.metadata.put(SearchEngineResponse.RESULTS_TOTAL_KEY,
imagesResultSet.deephits);
if (imagesResultSet.results != null)
{
for (ImageResult result : imagesResultSet.results)
{
final Document document = new Document(result.title, result.summary, result.refererURL);
// We use the image's referer page as the target click for the title.
document.setField(Document.CLICK_URL, result.refererClickURL);
// Attach thumbnail URL.
document.setField(Document.THUMBNAIL_URL, result.thumbnailURL);
response.results.add(document);
}
}
}
// If language has not been set based on the response, set it based on the request
if (requestedLanguage != null) {
for (Document document : response.results)
{
if (document.getLanguage() == null)
{
document.setLanguage(requestedLanguage);
}
}
}
}
|
diff --git a/panc/src/main/java/org/quattor/pan/utils/XmlUtils.java b/panc/src/main/java/org/quattor/pan/utils/XmlUtils.java
index 8d1d76a..02f04fa 100644
--- a/panc/src/main/java/org/quattor/pan/utils/XmlUtils.java
+++ b/panc/src/main/java/org/quattor/pan/utils/XmlUtils.java
@@ -1,64 +1,67 @@
package org.quattor.pan.utils;
import static org.quattor.pan.utils.MessageUtils.MSG_MISSING_SAX_TRANSFORMER;
import static org.quattor.pan.utils.MessageUtils.MSG_UNEXPECTED_EXCEPTION_WHILE_WRITING_OUTPUT;
import java.util.Properties;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.sax.SAXTransformerFactory;
import javax.xml.transform.sax.TransformerHandler;
import org.quattor.pan.exceptions.CompilerError;
public class XmlUtils {
private XmlUtils() {
}
public static TransformerHandler getSaxTransformerHandler() {
try {
// Generate the transformer factory. Need to guarantee that we get a
// SAXTransformerFactory.
TransformerFactory factory = TransformerFactory.newInstance();
if (!factory.getFeature(SAXTransformerFactory.FEATURE)) {
throw CompilerError.create(MSG_MISSING_SAX_TRANSFORMER);
}
// Only set the indentation if the returned TransformerFactory
// supports it.
if (factory.getFeature("indent-number")) {
- factory.setAttribute("indent-number", Integer.valueOf(4));
+ try {
+ factory.setAttribute("indent-number", Integer.valueOf(4));
+ } catch (Exception consumed) {
+ }
}
// Can safely cast the factory to a SAX-specific one. Get the
// handler to feed with SAX events.
SAXTransformerFactory saxfactory = (SAXTransformerFactory) factory;
TransformerHandler handler = saxfactory.newTransformerHandler();
// Set parameters of the embedded transformer.
Transformer transformer = handler.getTransformer();
Properties properties = new Properties();
properties.setProperty(OutputKeys.INDENT, "yes");
properties.setProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperties(properties);
return handler;
} catch (TransformerConfigurationException tce) {
Error error = CompilerError
.create(MSG_UNEXPECTED_EXCEPTION_WHILE_WRITING_OUTPUT);
error.initCause(tce);
throw error;
}
}
}
| true | true | public static TransformerHandler getSaxTransformerHandler() {
try {
// Generate the transformer factory. Need to guarantee that we get a
// SAXTransformerFactory.
TransformerFactory factory = TransformerFactory.newInstance();
if (!factory.getFeature(SAXTransformerFactory.FEATURE)) {
throw CompilerError.create(MSG_MISSING_SAX_TRANSFORMER);
}
// Only set the indentation if the returned TransformerFactory
// supports it.
if (factory.getFeature("indent-number")) {
factory.setAttribute("indent-number", Integer.valueOf(4));
}
// Can safely cast the factory to a SAX-specific one. Get the
// handler to feed with SAX events.
SAXTransformerFactory saxfactory = (SAXTransformerFactory) factory;
TransformerHandler handler = saxfactory.newTransformerHandler();
// Set parameters of the embedded transformer.
Transformer transformer = handler.getTransformer();
Properties properties = new Properties();
properties.setProperty(OutputKeys.INDENT, "yes");
properties.setProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperties(properties);
return handler;
} catch (TransformerConfigurationException tce) {
Error error = CompilerError
.create(MSG_UNEXPECTED_EXCEPTION_WHILE_WRITING_OUTPUT);
error.initCause(tce);
throw error;
}
}
| public static TransformerHandler getSaxTransformerHandler() {
try {
// Generate the transformer factory. Need to guarantee that we get a
// SAXTransformerFactory.
TransformerFactory factory = TransformerFactory.newInstance();
if (!factory.getFeature(SAXTransformerFactory.FEATURE)) {
throw CompilerError.create(MSG_MISSING_SAX_TRANSFORMER);
}
// Only set the indentation if the returned TransformerFactory
// supports it.
if (factory.getFeature("indent-number")) {
try {
factory.setAttribute("indent-number", Integer.valueOf(4));
} catch (Exception consumed) {
}
}
// Can safely cast the factory to a SAX-specific one. Get the
// handler to feed with SAX events.
SAXTransformerFactory saxfactory = (SAXTransformerFactory) factory;
TransformerHandler handler = saxfactory.newTransformerHandler();
// Set parameters of the embedded transformer.
Transformer transformer = handler.getTransformer();
Properties properties = new Properties();
properties.setProperty(OutputKeys.INDENT, "yes");
properties.setProperty(OutputKeys.METHOD, "xml");
transformer.setOutputProperties(properties);
return handler;
} catch (TransformerConfigurationException tce) {
Error error = CompilerError
.create(MSG_UNEXPECTED_EXCEPTION_WHILE_WRITING_OUTPUT);
error.initCause(tce);
throw error;
}
}
|
diff --git a/src/com/android/settings/deviceinfo/Status.java b/src/com/android/settings/deviceinfo/Status.java
index e443c1d29..f171c81d9 100644
--- a/src/com/android/settings/deviceinfo/Status.java
+++ b/src/com/android/settings/deviceinfo/Status.java
@@ -1,442 +1,437 @@
/*
* 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.settings.deviceinfo;
import android.bluetooth.BluetoothAdapter;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.res.Resources;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.BatteryManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.os.SystemProperties;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.telephony.PhoneNumberUtils;
import android.telephony.PhoneStateListener;
import android.telephony.ServiceState;
import android.telephony.TelephonyManager;
import android.text.TextUtils;
import com.android.internal.telephony.Phone;
import com.android.internal.telephony.PhoneFactory;
import com.android.internal.telephony.PhoneStateIntentReceiver;
import com.android.internal.telephony.TelephonyProperties;
import com.android.settings.R;
import com.android.settings.Utils;
import java.lang.ref.WeakReference;
/**
* Display the following information
* # Phone Number
* # Network
* # Roaming
* # Device Id (IMEI in GSM and MEID in CDMA)
* # Network type
* # Signal Strength
* # Battery Strength : TODO
* # Uptime
* # Awake Time
* # XMPP/buzz/tickle status : TODO
*
*/
public class Status extends PreferenceActivity {
private static final String KEY_SERVICE_STATE = "service_state";
private static final String KEY_OPERATOR_NAME = "operator_name";
private static final String KEY_ROAMING_STATE = "roaming_state";
private static final String KEY_NETWORK_TYPE = "network_type";
private static final String KEY_PHONE_NUMBER = "number";
private static final String KEY_IMEI_SV = "imei_sv";
private static final String KEY_IMEI = "imei";
private static final String KEY_PRL_VERSION = "prl_version";
private static final String KEY_MIN_NUMBER = "min_number";
private static final String KEY_MEID_NUMBER = "meid_number";
private static final String KEY_SIGNAL_STRENGTH = "signal_strength";
private static final String KEY_BATTERY_STATUS = "battery_status";
private static final String KEY_BATTERY_LEVEL = "battery_level";
private static final String KEY_WIFI_MAC_ADDRESS = "wifi_mac_address";
private static final String KEY_BT_ADDRESS = "bt_address";
private static final int EVENT_SIGNAL_STRENGTH_CHANGED = 200;
private static final int EVENT_SERVICE_STATE_CHANGED = 300;
private static final int EVENT_UPDATE_STATS = 500;
private TelephonyManager mTelephonyManager;
private Phone mPhone = null;
private PhoneStateIntentReceiver mPhoneStateReceiver;
private Resources mRes;
private Preference mSignalStrength;
private Preference mUptime;
private static String sUnknown;
private Preference mBatteryStatus;
private Preference mBatteryLevel;
private Handler mHandler;
private static class MyHandler extends Handler {
private WeakReference<Status> mStatus;
public MyHandler(Status activity) {
mStatus = new WeakReference<Status>(activity);
}
@Override
public void handleMessage(Message msg) {
Status status = mStatus.get();
if (status == null) {
return;
}
switch (msg.what) {
case EVENT_SIGNAL_STRENGTH_CHANGED:
status.updateSignalStrength();
break;
case EVENT_SERVICE_STATE_CHANGED:
ServiceState serviceState = status.mPhoneStateReceiver.getServiceState();
status.updateServiceState(serviceState);
break;
case EVENT_UPDATE_STATS:
status.updateTimes();
sendEmptyMessageDelayed(EVENT_UPDATE_STATS, 1000);
break;
}
}
}
private BroadcastReceiver mBatteryInfoReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (Intent.ACTION_BATTERY_CHANGED.equals(action)) {
int level = intent.getIntExtra("level", 0);
int scale = intent.getIntExtra("scale", 100);
mBatteryLevel.setSummary(String.valueOf(level * 100 / scale) + "%");
int plugType = intent.getIntExtra("plugged", 0);
int status = intent.getIntExtra("status", BatteryManager.BATTERY_STATUS_UNKNOWN);
String statusString;
if (status == BatteryManager.BATTERY_STATUS_CHARGING) {
statusString = getString(R.string.battery_info_status_charging);
if (plugType > 0) {
statusString = statusString + " " + getString(
(plugType == BatteryManager.BATTERY_PLUGGED_AC)
? R.string.battery_info_status_charging_ac
: R.string.battery_info_status_charging_usb);
}
} else if (status == BatteryManager.BATTERY_STATUS_DISCHARGING) {
statusString = getString(R.string.battery_info_status_discharging);
} else if (status == BatteryManager.BATTERY_STATUS_NOT_CHARGING) {
statusString = getString(R.string.battery_info_status_not_charging);
} else if (status == BatteryManager.BATTERY_STATUS_FULL) {
statusString = getString(R.string.battery_info_status_full);
} else {
statusString = getString(R.string.battery_info_status_unknown);
}
mBatteryStatus.setSummary(statusString);
}
}
};
private PhoneStateListener mPhoneStateListener = new PhoneStateListener() {
@Override
public void onDataConnectionStateChanged(int state) {
updateDataState();
updateNetworkType();
}
};
@Override
protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
Preference removablePref;
mHandler = new MyHandler(this);
mTelephonyManager = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
addPreferencesFromResource(R.xml.device_info_status);
mBatteryLevel = findPreference(KEY_BATTERY_LEVEL);
mBatteryStatus = findPreference(KEY_BATTERY_STATUS);
mRes = getResources();
if (sUnknown == null) {
sUnknown = mRes.getString(R.string.device_info_default);
}
mPhone = PhoneFactory.getDefaultPhone();
// Note - missing in zaku build, be careful later...
mSignalStrength = findPreference(KEY_SIGNAL_STRENGTH);
mUptime = findPreference("up_time");
//NOTE "imei" is the "Device ID" since it represents the IMEI in GSM and the MEID in CDMA
if (mPhone.getPhoneName().equals("CDMA")) {
setSummaryText(KEY_MEID_NUMBER, mPhone.getMeid());
setSummaryText(KEY_MIN_NUMBER, mPhone.getCdmaMin());
setSummaryText(KEY_PRL_VERSION, mPhone.getCdmaPrlVersion());
// device is not GSM/UMTS, do not display GSM/UMTS features
// check Null in case no specified preference in overlay xml
removePreferenceFromScreen(KEY_IMEI);
removePreferenceFromScreen(KEY_IMEI_SV);
} else {
setSummaryText(KEY_IMEI, mPhone.getDeviceId());
setSummaryText(KEY_IMEI_SV,
((TelephonyManager) getSystemService(TELEPHONY_SERVICE))
.getDeviceSoftwareVersion());
// device is not CDMA, do not display CDMA features
// check Null in case no specified preference in overlay xml
removePreferenceFromScreen(KEY_PRL_VERSION);
removePreferenceFromScreen(KEY_MEID_NUMBER);
removePreferenceFromScreen(KEY_MIN_NUMBER);
}
- // Remove the phone number preference if the device is not voice capable.
- if (!Utils.isVoiceCapable(this)) {
- removePreferenceFromScreen(KEY_PHONE_NUMBER);
- } else {
- String rawNumber = mPhone.getLine1Number(); // may be null or empty
- String formattedNumber = null;
- if (!TextUtils.isEmpty(rawNumber)) {
- formattedNumber = PhoneNumberUtils.formatNumber(rawNumber);
- }
- // If formattedNumber is null or empty, it'll display as "Unknown".
- setSummaryText(KEY_PHONE_NUMBER, formattedNumber);
+ String rawNumber = mPhone.getLine1Number(); // may be null or empty
+ String formattedNumber = null;
+ if (!TextUtils.isEmpty(rawNumber)) {
+ formattedNumber = PhoneNumberUtils.formatNumber(rawNumber);
}
+ // If formattedNumber is null or empty, it'll display as "Unknown".
+ setSummaryText(KEY_PHONE_NUMBER, formattedNumber);
mPhoneStateReceiver = new PhoneStateIntentReceiver(this, mHandler);
mPhoneStateReceiver.notifySignalStrength(EVENT_SIGNAL_STRENGTH_CHANGED);
mPhoneStateReceiver.notifyServiceState(EVENT_SERVICE_STATE_CHANGED);
setWifiStatus();
setBtStatus();
}
@Override
protected void onResume() {
super.onResume();
mPhoneStateReceiver.registerIntent();
registerReceiver(mBatteryInfoReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
updateSignalStrength();
updateServiceState(mPhone.getServiceState());
updateDataState();
mTelephonyManager.listen(mPhoneStateListener,
PhoneStateListener.LISTEN_DATA_CONNECTION_STATE);
mHandler.sendEmptyMessage(EVENT_UPDATE_STATS);
}
@Override
public void onPause() {
super.onPause();
mPhoneStateReceiver.unregisterIntent();
mTelephonyManager.listen(mPhoneStateListener, PhoneStateListener.LISTEN_NONE);
unregisterReceiver(mBatteryInfoReceiver);
mHandler.removeMessages(EVENT_UPDATE_STATS);
}
/**
* Removes the specified preference, if it exists.
* @param key the key for the Preference item
*/
private void removePreferenceFromScreen(String key) {
Preference pref = findPreference(key);
if (pref != null) {
getPreferenceScreen().removePreference(pref);
}
}
/**
* @param preference The key for the Preference item
* @param property The system property to fetch
* @param alt The default value, if the property doesn't exist
*/
private void setSummary(String preference, String property, String alt) {
try {
findPreference(preference).setSummary(
SystemProperties.get(property, alt));
} catch (RuntimeException e) {
}
}
private void setSummaryText(String preference, String text) {
if (TextUtils.isEmpty(text)) {
text = sUnknown;
}
// some preferences may be missing
if (findPreference(preference) != null) {
findPreference(preference).setSummary(text);
}
}
private void updateNetworkType() {
// Whether EDGE, UMTS, etc...
setSummary(KEY_NETWORK_TYPE, TelephonyProperties.PROPERTY_DATA_NETWORK_TYPE, sUnknown);
}
private void updateDataState() {
int state = mTelephonyManager.getDataState();
String display = mRes.getString(R.string.radioInfo_unknown);
switch (state) {
case TelephonyManager.DATA_CONNECTED:
display = mRes.getString(R.string.radioInfo_data_connected);
break;
case TelephonyManager.DATA_SUSPENDED:
display = mRes.getString(R.string.radioInfo_data_suspended);
break;
case TelephonyManager.DATA_CONNECTING:
display = mRes.getString(R.string.radioInfo_data_connecting);
break;
case TelephonyManager.DATA_DISCONNECTED:
display = mRes.getString(R.string.radioInfo_data_disconnected);
break;
}
setSummaryText("data_state", display);
}
private void updateServiceState(ServiceState serviceState) {
int state = serviceState.getState();
String display = mRes.getString(R.string.radioInfo_unknown);
switch (state) {
case ServiceState.STATE_IN_SERVICE:
display = mRes.getString(R.string.radioInfo_service_in);
break;
case ServiceState.STATE_OUT_OF_SERVICE:
case ServiceState.STATE_EMERGENCY_ONLY:
display = mRes.getString(R.string.radioInfo_service_out);
break;
case ServiceState.STATE_POWER_OFF:
display = mRes.getString(R.string.radioInfo_service_off);
break;
}
setSummaryText(KEY_SERVICE_STATE, display);
if (serviceState.getRoaming()) {
setSummaryText(KEY_ROAMING_STATE, mRes.getString(R.string.radioInfo_roaming_in));
} else {
setSummaryText(KEY_ROAMING_STATE, mRes.getString(R.string.radioInfo_roaming_not));
}
setSummaryText(KEY_OPERATOR_NAME, serviceState.getOperatorAlphaLong());
}
void updateSignalStrength() {
// TODO PhoneStateIntentReceiver is deprecated and PhoneStateListener
// should probably used instead.
// not loaded in some versions of the code (e.g., zaku)
if (mSignalStrength != null) {
int state =
mPhoneStateReceiver.getServiceState().getState();
Resources r = getResources();
if ((ServiceState.STATE_OUT_OF_SERVICE == state) ||
(ServiceState.STATE_POWER_OFF == state)) {
mSignalStrength.setSummary("0");
}
int signalDbm = mPhoneStateReceiver.getSignalStrengthDbm();
if (-1 == signalDbm) signalDbm = 0;
int signalAsu = mPhoneStateReceiver.getSignalStrength();
if (-1 == signalAsu) signalAsu = 0;
mSignalStrength.setSummary(String.valueOf(signalDbm) + " "
+ r.getString(R.string.radioInfo_display_dbm) + " "
+ String.valueOf(signalAsu) + " "
+ r.getString(R.string.radioInfo_display_asu));
}
}
private void setWifiStatus() {
WifiManager wifiManager = (WifiManager) getSystemService(WIFI_SERVICE);
WifiInfo wifiInfo = wifiManager.getConnectionInfo();
Preference wifiMacAddressPref = findPreference(KEY_WIFI_MAC_ADDRESS);
String macAddress = wifiInfo == null ? null : wifiInfo.getMacAddress();
wifiMacAddressPref.setSummary(!TextUtils.isEmpty(macAddress) ? macAddress
: getString(R.string.status_unavailable));
}
private void setBtStatus() {
BluetoothAdapter bluetooth = BluetoothAdapter.getDefaultAdapter();
Preference btAddressPref = findPreference(KEY_BT_ADDRESS);
if (bluetooth == null) {
// device not BT capable
getPreferenceScreen().removePreference(btAddressPref);
} else {
String address = bluetooth.isEnabled() ? bluetooth.getAddress() : null;
btAddressPref.setSummary(!TextUtils.isEmpty(address) ? address
: getString(R.string.status_unavailable));
}
}
void updateTimes() {
long at = SystemClock.uptimeMillis() / 1000;
long ut = SystemClock.elapsedRealtime() / 1000;
if (ut == 0) {
ut = 1;
}
mUptime.setSummary(convert(ut));
}
private String pad(int n) {
if (n >= 10) {
return String.valueOf(n);
} else {
return "0" + String.valueOf(n);
}
}
private String convert(long t) {
int s = (int)(t % 60);
int m = (int)((t / 60) % 60);
int h = (int)((t / 3600));
return h + ":" + pad(m) + ":" + pad(s);
}
}
| false | true | protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
Preference removablePref;
mHandler = new MyHandler(this);
mTelephonyManager = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
addPreferencesFromResource(R.xml.device_info_status);
mBatteryLevel = findPreference(KEY_BATTERY_LEVEL);
mBatteryStatus = findPreference(KEY_BATTERY_STATUS);
mRes = getResources();
if (sUnknown == null) {
sUnknown = mRes.getString(R.string.device_info_default);
}
mPhone = PhoneFactory.getDefaultPhone();
// Note - missing in zaku build, be careful later...
mSignalStrength = findPreference(KEY_SIGNAL_STRENGTH);
mUptime = findPreference("up_time");
//NOTE "imei" is the "Device ID" since it represents the IMEI in GSM and the MEID in CDMA
if (mPhone.getPhoneName().equals("CDMA")) {
setSummaryText(KEY_MEID_NUMBER, mPhone.getMeid());
setSummaryText(KEY_MIN_NUMBER, mPhone.getCdmaMin());
setSummaryText(KEY_PRL_VERSION, mPhone.getCdmaPrlVersion());
// device is not GSM/UMTS, do not display GSM/UMTS features
// check Null in case no specified preference in overlay xml
removePreferenceFromScreen(KEY_IMEI);
removePreferenceFromScreen(KEY_IMEI_SV);
} else {
setSummaryText(KEY_IMEI, mPhone.getDeviceId());
setSummaryText(KEY_IMEI_SV,
((TelephonyManager) getSystemService(TELEPHONY_SERVICE))
.getDeviceSoftwareVersion());
// device is not CDMA, do not display CDMA features
// check Null in case no specified preference in overlay xml
removePreferenceFromScreen(KEY_PRL_VERSION);
removePreferenceFromScreen(KEY_MEID_NUMBER);
removePreferenceFromScreen(KEY_MIN_NUMBER);
}
// Remove the phone number preference if the device is not voice capable.
if (!Utils.isVoiceCapable(this)) {
removePreferenceFromScreen(KEY_PHONE_NUMBER);
} else {
String rawNumber = mPhone.getLine1Number(); // may be null or empty
String formattedNumber = null;
if (!TextUtils.isEmpty(rawNumber)) {
formattedNumber = PhoneNumberUtils.formatNumber(rawNumber);
}
// If formattedNumber is null or empty, it'll display as "Unknown".
setSummaryText(KEY_PHONE_NUMBER, formattedNumber);
}
mPhoneStateReceiver = new PhoneStateIntentReceiver(this, mHandler);
mPhoneStateReceiver.notifySignalStrength(EVENT_SIGNAL_STRENGTH_CHANGED);
mPhoneStateReceiver.notifyServiceState(EVENT_SERVICE_STATE_CHANGED);
setWifiStatus();
setBtStatus();
}
| protected void onCreate(Bundle icicle) {
super.onCreate(icicle);
Preference removablePref;
mHandler = new MyHandler(this);
mTelephonyManager = (TelephonyManager)getSystemService(TELEPHONY_SERVICE);
addPreferencesFromResource(R.xml.device_info_status);
mBatteryLevel = findPreference(KEY_BATTERY_LEVEL);
mBatteryStatus = findPreference(KEY_BATTERY_STATUS);
mRes = getResources();
if (sUnknown == null) {
sUnknown = mRes.getString(R.string.device_info_default);
}
mPhone = PhoneFactory.getDefaultPhone();
// Note - missing in zaku build, be careful later...
mSignalStrength = findPreference(KEY_SIGNAL_STRENGTH);
mUptime = findPreference("up_time");
//NOTE "imei" is the "Device ID" since it represents the IMEI in GSM and the MEID in CDMA
if (mPhone.getPhoneName().equals("CDMA")) {
setSummaryText(KEY_MEID_NUMBER, mPhone.getMeid());
setSummaryText(KEY_MIN_NUMBER, mPhone.getCdmaMin());
setSummaryText(KEY_PRL_VERSION, mPhone.getCdmaPrlVersion());
// device is not GSM/UMTS, do not display GSM/UMTS features
// check Null in case no specified preference in overlay xml
removePreferenceFromScreen(KEY_IMEI);
removePreferenceFromScreen(KEY_IMEI_SV);
} else {
setSummaryText(KEY_IMEI, mPhone.getDeviceId());
setSummaryText(KEY_IMEI_SV,
((TelephonyManager) getSystemService(TELEPHONY_SERVICE))
.getDeviceSoftwareVersion());
// device is not CDMA, do not display CDMA features
// check Null in case no specified preference in overlay xml
removePreferenceFromScreen(KEY_PRL_VERSION);
removePreferenceFromScreen(KEY_MEID_NUMBER);
removePreferenceFromScreen(KEY_MIN_NUMBER);
}
String rawNumber = mPhone.getLine1Number(); // may be null or empty
String formattedNumber = null;
if (!TextUtils.isEmpty(rawNumber)) {
formattedNumber = PhoneNumberUtils.formatNumber(rawNumber);
}
// If formattedNumber is null or empty, it'll display as "Unknown".
setSummaryText(KEY_PHONE_NUMBER, formattedNumber);
mPhoneStateReceiver = new PhoneStateIntentReceiver(this, mHandler);
mPhoneStateReceiver.notifySignalStrength(EVENT_SIGNAL_STRENGTH_CHANGED);
mPhoneStateReceiver.notifyServiceState(EVENT_SERVICE_STATE_CHANGED);
setWifiStatus();
setBtStatus();
}
|
diff --git a/drools-core/src/main/java/org/drools/io/impl/ResourceChangeScannerImpl.java b/drools-core/src/main/java/org/drools/io/impl/ResourceChangeScannerImpl.java
index d738de399b..3fcc46e0fa 100644
--- a/drools-core/src/main/java/org/drools/io/impl/ResourceChangeScannerImpl.java
+++ b/drools-core/src/main/java/org/drools/io/impl/ResourceChangeScannerImpl.java
@@ -1,338 +1,338 @@
/*
* Copyright 2010 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.drools.io.impl;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.Set;
import java.util.concurrent.Future;
import org.drools.io.internal.InternalResource;
import org.kie.ChangeSet;
import org.kie.SystemEventListener;
import org.kie.concurrent.ExecutorProviderFactory;
import org.kie.io.Resource;
import org.kie.io.ResourceChangeNotifier;
import org.kie.io.ResourceChangeScanner;
import org.kie.io.ResourceChangeScannerConfiguration;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class ResourceChangeScannerImpl
implements
ResourceChangeScanner {
private final Logger logger = LoggerFactory.getLogger( ResourceChangeScanner.class );
private final Map<Resource, Set<ResourceChangeNotifier>> resources;
private final Set<Resource> directories;
private int interval;
private Future<Boolean> scannerSchedulerExecutor;
private ProcessChangeSet scannerScheduler;
public ResourceChangeScannerImpl() {
this.resources = new HashMap<Resource, Set<ResourceChangeNotifier>>();
this.directories = new HashSet<Resource>();
this.setInterval( 60 );
logger.info( "ResourceChangeScanner created with default interval=60" );
}
public void configure(ResourceChangeScannerConfiguration configuration) {
this.setInterval( ((ResourceChangeScannerConfigurationImpl) configuration).getInterval() );
logger.info( "ResourceChangeScanner reconfigured with interval=" + getInterval() );
// restart it if it's already running.
if ( this.scannerScheduler != null && this.scannerScheduler.isRunning() ) {
stop();
start();
}
}
public ResourceChangeScannerConfiguration newResourceChangeScannerConfiguration() {
return new ResourceChangeScannerConfigurationImpl();
}
public ResourceChangeScannerConfiguration newResourceChangeScannerConfiguration(Properties properties) {
return new ResourceChangeScannerConfigurationImpl( properties );
}
public void subscribeNotifier(ResourceChangeNotifier notifier,
Resource resource) {
synchronized ( this.resources ) {
if ( ((InternalResource) resource).isDirectory() ) {
this.directories.add( resource );
}
Set<ResourceChangeNotifier> notifiers = this.resources.get( resource );
if ( notifiers == null ) {
notifiers = new HashSet<ResourceChangeNotifier>();
this.resources.put( resource,
notifiers );
}
logger.debug( "ResourceChangeScanner subcribing notifier=" + notifier + " to resource=" + resource );
notifiers.add( notifier );
}
}
public void unsubscribeNotifier(ResourceChangeNotifier notifier,
Resource resource) {
synchronized ( this.resources ) {
Set<ResourceChangeNotifier> notifiers = this.resources.get( resource );
if ( notifiers == null ) {
return;
}
logger.debug( "ResourceChangeScanner unsubcribing notifier=" + notifier + " to resource=" + resource );
notifiers.remove( notifier );
if ( notifiers.isEmpty() ) {
logger.debug( "ResourceChangeScanner resource=" + resource + " now has no subscribers" );
this.resources.remove( resource );
this.directories.remove( resource ); // don't bother with
// isDirectory check, as
// doing a remove is
// harmless if it doesn't
// exist
}
}
}
public Map<Resource, Set<ResourceChangeNotifier>> getResources() {
return resources;
}
public void scan() {
logger.debug( "ResourceChangeScanner attempt to scan " + this.resources.size() + " resources" );
synchronized ( this.resources ) {
Map<ResourceChangeNotifier, ChangeSet> notifications = new HashMap<ResourceChangeNotifier, ChangeSet>();
List<Resource> removed = new ArrayList<Resource>();
// detect modified and added
for ( Resource resource : this.directories ) {
logger.debug( "ResourceChangeScanner scanning directory=" + resource );
for ( Resource child : ((InternalResource) resource).listResources() ) {
if ( ((InternalResource) child).isDirectory() ) {
continue; // ignore sub directories
}
if ( !this.resources.containsKey( child ) ) {
logger.debug( "ResourceChangeScanner new resource=" + child );
// child is new
((InternalResource) child).setResourceType( ((InternalResource) resource).getResourceType() );
Set<ResourceChangeNotifier> notifiers = this.resources.get( resource ); // get notifiers for this
// directory
for ( ResourceChangeNotifier notifier : notifiers ) {
ChangeSetImpl changeSet = (ChangeSetImpl) notifications.get( notifier );
if ( changeSet == null ) {
// lazy initialise changeSet
changeSet = new ChangeSetImpl();
notifications.put( notifier,
changeSet );
}
if ( changeSet.getResourcesAdded().isEmpty() ) {
changeSet.setResourcesAdded( new ArrayList<Resource>() );
}
changeSet.getResourcesAdded().add( child );
notifier.subscribeChildResource( resource,
child );
}
}
}
}
for ( Entry<Resource, Set<ResourceChangeNotifier>> entry : this.resources.entrySet() ) {
Resource resource = entry.getKey();
Set<ResourceChangeNotifier> notifiers = entry.getValue();
if ( !((InternalResource) resource).isDirectory() ) {
// detect if Resource has been removed
long lastModified = ((InternalResource) resource).getLastModified();
long lastRead = ((InternalResource) resource).getLastRead();
if ( lastModified == 0 ) {
logger.debug( "ResourceChangeScanner removed resource=" + resource );
removed.add( resource );
// resource is no longer present
// iterate notifiers for this resource and add to each
// removed
for ( ResourceChangeNotifier notifier : notifiers ) {
ChangeSetImpl changeSet = (ChangeSetImpl) notifications.get( notifier );
if ( changeSet == null ) {
// lazy initialise changeSet
changeSet = new ChangeSetImpl();
notifications.put( notifier,
changeSet );
}
if ( changeSet.getResourcesRemoved().isEmpty() ) {
changeSet.setResourcesRemoved( new ArrayList<Resource>() );
}
changeSet.getResourcesRemoved().add( resource );
}
- } else if ( lastRead < lastModified && lastRead >= 0 ) {
+ } else if ( lastRead < lastModified ) {
logger.debug( "ResourceChangeScanner modified resource=" + resource + " : " + lastRead + " : " + lastModified );
// it's modified
// iterate notifiers for this resource and add to each
// modified
for ( ResourceChangeNotifier notifier : notifiers ) {
ChangeSetImpl changeSet = (ChangeSetImpl) notifications.get( notifier );
if ( changeSet == null ) {
// lazy initialise changeSet
changeSet = new ChangeSetImpl();
notifications.put( notifier,
changeSet );
}
if ( changeSet.getResourcesModified().isEmpty() ) {
changeSet.setResourcesModified( new ArrayList<Resource>() );
}
changeSet.getResourcesModified().add( resource );
}
}
}
}
// now iterate and removed the removed resources, we do this so as
// not to mutate the foreach loop while iterating
for ( Resource resource : removed ) {
this.resources.remove( resource );
}
for ( Entry<ResourceChangeNotifier, ChangeSet> entry : notifications.entrySet() ) {
ResourceChangeNotifier notifier = entry.getKey();
ChangeSet changeSet = entry.getValue();
notifier.publishChangeSet( changeSet );
}
}
}
public void setInterval(int interval) {
if ( interval <= 0 ) {
throw new IllegalArgumentException( "Invalid interval time: " + interval + ". It should be a positive number bigger than 0" );
}
this.interval = interval;
logger.info( "ResourceChangeScanner reconfigured with interval=" + getInterval() );
if ( this.scannerScheduler != null && this.scannerScheduler.isRunning() ) {
stop();
start();
}
}
public int getInterval() {
return this.interval;
}
public void start() {
this.scannerScheduler = new ProcessChangeSet( this.resources,
this,
this.interval );
this.scannerSchedulerExecutor =
ExecutorProviderFactory.getExecutorProvider().<Boolean>getCompletionService()
.submit(this.scannerScheduler, true);
}
public void stop() {
if ( this.scannerScheduler != null && this.scannerScheduler.isRunning() ) {
this.scannerScheduler.stop();
this.scannerSchedulerExecutor.cancel(true);
this.scannerScheduler = null;
}
}
public void reset() {
this.resources.clear();
this.directories.clear();
}
public static class ProcessChangeSet
implements
Runnable {
private final Logger logger = LoggerFactory.getLogger( ProcessChangeSet.class );
private volatile boolean scan;
private final ResourceChangeScannerImpl scanner;
private final long interval;
private final Map<Resource, Set<ResourceChangeNotifier>> resources;
ProcessChangeSet(Map<Resource, Set<ResourceChangeNotifier>> resources,
ResourceChangeScannerImpl scanner,
int interval) {
this.resources = resources;
this.scanner = scanner;
this.interval = interval;
this.scan = true;
}
public int getInterval() {
return (int) this.interval;
}
public void stop() {
this.scan = false;
}
public boolean isRunning() {
return this.scan;
}
public void run() {
synchronized ( this ) {
if ( this.scan ) {
this.logger.info( "ResourceChangeNotification scanner has started" );
}
while ( this.scan ) {
try {
// logger.trace( "BEFORE : sync this.resources" );
synchronized ( this.resources ) {
// logger.trace( "DURING : sync this.resources" );
// lock the resources, as we don't want this modified
// while processing
this.scanner.scan();
}
// logger.trace( "AFTER : SCAN" );
} catch (RuntimeException e) {
this.logger.error( e.getMessage(), e );
} catch (Error e) {
this.logger.error( e.getMessage(), e );
}
try {
this.logger.debug( "ResourceChangeScanner thread is waiting for " + this.interval + " seconds." );
wait( this.interval * 1000 );
} catch ( InterruptedException e ) {
if ( this.scan ) {
this.logger.error( e.getMessage(), new RuntimeException( "ResourceChangeNotification ChangeSet scanning thread was interrupted, but shutdown was not requested",
e ) );
}
}
}
this.logger.info( "ResourceChangeNotification scanner has stopped" );
}
}
}
public void setSystemEventListener(SystemEventListener listener) {
// TODO Auto-generated method stub
}
}
| true | true | public void scan() {
logger.debug( "ResourceChangeScanner attempt to scan " + this.resources.size() + " resources" );
synchronized ( this.resources ) {
Map<ResourceChangeNotifier, ChangeSet> notifications = new HashMap<ResourceChangeNotifier, ChangeSet>();
List<Resource> removed = new ArrayList<Resource>();
// detect modified and added
for ( Resource resource : this.directories ) {
logger.debug( "ResourceChangeScanner scanning directory=" + resource );
for ( Resource child : ((InternalResource) resource).listResources() ) {
if ( ((InternalResource) child).isDirectory() ) {
continue; // ignore sub directories
}
if ( !this.resources.containsKey( child ) ) {
logger.debug( "ResourceChangeScanner new resource=" + child );
// child is new
((InternalResource) child).setResourceType( ((InternalResource) resource).getResourceType() );
Set<ResourceChangeNotifier> notifiers = this.resources.get( resource ); // get notifiers for this
// directory
for ( ResourceChangeNotifier notifier : notifiers ) {
ChangeSetImpl changeSet = (ChangeSetImpl) notifications.get( notifier );
if ( changeSet == null ) {
// lazy initialise changeSet
changeSet = new ChangeSetImpl();
notifications.put( notifier,
changeSet );
}
if ( changeSet.getResourcesAdded().isEmpty() ) {
changeSet.setResourcesAdded( new ArrayList<Resource>() );
}
changeSet.getResourcesAdded().add( child );
notifier.subscribeChildResource( resource,
child );
}
}
}
}
for ( Entry<Resource, Set<ResourceChangeNotifier>> entry : this.resources.entrySet() ) {
Resource resource = entry.getKey();
Set<ResourceChangeNotifier> notifiers = entry.getValue();
if ( !((InternalResource) resource).isDirectory() ) {
// detect if Resource has been removed
long lastModified = ((InternalResource) resource).getLastModified();
long lastRead = ((InternalResource) resource).getLastRead();
if ( lastModified == 0 ) {
logger.debug( "ResourceChangeScanner removed resource=" + resource );
removed.add( resource );
// resource is no longer present
// iterate notifiers for this resource and add to each
// removed
for ( ResourceChangeNotifier notifier : notifiers ) {
ChangeSetImpl changeSet = (ChangeSetImpl) notifications.get( notifier );
if ( changeSet == null ) {
// lazy initialise changeSet
changeSet = new ChangeSetImpl();
notifications.put( notifier,
changeSet );
}
if ( changeSet.getResourcesRemoved().isEmpty() ) {
changeSet.setResourcesRemoved( new ArrayList<Resource>() );
}
changeSet.getResourcesRemoved().add( resource );
}
} else if ( lastRead < lastModified && lastRead >= 0 ) {
logger.debug( "ResourceChangeScanner modified resource=" + resource + " : " + lastRead + " : " + lastModified );
// it's modified
// iterate notifiers for this resource and add to each
// modified
for ( ResourceChangeNotifier notifier : notifiers ) {
ChangeSetImpl changeSet = (ChangeSetImpl) notifications.get( notifier );
if ( changeSet == null ) {
// lazy initialise changeSet
changeSet = new ChangeSetImpl();
notifications.put( notifier,
changeSet );
}
if ( changeSet.getResourcesModified().isEmpty() ) {
changeSet.setResourcesModified( new ArrayList<Resource>() );
}
changeSet.getResourcesModified().add( resource );
}
}
}
}
// now iterate and removed the removed resources, we do this so as
// not to mutate the foreach loop while iterating
for ( Resource resource : removed ) {
this.resources.remove( resource );
}
for ( Entry<ResourceChangeNotifier, ChangeSet> entry : notifications.entrySet() ) {
ResourceChangeNotifier notifier = entry.getKey();
ChangeSet changeSet = entry.getValue();
notifier.publishChangeSet( changeSet );
}
}
}
| public void scan() {
logger.debug( "ResourceChangeScanner attempt to scan " + this.resources.size() + " resources" );
synchronized ( this.resources ) {
Map<ResourceChangeNotifier, ChangeSet> notifications = new HashMap<ResourceChangeNotifier, ChangeSet>();
List<Resource> removed = new ArrayList<Resource>();
// detect modified and added
for ( Resource resource : this.directories ) {
logger.debug( "ResourceChangeScanner scanning directory=" + resource );
for ( Resource child : ((InternalResource) resource).listResources() ) {
if ( ((InternalResource) child).isDirectory() ) {
continue; // ignore sub directories
}
if ( !this.resources.containsKey( child ) ) {
logger.debug( "ResourceChangeScanner new resource=" + child );
// child is new
((InternalResource) child).setResourceType( ((InternalResource) resource).getResourceType() );
Set<ResourceChangeNotifier> notifiers = this.resources.get( resource ); // get notifiers for this
// directory
for ( ResourceChangeNotifier notifier : notifiers ) {
ChangeSetImpl changeSet = (ChangeSetImpl) notifications.get( notifier );
if ( changeSet == null ) {
// lazy initialise changeSet
changeSet = new ChangeSetImpl();
notifications.put( notifier,
changeSet );
}
if ( changeSet.getResourcesAdded().isEmpty() ) {
changeSet.setResourcesAdded( new ArrayList<Resource>() );
}
changeSet.getResourcesAdded().add( child );
notifier.subscribeChildResource( resource,
child );
}
}
}
}
for ( Entry<Resource, Set<ResourceChangeNotifier>> entry : this.resources.entrySet() ) {
Resource resource = entry.getKey();
Set<ResourceChangeNotifier> notifiers = entry.getValue();
if ( !((InternalResource) resource).isDirectory() ) {
// detect if Resource has been removed
long lastModified = ((InternalResource) resource).getLastModified();
long lastRead = ((InternalResource) resource).getLastRead();
if ( lastModified == 0 ) {
logger.debug( "ResourceChangeScanner removed resource=" + resource );
removed.add( resource );
// resource is no longer present
// iterate notifiers for this resource and add to each
// removed
for ( ResourceChangeNotifier notifier : notifiers ) {
ChangeSetImpl changeSet = (ChangeSetImpl) notifications.get( notifier );
if ( changeSet == null ) {
// lazy initialise changeSet
changeSet = new ChangeSetImpl();
notifications.put( notifier,
changeSet );
}
if ( changeSet.getResourcesRemoved().isEmpty() ) {
changeSet.setResourcesRemoved( new ArrayList<Resource>() );
}
changeSet.getResourcesRemoved().add( resource );
}
} else if ( lastRead < lastModified ) {
logger.debug( "ResourceChangeScanner modified resource=" + resource + " : " + lastRead + " : " + lastModified );
// it's modified
// iterate notifiers for this resource and add to each
// modified
for ( ResourceChangeNotifier notifier : notifiers ) {
ChangeSetImpl changeSet = (ChangeSetImpl) notifications.get( notifier );
if ( changeSet == null ) {
// lazy initialise changeSet
changeSet = new ChangeSetImpl();
notifications.put( notifier,
changeSet );
}
if ( changeSet.getResourcesModified().isEmpty() ) {
changeSet.setResourcesModified( new ArrayList<Resource>() );
}
changeSet.getResourcesModified().add( resource );
}
}
}
}
// now iterate and removed the removed resources, we do this so as
// not to mutate the foreach loop while iterating
for ( Resource resource : removed ) {
this.resources.remove( resource );
}
for ( Entry<ResourceChangeNotifier, ChangeSet> entry : notifications.entrySet() ) {
ResourceChangeNotifier notifier = entry.getKey();
ChangeSet changeSet = entry.getValue();
notifier.publishChangeSet( changeSet );
}
}
}
|
diff --git a/Client/Core/src/main/java/me/footlights/core/data/File.java b/Client/Core/src/main/java/me/footlights/core/data/File.java
index 281cf6af..bdc28cd4 100644
--- a/Client/Core/src/main/java/me/footlights/core/data/File.java
+++ b/Client/Core/src/main/java/me/footlights/core/data/File.java
@@ -1,268 +1,273 @@
/*
* Copyright 2011 Jonathan Anderson
*
* 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 me.footlights.core.data;
import java.io.IOException;
import java.io.InputStream;
import java.nio.BufferUnderflowException;
import java.nio.ByteBuffer;
import java.security.GeneralSecurityException;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
/**
* A logical file.
*
* Files are immutable; to modify a file, you must create and freeze a {@link MutableFile}.
*/
public class File implements me.footlights.plugin.File
{
public static File from(EncryptedBlock header, Collection<EncryptedBlock> ciphertext)
{
List<Block> plaintext = Lists.newArrayListWithCapacity(ciphertext.size());
for (EncryptedBlock e : ciphertext) plaintext.add(e.plaintext());
return new File(header, plaintext, ciphertext);
}
public static MutableFile newBuilder() { return new MutableFile(); }
public static final class MutableFile
{
public MutableFile setContent(Collection<ByteBuffer> content)
{
this.content = ImmutableList.copyOf(content);
return this;
}
MutableFile setBlocks(Collection<Block> content)
{
List<ByteBuffer> bytes = Lists.newLinkedList();
for (Block b : content) bytes.add(b.content());
this.content = ImmutableList.copyOf(bytes);
return this;
}
MutableFile setDesiredBlockSize(int size)
{
this.desiredBlockSize = size;
return this;
}
/**
* Produce a proper {@link File} by fixing the current contents of this
* {@link MutableFile}.
*/
public File freeze() throws FormatException, GeneralSecurityException
{
// First, break the content into chunks of the appropriate size.
Collection<ByteBuffer> chunked =
rechunk(content, desiredBlockSize - Block.OVERHEAD_BYTES);
// Next, create {@link EncryptedBlock} objects.
List<EncryptedBlock> ciphertext = Lists.newLinkedList();
for (ByteBuffer b : chunked)
ciphertext.add(
Block.newBuilder()
.setContent(b)
.setDesiredSize(desiredBlockSize)
.build()
.encrypt());
// Finally, create the header. TODO: just embed links in all the blocks.
Block.Builder header = Block.newBuilder();
for (EncryptedBlock b : ciphertext) header.addLink(b.link());
return File.from(header.build().encrypt(), ciphertext);
}
private MutableFile() {}
private Iterable<ByteBuffer> content = Lists.newArrayList();
private int desiredBlockSize = 4096;
}
/**
* The content of the file, transformed into an {@link InputStream}.
*/
public InputStream getInputStream()
{
final ByteBuffer[] buffers = new ByteBuffer[plaintext.size()];
for (int i = 0; i < buffers.length; i++)
buffers[i] = plaintext.get(i).content();
return new InputStream()
{
@Override public int read(byte[] buffer, int offset, int len)
{
if (len == 0) return 0;
if (blockIndex >= plaintext.size()) return -1;
int pos = offset;
- while (pos < len)
+ while (pos < (offset + len))
{
ByteBuffer next = buffers[blockIndex];
- if (next.remaining() > 0)
+ if (next.remaining() > len)
+ {
+ next.get(buffer, pos, len);
+ pos += len;
+ }
+ else if (next.remaining() > 0)
{
int bytes = next.remaining();
next.get(buffer, pos, bytes);
pos += bytes;
+ blockIndex++;
}
if (pos == offset) return -1;
- else blockIndex++;
}
return (pos - offset);
}
/** This is a horrendously inefficient way of reading data. Don't! */
@Override public int read() throws IOException
{
byte[] data = new byte[1];
int bytes = read(data, 0, data.length);
if (bytes < 0) throw new BufferUnderflowException();
if (bytes == 0)
throw new Error(
"Implementation error in File.read(byte[1]): returned 0");
return data[0];
}
private int blockIndex;
};
}
/** Encrypted blocks to be saved in a {@link Store}. */
public List<EncryptedBlock> toSave()
{
LinkedList<EncryptedBlock> everything = Lists.newLinkedList(ciphertext);
everything.push(header);
return everything;
}
/** A link to the {@link File} itself. */
public Link link() { return header.link(); }
/**
* The contents of the file.
*
* @throws IOException on I/O errors such as network failures
*/
List<ByteBuffer> content() throws IOException
{
List<ByteBuffer> content = Lists.newLinkedList();
for (Block b : plaintext) content.add(b.content());
return content;
}
@Override public boolean equals(Object o)
{
if (o == null) return false;
if (!(o instanceof File)) return false;
File f = (File) o;
if (!this.header.equals(f.header)) return false;
if (!this.plaintext.equals(f.plaintext)) return false;
if (!this.ciphertext.equals(f.ciphertext)) return false;
return true;
}
@Override
public String toString()
{
return "Encrypted File [ " + plaintext.size() + " blocks, name = '" + header.name() + "' ]";
}
/** Convert buffers of data, which may have any size, into buffers of a desired chunk size. */
private static Collection<ByteBuffer> rechunk(Iterable<ByteBuffer> content, int chunkSize)
{
Iterator<ByteBuffer> i = content.iterator();
ByteBuffer next = null;
List<ByteBuffer> chunked = Lists.newLinkedList();
ByteBuffer current = ByteBuffer.allocate(chunkSize);
while (true)
{
// Fetch the next input buffer (if necessary). If there are none, we're done.
if ((next == null) || !next.hasRemaining())
{
if (i.hasNext()) next = i.next();
else break;
// If the next batch of content is already the right size, add it directly.
if (next.remaining() == chunkSize)
{
chunked.add(next);
continue;
}
}
// If the current output buffer is full, create a new one.
if (current.remaining() == 0)
{
current.flip();
chunked.add(current);
current = ByteBuffer.allocate(chunkSize);
}
// Copy data from input to output.
int toCopy = Math.min(next.remaining(), current.remaining());
next.get(current.array(), current.position(), toCopy);
current.position(current.position() + toCopy);
}
if (current.position() > 0)
{
current.flip();
chunked.add(current);
}
return chunked;
}
/** Default constructor; produces an anonymous file */
private File(EncryptedBlock header,
Collection<Block> plaintext, Collection<EncryptedBlock> ciphertext)
{
this.header = header;
this.plaintext = ImmutableList.<Block>builder().addAll(plaintext).build();
this.ciphertext = ImmutableList.<EncryptedBlock>builder().addAll(ciphertext).build();
}
private final EncryptedBlock header;
private final ImmutableList<Block> plaintext;
private final ImmutableList<EncryptedBlock> ciphertext;
}
| false | true | public InputStream getInputStream()
{
final ByteBuffer[] buffers = new ByteBuffer[plaintext.size()];
for (int i = 0; i < buffers.length; i++)
buffers[i] = plaintext.get(i).content();
return new InputStream()
{
@Override public int read(byte[] buffer, int offset, int len)
{
if (len == 0) return 0;
if (blockIndex >= plaintext.size()) return -1;
int pos = offset;
while (pos < len)
{
ByteBuffer next = buffers[blockIndex];
if (next.remaining() > 0)
{
int bytes = next.remaining();
next.get(buffer, pos, bytes);
pos += bytes;
}
if (pos == offset) return -1;
else blockIndex++;
}
return (pos - offset);
}
/** This is a horrendously inefficient way of reading data. Don't! */
@Override public int read() throws IOException
{
byte[] data = new byte[1];
int bytes = read(data, 0, data.length);
if (bytes < 0) throw new BufferUnderflowException();
if (bytes == 0)
throw new Error(
"Implementation error in File.read(byte[1]): returned 0");
return data[0];
}
private int blockIndex;
};
}
| public InputStream getInputStream()
{
final ByteBuffer[] buffers = new ByteBuffer[plaintext.size()];
for (int i = 0; i < buffers.length; i++)
buffers[i] = plaintext.get(i).content();
return new InputStream()
{
@Override public int read(byte[] buffer, int offset, int len)
{
if (len == 0) return 0;
if (blockIndex >= plaintext.size()) return -1;
int pos = offset;
while (pos < (offset + len))
{
ByteBuffer next = buffers[blockIndex];
if (next.remaining() > len)
{
next.get(buffer, pos, len);
pos += len;
}
else if (next.remaining() > 0)
{
int bytes = next.remaining();
next.get(buffer, pos, bytes);
pos += bytes;
blockIndex++;
}
if (pos == offset) return -1;
}
return (pos - offset);
}
/** This is a horrendously inefficient way of reading data. Don't! */
@Override public int read() throws IOException
{
byte[] data = new byte[1];
int bytes = read(data, 0, data.length);
if (bytes < 0) throw new BufferUnderflowException();
if (bytes == 0)
throw new Error(
"Implementation error in File.read(byte[1]): returned 0");
return data[0];
}
private int blockIndex;
};
}
|
diff --git a/module-nio/src/main/java/org/apache/http/impl/nio/reactor/AbstractMultiworkerIOReactor.java b/module-nio/src/main/java/org/apache/http/impl/nio/reactor/AbstractMultiworkerIOReactor.java
index fd8a27a2e..8b0148539 100644
--- a/module-nio/src/main/java/org/apache/http/impl/nio/reactor/AbstractMultiworkerIOReactor.java
+++ b/module-nio/src/main/java/org/apache/http/impl/nio/reactor/AbstractMultiworkerIOReactor.java
@@ -1,344 +1,347 @@
/*
* $HeadURL$
* $Revision$
* $Date$
*
* ====================================================================
* 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*
*/
package org.apache.http.impl.nio.reactor;
import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.Socket;
import java.nio.channels.Channel;
import java.nio.channels.ClosedChannelException;
import java.nio.channels.ClosedSelectorException;
import java.nio.channels.SelectableChannel;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.ThreadFactory;
import org.apache.http.nio.params.NIOReactorParams;
import org.apache.http.nio.reactor.IOEventDispatch;
import org.apache.http.nio.reactor.IOReactor;
import org.apache.http.nio.reactor.IOReactorException;
import org.apache.http.nio.reactor.IOReactorExceptionHandler;
import org.apache.http.nio.reactor.IOReactorStatus;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
public abstract class AbstractMultiworkerIOReactor implements IOReactor {
protected volatile IOReactorStatus status;
protected final HttpParams params;
protected final Selector selector;
protected final long selectTimeout;
private final int workerCount;
private final ThreadFactory threadFactory;
private final BaseIOReactor[] dispatchers;
private final Worker[] workers;
private final Thread[] threads;
private final long gracePeriod;
private final Object shutdownMutex;
protected IOReactorExceptionHandler exceptionHandler;
private int currentWorker = 0;
public AbstractMultiworkerIOReactor(
int workerCount,
final ThreadFactory threadFactory,
final HttpParams params) throws IOReactorException {
super();
if (workerCount <= 0) {
throw new IllegalArgumentException("Worker count may not be negative or zero");
}
if (params == null) {
throw new IllegalArgumentException("HTTP parameters may not be null");
}
try {
this.selector = Selector.open();
} catch (IOException ex) {
throw new IOReactorException("Failure opening selector", ex);
}
this.params = params;
this.selectTimeout = NIOReactorParams.getSelectInterval(params);
this.gracePeriod = NIOReactorParams.getGracePeriod(params);
this.shutdownMutex = new Object();
this.workerCount = workerCount;
if (threadFactory != null) {
this.threadFactory = threadFactory;
} else {
this.threadFactory = new DefaultThreadFactory();
}
this.dispatchers = new BaseIOReactor[workerCount];
this.workers = new Worker[workerCount];
this.threads = new Thread[workerCount];
this.status = IOReactorStatus.INACTIVE;
}
public IOReactorStatus getStatus() {
return this.status;
}
public void setExceptionHandler(final IOReactorExceptionHandler exceptionHandler) {
this.exceptionHandler = exceptionHandler;
}
protected abstract void processEvents(int count) throws IOReactorException;
protected abstract void cancelRequests() throws IOReactorException;
public void execute(
final IOEventDispatch eventDispatch) throws InterruptedIOException, IOReactorException {
if (eventDispatch == null) {
throw new IllegalArgumentException("Event dispatcher may not be null");
}
this.status = IOReactorStatus.ACTIVE;
// Start I/O dispatchers
for (int i = 0; i < this.dispatchers.length; i++) {
BaseIOReactor dispatcher = new BaseIOReactor(this.selectTimeout);
dispatcher.setExceptionHandler(exceptionHandler);
this.dispatchers[i] = dispatcher;
}
for (int i = 0; i < this.workerCount; i++) {
BaseIOReactor dispatcher = this.dispatchers[i];
this.workers[i] = new Worker(dispatcher, eventDispatch);
this.threads[i] = this.threadFactory.newThread(this.workers[i]);
}
for (int i = 0; i < this.workerCount; i++) {
if (this.status != IOReactorStatus.ACTIVE) {
return;
}
this.threads[i].start();
}
+ boolean completed = false;
try {
for (;;) {
int readyCount;
try {
readyCount = this.selector.select(this.selectTimeout);
} catch (InterruptedIOException ex) {
throw ex;
} catch (IOException ex) {
throw new IOReactorException("Unexpected selector failure", ex);
}
if (this.status.compareTo(IOReactorStatus.ACTIVE) > 0) {
+ completed = true;
break;
}
processEvents(readyCount);
// Verify I/O dispatchers
for (int i = 0; i < this.workerCount; i++) {
Worker worker = this.workers[i];
Thread thread = this.threads[i];
if (!thread.isAlive()) {
Exception ex = worker.getException();
if (ex instanceof IOReactorException) {
throw (IOReactorException) ex;
} else if (ex instanceof InterruptedIOException) {
throw (InterruptedIOException) ex;
} else if (ex instanceof RuntimeException) {
throw (RuntimeException) ex;
} else if (ex != null) {
throw new IOReactorException(ex.getMessage(), ex);
}
}
}
}
} catch (ClosedSelectorException ex) {
} finally {
- // Shutdown
try {
doShutdown();
} catch (IOException ex) {
- throw new IOReactorException(ex.getMessage(), ex);
+ if (completed) {
+ throw new IOReactorException(ex.getMessage(), ex);
+ }
}
}
}
protected void doShutdown() throws IOException {
if (this.status.compareTo(IOReactorStatus.SHUTTING_DOWN) >= 0) {
return;
}
this.status = IOReactorStatus.SHUTTING_DOWN;
cancelRequests();
this.selector.wakeup();
// Close out all channels
if (this.selector.isOpen()) {
Set<SelectionKey> keys = this.selector.keys();
for (Iterator<SelectionKey> it = keys.iterator(); it.hasNext(); ) {
try {
SelectionKey key = it.next();
Channel channel = key.channel();
if (channel != null) {
channel.close();
}
} catch (IOException ignore) {
}
}
// Stop dispatching I/O events
this.selector.close();
}
// Attempt to shut down I/O dispatchers gracefully
for (int i = 0; i < this.workerCount; i++) {
BaseIOReactor dispatcher = this.dispatchers[i];
dispatcher.gracefulShutdown();
}
try {
// Force shut down I/O dispatchers if they fail to terminate
// in time
for (int i = 0; i < this.workerCount; i++) {
BaseIOReactor dispatcher = this.dispatchers[i];
if (dispatcher.getStatus() != IOReactorStatus.INACTIVE) {
dispatcher.awaitShutdown(this.gracePeriod);
}
if (dispatcher.getStatus() != IOReactorStatus.SHUT_DOWN) {
dispatcher.hardShutdown();
}
}
// Join worker threads
for (int i = 0; i < this.workerCount; i++) {
Thread t = this.threads[i];
if (t != null) {
t.join(this.gracePeriod);
}
}
} catch (InterruptedException ex) {
throw new InterruptedIOException(ex.getMessage());
} finally {
synchronized (this.shutdownMutex) {
this.status = IOReactorStatus.SHUT_DOWN;
this.shutdownMutex.notifyAll();
}
}
}
protected void addChannel(final ChannelEntry entry) {
// Distribute new channels among the workers
this.dispatchers[this.currentWorker++ % this.workerCount].addChannel(entry);
}
protected SelectionKey registerChannel(
final SelectableChannel channel, int ops) throws ClosedChannelException {
return channel.register(this.selector, ops);
}
protected void prepareSocket(final Socket socket) throws IOException {
socket.setTcpNoDelay(HttpConnectionParams.getTcpNoDelay(this.params));
socket.setSoTimeout(HttpConnectionParams.getSoTimeout(this.params));
int linger = HttpConnectionParams.getLinger(this.params);
if (linger >= 0) {
socket.setSoLinger(linger > 0, linger);
}
}
protected void awaitShutdown(long timeout) throws InterruptedException {
synchronized (this.shutdownMutex) {
long deadline = System.currentTimeMillis() + timeout;
long remaining = timeout;
while (this.status != IOReactorStatus.SHUT_DOWN) {
this.shutdownMutex.wait(remaining);
if (timeout > 0) {
remaining = deadline - System.currentTimeMillis();
if (remaining <= 0) {
break;
}
}
}
}
}
public void shutdown() throws IOException {
shutdown(2000);
}
public void shutdown(long waitMs) throws IOException {
if (this.status != IOReactorStatus.ACTIVE) {
return;
}
this.status = IOReactorStatus.SHUTDOWN_REQUEST;
this.selector.wakeup();
try {
awaitShutdown(waitMs);
} catch (InterruptedException ignore) {
}
}
static class Worker implements Runnable {
final BaseIOReactor dispatcher;
final IOEventDispatch eventDispatch;
private volatile Exception exception;
public Worker(final BaseIOReactor dispatcher, final IOEventDispatch eventDispatch) {
super();
this.dispatcher = dispatcher;
this.eventDispatch = eventDispatch;
}
public void run() {
try {
this.dispatcher.execute(this.eventDispatch);
} catch (InterruptedIOException ex) {
this.exception = ex;
} catch (IOReactorException ex) {
this.exception = ex;
} catch (RuntimeException ex) {
this.exception = ex;
}
}
public Exception getException() {
return this.exception;
}
}
static class DefaultThreadFactory implements ThreadFactory {
private static volatile int COUNT = 0;
public Thread newThread(final Runnable r) {
return new Thread(r, "I/O dispatcher " + (++COUNT));
}
}
}
| false | true | public void execute(
final IOEventDispatch eventDispatch) throws InterruptedIOException, IOReactorException {
if (eventDispatch == null) {
throw new IllegalArgumentException("Event dispatcher may not be null");
}
this.status = IOReactorStatus.ACTIVE;
// Start I/O dispatchers
for (int i = 0; i < this.dispatchers.length; i++) {
BaseIOReactor dispatcher = new BaseIOReactor(this.selectTimeout);
dispatcher.setExceptionHandler(exceptionHandler);
this.dispatchers[i] = dispatcher;
}
for (int i = 0; i < this.workerCount; i++) {
BaseIOReactor dispatcher = this.dispatchers[i];
this.workers[i] = new Worker(dispatcher, eventDispatch);
this.threads[i] = this.threadFactory.newThread(this.workers[i]);
}
for (int i = 0; i < this.workerCount; i++) {
if (this.status != IOReactorStatus.ACTIVE) {
return;
}
this.threads[i].start();
}
try {
for (;;) {
int readyCount;
try {
readyCount = this.selector.select(this.selectTimeout);
} catch (InterruptedIOException ex) {
throw ex;
} catch (IOException ex) {
throw new IOReactorException("Unexpected selector failure", ex);
}
if (this.status.compareTo(IOReactorStatus.ACTIVE) > 0) {
break;
}
processEvents(readyCount);
// Verify I/O dispatchers
for (int i = 0; i < this.workerCount; i++) {
Worker worker = this.workers[i];
Thread thread = this.threads[i];
if (!thread.isAlive()) {
Exception ex = worker.getException();
if (ex instanceof IOReactorException) {
throw (IOReactorException) ex;
} else if (ex instanceof InterruptedIOException) {
throw (InterruptedIOException) ex;
} else if (ex instanceof RuntimeException) {
throw (RuntimeException) ex;
} else if (ex != null) {
throw new IOReactorException(ex.getMessage(), ex);
}
}
}
}
} catch (ClosedSelectorException ex) {
} finally {
// Shutdown
try {
doShutdown();
} catch (IOException ex) {
throw new IOReactorException(ex.getMessage(), ex);
}
}
}
| public void execute(
final IOEventDispatch eventDispatch) throws InterruptedIOException, IOReactorException {
if (eventDispatch == null) {
throw new IllegalArgumentException("Event dispatcher may not be null");
}
this.status = IOReactorStatus.ACTIVE;
// Start I/O dispatchers
for (int i = 0; i < this.dispatchers.length; i++) {
BaseIOReactor dispatcher = new BaseIOReactor(this.selectTimeout);
dispatcher.setExceptionHandler(exceptionHandler);
this.dispatchers[i] = dispatcher;
}
for (int i = 0; i < this.workerCount; i++) {
BaseIOReactor dispatcher = this.dispatchers[i];
this.workers[i] = new Worker(dispatcher, eventDispatch);
this.threads[i] = this.threadFactory.newThread(this.workers[i]);
}
for (int i = 0; i < this.workerCount; i++) {
if (this.status != IOReactorStatus.ACTIVE) {
return;
}
this.threads[i].start();
}
boolean completed = false;
try {
for (;;) {
int readyCount;
try {
readyCount = this.selector.select(this.selectTimeout);
} catch (InterruptedIOException ex) {
throw ex;
} catch (IOException ex) {
throw new IOReactorException("Unexpected selector failure", ex);
}
if (this.status.compareTo(IOReactorStatus.ACTIVE) > 0) {
completed = true;
break;
}
processEvents(readyCount);
// Verify I/O dispatchers
for (int i = 0; i < this.workerCount; i++) {
Worker worker = this.workers[i];
Thread thread = this.threads[i];
if (!thread.isAlive()) {
Exception ex = worker.getException();
if (ex instanceof IOReactorException) {
throw (IOReactorException) ex;
} else if (ex instanceof InterruptedIOException) {
throw (InterruptedIOException) ex;
} else if (ex instanceof RuntimeException) {
throw (RuntimeException) ex;
} else if (ex != null) {
throw new IOReactorException(ex.getMessage(), ex);
}
}
}
}
} catch (ClosedSelectorException ex) {
} finally {
try {
doShutdown();
} catch (IOException ex) {
if (completed) {
throw new IOReactorException(ex.getMessage(), ex);
}
}
}
}
|
diff --git a/src/org/rascalmpl/unicode/UnicodeDetector.java b/src/org/rascalmpl/unicode/UnicodeDetector.java
index a04bb4cc59..edee4ec482 100644
--- a/src/org/rascalmpl/unicode/UnicodeDetector.java
+++ b/src/org/rascalmpl/unicode/UnicodeDetector.java
@@ -1,159 +1,164 @@
/*******************************************************************************
* Copyright (c) 2009-2012 CWI
* 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:
* * Davy Landman - [email protected] - CWI
*******************************************************************************/
package org.rascalmpl.unicode;
import java.io.IOException;
import java.io.InputStream;
import java.nio.charset.Charset;
public class UnicodeDetector {
private static final int maximumBOMLength = 4;
private static final ByteOrderMarker[] boms = {
ByteOrderMarker.UTF8,
ByteOrderMarker.UTF32BE,
ByteOrderMarker.UTF32LE, // 32 first, to avoid ambituity with the 16 LE
ByteOrderMarker.UTF16BE,
ByteOrderMarker.UTF16LE
};
/**
* Try to detect an encoding, only UTF8 and UTF32 we can try to detect.
* Other detection are to intensive.
* <b>Warning, don't fallback to UTF8, if this method didn't return UTF8 as a encoding
* it really isn't UTF8! Try Charset.defaultCharset().</b>
* @return either the detected Charset or null
*/
public static Charset detectByContent(byte[] buffer, int bufferSize) {
// first, lets see if it might be a valid UTF8 (biggest chance)
// http://www.w3.org/International/questions/qa-forms-utf-8
// we translate this Regular Expression to a while loop
// using the help of
// http://stackoverflow.com/questions/1031645/how-to-detect-utf-8-in-plain-c
boolean match= true;
int i = 0;
while (match && i + 3 < bufferSize) {
int c0 = buffer[i] & 0xff;
if (c0 == 0x09 || c0 == 0x0A || c0 == 0x0D ||
(0x20 <= c0 && c0 <= 0x7E)) {
// just plain ASCII
i++;
continue;
}
+ if (0x01 <= c0 || c0 <= 0x1F) {
+ // actually also valid UTF8 chars
+ i++;
+ continue;
+ }
int c1 = buffer[i + 1] & 0xff;
if ((0xC2 <= c0 && c0 <= 0xDF) &&
(0x80 <= c1 && c1 <= 0xBF)) {
// non-overlong 2-byte
i += 2;
continue;
}
int c2 = buffer[i + 2] & 0xff;
if( (// excluding overlongs
c0 == 0xE0 &&
(0xA0 <= c1 && c1 <= 0xBF) &&
(0x80 <= c2 && c2 <= 0xBF)
) ||
(// straight 3-byte
((0xE1 <= c0 && c0 <= 0xEC) ||
c0 == 0xEE ||
c0 == 0xEF) &&
(0x80 <= c1 && c1 <= 0xBF) &&
(0x80 <= c2 && c2 <= 0xBF)
) ||
(// excluding surrogates
c0 == 0xED &&
(0x80 <= c1 && c1 <= 0x9F) &&
(0x80 <= c2 && c2 <= 0xBF)
)
) {
i += 3;
continue;
}
int c3 = buffer[i + 3] & 0xff;
if( (// planes 1-3
c0 == 0xF0 &&
(0x90 <= c1 && c1 <= 0xBF) &&
(0x80 <= c2 && c2 <= 0xBF) &&
(0x80 <= c3 && c3 <= 0xBF)
) ||
(// planes 4-15
(0xF1 <= c0 && c0 <= 0xF3) &&
(0x80 <= c1 && c1 <= 0xBF) &&
(0x80 <= c2 && c2 <= 0xBF) &&
(0x80 <= c3 && c3 <= 0xBF)
) ||
(// plane 16
c0 == 0xF4 &&
(0x80 <= c1 && c1 <= 0x8F) &&
(0x80 <= c2 && c2 <= 0xBF) &&
(0x80 <= c3 && c3 <= 0xBF)
)
) {
i += 4;
continue;
}
match = false;
break;
}
if (match)
return Charset.forName("UTF8");
// the other thing we can check if it might be a UTF32 file
// they must be of the pattern 0x00 0x10 0x.. 0x.. (BE) or 0x.. 0x.. 0x10 0x00 (LE)
match = true;
for (i = 0; i + 1 < bufferSize && match; i+=2) {
match = (buffer[i] & 0xff) == 0 && (buffer[i + 1] & 0xff) == 0x10;
}
if (match)
return Charset.forName("UTF-32BE");
match = true;
for (i = 2; i + 1 < bufferSize && match; i+=2) {
match = (buffer[i] & 0xff) == 0x10 && (buffer[i + 1] & 0xff) == 0x0;
}
if (match)
return Charset.forName("UTF-32LE");
return null;
}
public static ByteOrderMarker detectBom(byte[] detectionBuffer, int bufferSize) {
for (ByteOrderMarker b: boms) {
if (b.matches(detectionBuffer, bufferSize))
return b;
}
return null;
}
public static int getMaximumBOMLength() {
return maximumBOMLength;
}
public static int getSuggestedDetectionSampleSize() {
return 32;
}
/**
* Try to estimate if the content might be incoded in UTF-8/16/32.
* <b>Warning, if this method does not return a charset, it can't be UTF8 or UTF32.
* It might be UTF-16 (unlickely) or a strange codepoint.
* </b>
*/
public static Charset estimateCharset(InputStream in) throws IOException {
byte[] buffer = new byte[getSuggestedDetectionSampleSize()];
int totalRead = in.read(buffer);
ByteOrderMarker bom = detectBom(buffer, totalRead);
if (bom != null)
return bom.getCharset();
return detectByContent(buffer, totalRead);
}
}
| true | true | public static Charset detectByContent(byte[] buffer, int bufferSize) {
// first, lets see if it might be a valid UTF8 (biggest chance)
// http://www.w3.org/International/questions/qa-forms-utf-8
// we translate this Regular Expression to a while loop
// using the help of
// http://stackoverflow.com/questions/1031645/how-to-detect-utf-8-in-plain-c
boolean match= true;
int i = 0;
while (match && i + 3 < bufferSize) {
int c0 = buffer[i] & 0xff;
if (c0 == 0x09 || c0 == 0x0A || c0 == 0x0D ||
(0x20 <= c0 && c0 <= 0x7E)) {
// just plain ASCII
i++;
continue;
}
int c1 = buffer[i + 1] & 0xff;
if ((0xC2 <= c0 && c0 <= 0xDF) &&
(0x80 <= c1 && c1 <= 0xBF)) {
// non-overlong 2-byte
i += 2;
continue;
}
int c2 = buffer[i + 2] & 0xff;
if( (// excluding overlongs
c0 == 0xE0 &&
(0xA0 <= c1 && c1 <= 0xBF) &&
(0x80 <= c2 && c2 <= 0xBF)
) ||
(// straight 3-byte
((0xE1 <= c0 && c0 <= 0xEC) ||
c0 == 0xEE ||
c0 == 0xEF) &&
(0x80 <= c1 && c1 <= 0xBF) &&
(0x80 <= c2 && c2 <= 0xBF)
) ||
(// excluding surrogates
c0 == 0xED &&
(0x80 <= c1 && c1 <= 0x9F) &&
(0x80 <= c2 && c2 <= 0xBF)
)
) {
i += 3;
continue;
}
int c3 = buffer[i + 3] & 0xff;
if( (// planes 1-3
c0 == 0xF0 &&
(0x90 <= c1 && c1 <= 0xBF) &&
(0x80 <= c2 && c2 <= 0xBF) &&
(0x80 <= c3 && c3 <= 0xBF)
) ||
(// planes 4-15
(0xF1 <= c0 && c0 <= 0xF3) &&
(0x80 <= c1 && c1 <= 0xBF) &&
(0x80 <= c2 && c2 <= 0xBF) &&
(0x80 <= c3 && c3 <= 0xBF)
) ||
(// plane 16
c0 == 0xF4 &&
(0x80 <= c1 && c1 <= 0x8F) &&
(0x80 <= c2 && c2 <= 0xBF) &&
(0x80 <= c3 && c3 <= 0xBF)
)
) {
i += 4;
continue;
}
match = false;
break;
}
if (match)
return Charset.forName("UTF8");
// the other thing we can check if it might be a UTF32 file
// they must be of the pattern 0x00 0x10 0x.. 0x.. (BE) or 0x.. 0x.. 0x10 0x00 (LE)
match = true;
for (i = 0; i + 1 < bufferSize && match; i+=2) {
match = (buffer[i] & 0xff) == 0 && (buffer[i + 1] & 0xff) == 0x10;
}
if (match)
return Charset.forName("UTF-32BE");
match = true;
for (i = 2; i + 1 < bufferSize && match; i+=2) {
match = (buffer[i] & 0xff) == 0x10 && (buffer[i + 1] & 0xff) == 0x0;
}
if (match)
return Charset.forName("UTF-32LE");
return null;
}
| public static Charset detectByContent(byte[] buffer, int bufferSize) {
// first, lets see if it might be a valid UTF8 (biggest chance)
// http://www.w3.org/International/questions/qa-forms-utf-8
// we translate this Regular Expression to a while loop
// using the help of
// http://stackoverflow.com/questions/1031645/how-to-detect-utf-8-in-plain-c
boolean match= true;
int i = 0;
while (match && i + 3 < bufferSize) {
int c0 = buffer[i] & 0xff;
if (c0 == 0x09 || c0 == 0x0A || c0 == 0x0D ||
(0x20 <= c0 && c0 <= 0x7E)) {
// just plain ASCII
i++;
continue;
}
if (0x01 <= c0 || c0 <= 0x1F) {
// actually also valid UTF8 chars
i++;
continue;
}
int c1 = buffer[i + 1] & 0xff;
if ((0xC2 <= c0 && c0 <= 0xDF) &&
(0x80 <= c1 && c1 <= 0xBF)) {
// non-overlong 2-byte
i += 2;
continue;
}
int c2 = buffer[i + 2] & 0xff;
if( (// excluding overlongs
c0 == 0xE0 &&
(0xA0 <= c1 && c1 <= 0xBF) &&
(0x80 <= c2 && c2 <= 0xBF)
) ||
(// straight 3-byte
((0xE1 <= c0 && c0 <= 0xEC) ||
c0 == 0xEE ||
c0 == 0xEF) &&
(0x80 <= c1 && c1 <= 0xBF) &&
(0x80 <= c2 && c2 <= 0xBF)
) ||
(// excluding surrogates
c0 == 0xED &&
(0x80 <= c1 && c1 <= 0x9F) &&
(0x80 <= c2 && c2 <= 0xBF)
)
) {
i += 3;
continue;
}
int c3 = buffer[i + 3] & 0xff;
if( (// planes 1-3
c0 == 0xF0 &&
(0x90 <= c1 && c1 <= 0xBF) &&
(0x80 <= c2 && c2 <= 0xBF) &&
(0x80 <= c3 && c3 <= 0xBF)
) ||
(// planes 4-15
(0xF1 <= c0 && c0 <= 0xF3) &&
(0x80 <= c1 && c1 <= 0xBF) &&
(0x80 <= c2 && c2 <= 0xBF) &&
(0x80 <= c3 && c3 <= 0xBF)
) ||
(// plane 16
c0 == 0xF4 &&
(0x80 <= c1 && c1 <= 0x8F) &&
(0x80 <= c2 && c2 <= 0xBF) &&
(0x80 <= c3 && c3 <= 0xBF)
)
) {
i += 4;
continue;
}
match = false;
break;
}
if (match)
return Charset.forName("UTF8");
// the other thing we can check if it might be a UTF32 file
// they must be of the pattern 0x00 0x10 0x.. 0x.. (BE) or 0x.. 0x.. 0x10 0x00 (LE)
match = true;
for (i = 0; i + 1 < bufferSize && match; i+=2) {
match = (buffer[i] & 0xff) == 0 && (buffer[i + 1] & 0xff) == 0x10;
}
if (match)
return Charset.forName("UTF-32BE");
match = true;
for (i = 2; i + 1 < bufferSize && match; i+=2) {
match = (buffer[i] & 0xff) == 0x10 && (buffer[i + 1] & 0xff) == 0x0;
}
if (match)
return Charset.forName("UTF-32LE");
return null;
}
|
diff --git a/docdoku-server/docdoku-server-web/src/main/java/com/docdoku/server/rest/util/InstanceAttributeDozerConverter.java b/docdoku-server/docdoku-server-web/src/main/java/com/docdoku/server/rest/util/InstanceAttributeDozerConverter.java
index f9dd342f0..52e07795a 100644
--- a/docdoku-server/docdoku-server-web/src/main/java/com/docdoku/server/rest/util/InstanceAttributeDozerConverter.java
+++ b/docdoku-server/docdoku-server-web/src/main/java/com/docdoku/server/rest/util/InstanceAttributeDozerConverter.java
@@ -1,89 +1,90 @@
/*
* DocDoku, Professional Open Source
* Copyright 2006 - 2013 DocDoku SARL
*
* This file is part of DocDokuPLM.
*
* DocDokuPLM is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* DocDokuPLM is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with DocDokuPLM. If not, see <http://www.gnu.org/licenses/>.
*/
package com.docdoku.server.rest.util;
import com.docdoku.core.common.BinaryResource;
import com.docdoku.core.meta.InstanceAttribute;
import com.docdoku.core.meta.InstanceBooleanAttribute;
import com.docdoku.core.meta.InstanceDateAttribute;
import com.docdoku.core.meta.InstanceNumberAttribute;
import com.docdoku.core.meta.InstanceTextAttribute;
import com.docdoku.core.meta.InstanceURLAttribute;
import com.docdoku.server.rest.dto.InstanceAttributeDTO;
import org.dozer.DozerConverter;
import java.util.Date;
/**
* @author Florent Garin
*/
public class InstanceAttributeDozerConverter extends DozerConverter<InstanceAttribute, InstanceAttributeDTO> {
public InstanceAttributeDozerConverter() {
super(InstanceAttribute.class, InstanceAttributeDTO.class);
}
@Override
public InstanceAttributeDTO convertTo(InstanceAttribute source, InstanceAttributeDTO bdestination) {
InstanceAttributeDTO.Type type;
- String value;
+ String value = "";
if (source instanceof InstanceBooleanAttribute) {
type = InstanceAttributeDTO.Type.BOOLEAN;
value=source.getValue()+"";
} else if (source instanceof InstanceTextAttribute) {
type = InstanceAttributeDTO.Type.TEXT;
value=source.getValue()+"";
} else if (source instanceof InstanceNumberAttribute) {
type = InstanceAttributeDTO.Type.NUMBER;
value=source.getValue()+"";
} else if (source instanceof InstanceDateAttribute) {
type = InstanceAttributeDTO.Type.DATE;
- value=((InstanceDateAttribute)source).getDateValue().getTime()+"";
+ if(((InstanceDateAttribute)source).getDateValue() != null)
+ value=((InstanceDateAttribute)source).getDateValue().getTime()+"";
} else if (source instanceof InstanceURLAttribute) {
type = InstanceAttributeDTO.Type.URL;
value=source.getValue()+"";
} else {
throw new IllegalArgumentException("Instance attribute not supported");
}
return new InstanceAttributeDTO(source.getName(), type, value);
}
@Override
public InstanceAttribute convertFrom(InstanceAttributeDTO source, InstanceAttribute destination) {
switch(source.getType()){
case BOOLEAN:
return new InstanceBooleanAttribute(source.getName(), Boolean.parseBoolean(source.getValue()));
case DATE:
return new InstanceDateAttribute(source.getName(), new Date(Long.parseLong(source.getValue())));
case NUMBER:
return new InstanceNumberAttribute(source.getName(), Float.parseFloat(source.getValue()));
case TEXT:
return new InstanceTextAttribute(source.getName(), source.getValue());
case URL:
return new InstanceURLAttribute(source.getName(), source.getValue());
}
throw new IllegalArgumentException("Instance attribute not supported");
}
}
| false | true | public InstanceAttributeDTO convertTo(InstanceAttribute source, InstanceAttributeDTO bdestination) {
InstanceAttributeDTO.Type type;
String value;
if (source instanceof InstanceBooleanAttribute) {
type = InstanceAttributeDTO.Type.BOOLEAN;
value=source.getValue()+"";
} else if (source instanceof InstanceTextAttribute) {
type = InstanceAttributeDTO.Type.TEXT;
value=source.getValue()+"";
} else if (source instanceof InstanceNumberAttribute) {
type = InstanceAttributeDTO.Type.NUMBER;
value=source.getValue()+"";
} else if (source instanceof InstanceDateAttribute) {
type = InstanceAttributeDTO.Type.DATE;
value=((InstanceDateAttribute)source).getDateValue().getTime()+"";
} else if (source instanceof InstanceURLAttribute) {
type = InstanceAttributeDTO.Type.URL;
value=source.getValue()+"";
} else {
throw new IllegalArgumentException("Instance attribute not supported");
}
return new InstanceAttributeDTO(source.getName(), type, value);
}
| public InstanceAttributeDTO convertTo(InstanceAttribute source, InstanceAttributeDTO bdestination) {
InstanceAttributeDTO.Type type;
String value = "";
if (source instanceof InstanceBooleanAttribute) {
type = InstanceAttributeDTO.Type.BOOLEAN;
value=source.getValue()+"";
} else if (source instanceof InstanceTextAttribute) {
type = InstanceAttributeDTO.Type.TEXT;
value=source.getValue()+"";
} else if (source instanceof InstanceNumberAttribute) {
type = InstanceAttributeDTO.Type.NUMBER;
value=source.getValue()+"";
} else if (source instanceof InstanceDateAttribute) {
type = InstanceAttributeDTO.Type.DATE;
if(((InstanceDateAttribute)source).getDateValue() != null)
value=((InstanceDateAttribute)source).getDateValue().getTime()+"";
} else if (source instanceof InstanceURLAttribute) {
type = InstanceAttributeDTO.Type.URL;
value=source.getValue()+"";
} else {
throw new IllegalArgumentException("Instance attribute not supported");
}
return new InstanceAttributeDTO(source.getName(), type, value);
}
|
diff --git a/src/main/java/com/concursive/connect/web/modules/blog/actions/BlogActions.java b/src/main/java/com/concursive/connect/web/modules/blog/actions/BlogActions.java
index 441ebf1..72df5d3 100644
--- a/src/main/java/com/concursive/connect/web/modules/blog/actions/BlogActions.java
+++ b/src/main/java/com/concursive/connect/web/modules/blog/actions/BlogActions.java
@@ -1,557 +1,559 @@
/*
* ConcourseConnect
* Copyright 2009 Concursive Corporation
* http://www.concursive.com
*
* This file is part of ConcourseConnect, an open source social business
* software and community platform.
*
* Concursive ConcourseConnect is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, version 3 of the License.
*
* Under the terms of the GNU Affero General Public License you must release the
* complete source code for any application that uses any part of ConcourseConnect
* (system header files and libraries used by the operating system are excluded).
* These terms must be included in any work that has ConcourseConnect components.
* If you are developing and distributing open source applications under the
* GNU Affero General Public License, then you are free to use ConcourseConnect
* under the GNU Affero General Public License.
*
* If you are deploying a web site in which users interact with any portion of
* ConcourseConnect over a network, the complete source code changes must be made
* available. For example, include a link to the source archive directly from
* your web site.
*
* For OEMs, ISVs, SIs and VARs who distribute ConcourseConnect with their
* products, and do not license and distribute their source code under the GNU
* Affero General Public License, Concursive provides a flexible commercial
* license.
*
* To anyone in doubt, we recommend the commercial license. Our commercial license
* is competitively priced and will eliminate any confusion about how
* ConcourseConnect can be used and distributed.
*
* ConcourseConnect is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License
* along with ConcourseConnect. If not, see <http://www.gnu.org/licenses/>.
*
* Attribution Notice: ConcourseConnect is an Original Work of software created
* by Concursive Corporation
*/
package com.concursive.connect.web.modules.blog.actions;
import com.concursive.commons.email.SMTPMessage;
import com.concursive.commons.email.SMTPMessageFactory;
import com.concursive.commons.images.ImageUtils;
import com.concursive.commons.text.StringUtils;
import com.concursive.commons.web.mvc.actions.ActionContext;
import com.concursive.connect.Constants;
import com.concursive.connect.config.ApplicationPrefs;
import com.concursive.connect.web.controller.actions.GenericAction;
import com.concursive.connect.web.modules.blog.dao.BlogPost;
import com.concursive.connect.web.modules.blog.dao.BlogPostCategoryList;
import com.concursive.connect.web.modules.documents.beans.FileDownload;
import com.concursive.connect.web.modules.documents.dao.FileItem;
import com.concursive.connect.web.modules.documents.dao.FileItemList;
import com.concursive.connect.web.modules.documents.dao.Thumbnail;
import com.concursive.connect.web.modules.documents.utils.FileInfo;
import com.concursive.connect.web.modules.documents.utils.HttpMultiPartParser;
import com.concursive.connect.web.modules.documents.utils.ThumbnailUtils;
import com.concursive.connect.web.modules.login.dao.User;
import com.concursive.connect.web.modules.login.utils.UserUtils;
import com.concursive.connect.web.modules.members.dao.TeamMember;
import com.concursive.connect.web.modules.members.dao.TeamMemberList;
import com.concursive.connect.web.modules.profile.dao.Project;
import com.concursive.connect.web.modules.profile.utils.ProjectUtils;
import com.concursive.connect.web.utils.HtmlSelect;
import freemarker.template.Template;
import java.io.File;
import java.io.StringWriter;
import java.sql.Connection;
import java.util.HashMap;
import java.util.Map;
import java.util.StringTokenizer;
/**
* Actions for working with blog posts
*
* @author matt rajkowski
* @created June 24, 2003
*/
public final class BlogActions extends GenericAction {
public String executeCommandDetails(ActionContext context) {
// BlogActions.do?command=Details&pid=139&id=535&popup=true /show/xyz/blog/535
String projectId = context.getRequest().getParameter("pid");
String id = context.getRequest().getParameter("id");
String redirect = "/show/" + ProjectUtils.loadProject(Integer.parseInt(projectId)).getUniqueId() + "/blog/" + id;
context.getRequest().setAttribute("redirectTo", redirect);
context.getRequest().removeAttribute("PageLayout");
return "Redirect301";
}
/**
* Description of the Method
*
* @param context Description of the Parameter
* @return Description of the Return Value
*/
public String executeCommandEditCategoryList(ActionContext context) {
Connection db = null;
//Parameters
String projectId = context.getRequest().getParameter("pid");
String previousId = context.getRequest().getParameter("previousId");
try {
db = getConnection(context);
// Load the project
Project thisProject = retrieveAuthorizedProject(Integer.parseInt(projectId), context);
if (!hasProjectAccess(context, thisProject.getId(), "project-news-add")) {
return "PermissionError";
}
// Load the category list
BlogPostCategoryList categoryList = new BlogPostCategoryList();
categoryList.setProjectId(thisProject.getId());
categoryList.setEnabled(Constants.TRUE);
categoryList.buildList(db);
context.getRequest().setAttribute("editList", categoryList.getHtmlSelect());
// Edit List properties
context.getRequest().setAttribute("subTitleKey", "projectManagementNews.subtitle");
context.getRequest().setAttribute("subTitle", "Modify the blog post categories");
context.getRequest().setAttribute("returnUrl", ctx(context) + "/BlogActions.do?command=SaveCategoryList&pid=" + thisProject.getId() + "&previousId=" + previousId);
return ("EditListPopupOK");
} catch (Exception errorMessage) {
context.getRequest().setAttribute("Error", errorMessage);
return ("SystemError");
} finally {
this.freeConnection(context, db);
}
}
/**
* Description of the Method
*
* @param context Description of the Parameter
* @return Description of the Return Value
*/
public String executeCommandSaveCategoryList(ActionContext context) {
Connection db = null;
//Parameters
String projectId = context.getRequest().getParameter("pid");
String previousId = context.getRequest().getParameter("previousId");
try {
db = getConnection(context);
// Load the project
Project thisProject = retrieveAuthorizedProject(Integer.parseInt(projectId), context);
if (!hasProjectAccess(context, thisProject.getId(), "project-news-add")) {
return "PermissionError";
}
// Parse the request for items
String[] params = context.getRequest().getParameterValues("selectedList");
String[] names = new String[params.length];
int j = 0;
StringTokenizer st = new StringTokenizer(context.getRequest().getParameter("selectNames"), "^");
while (st.hasMoreTokens()) {
names[j] = st.nextToken();
if (System.getProperty("DEBUG") != null) {
System.out.println("ProjectManagementNews-> Item: " + names[j]);
}
j++;
}
// Load the previous category list
BlogPostCategoryList categoryList = new BlogPostCategoryList();
categoryList.setProjectId(thisProject.getId());
categoryList.buildList(db);
categoryList.updateValues(db, params, names);
// Reload the updated list for display
categoryList.clear();
categoryList.setEnabled(Constants.TRUE);
categoryList.setIncludeId(previousId);
categoryList.buildList(db);
HtmlSelect thisSelect = categoryList.getHtmlSelect();
thisSelect.addItem(-1, "-- None --", 0);
context.getRequest().setAttribute("editList", thisSelect);
return ("EditListPopupCloseOK");
} catch (Exception errorMessage) {
context.getRequest().setAttribute("Error", errorMessage);
return ("SystemError");
} finally {
this.freeConnection(context, db);
}
}
/**
* Description of the Method
*
* @param context Description of the Parameter
* @return Description of the Return Value
*/
public String executeCommandEmailMe(ActionContext context) {
Connection db = null;
//Parameters
String projectId = context.getRequest().getParameter("pid");
String newsId = context.getRequest().getParameter("id");
try {
db = getConnection(context);
// Load the project
Project thisProject = retrieveAuthorizedProject(Integer.parseInt(projectId), context);
if (!hasProjectAccess(context, thisProject.getId(), "project-news-view")) {
return "PermissionError";
}
// Load the article and send the email
BlogPost thisArticle = new BlogPost(db, Integer.parseInt(newsId), thisProject.getId());
if (1 == 1) {
ApplicationPrefs prefs = getApplicationPrefs(context);
SMTPMessage mail = SMTPMessageFactory.createSMTPMessageInstance(prefs.getPrefs());
mail.setFrom(this.getPref(context, "EMAILADDRESS"));
mail.addReplyTo(getUser(context).getEmail());
mail.setType("text/html");
mail.addTo(getUser(context).getEmail());
mail.setSubject(thisArticle.getSubject());
// Construct the message
StringBuffer body = new StringBuffer();
body.append("<table border=\"0\"");
body.append("<tr>");
body.append("<td>");
body.append(thisArticle.getIntro());
body.append("</td>");
body.append("</tr>");
if (thisArticle.hasMessage()) {
body.append("<tr><td>[message is continued...]</td></tr>");
}
body.append("<tr><td> </td></tr>");
body.append("<tr><td><a href=\"" + getLink(context, "show/" + thisProject.getUniqueId() + "/post/" + thisArticle.getId()) + "\">View this message online</a></td></tr>");
body.append("</table>");
// Send it...
mail.setBody(body.toString());
mail.send();
}
context.getRequest().setAttribute("project", thisProject);
context.getRequest().setAttribute("IncludeSection", "news_email_ok");
context.getRequest().setAttribute("pid", projectId);
return "EmailMeOK";
} catch (Exception errorMessage) {
context.getRequest().setAttribute("Error", errorMessage);
return ("SystemError");
} finally {
this.freeConnection(context, db);
}
}
/**
* Description of the Method
*
* @param context Description of the Parameter
* @return Description of the Return Value
*/
public String executeCommandEmailTeam(ActionContext context) {
Connection db = null;
//Parameters
String projectId = context.getRequest().getParameter("pid");
String newsId = context.getRequest().getParameter("id");
try {
db = getConnection(context);
// Load the project
Project thisProject = retrieveAuthorizedProject(Integer.parseInt(projectId), context);
if (!hasProjectAccess(context, thisProject.getId(), "project-news-add")) {
return "PermissionError";
}
// Load the article and send the email
BlogPost post = new BlogPost(db, Integer.parseInt(newsId), thisProject.getId());
if (1 == 1) {
ApplicationPrefs prefs = getApplicationPrefs(context);
SMTPMessage mail = SMTPMessageFactory.createSMTPMessageInstance(prefs.getPrefs());
mail.setFrom(this.getPref(context, "EMAILADDRESS"));
mail.setType("text/html");
mail.setSubject("[" + thisProject.getTitle() + "] Blog Post");
// Populate the message template
Template template = getFreemarkerConfiguration(context).getTemplate("blog_notification-html.ftl");
Map bodyMappings = new HashMap();
bodyMappings.put("project", thisProject);
bodyMappings.put("post", post);
bodyMappings.put("author", UserUtils.loadUser(post.getEnteredBy()));
bodyMappings.put("link", new HashMap());
((Map) bodyMappings.get("link")).put("site", getServerUrl(context));
((Map) bodyMappings.get("link")).put("blog", getLink(context, "show/" + thisProject.getUniqueId() + "/blog"));
((Map) bodyMappings.get("link")).put("post", getLink(context, "show/" + thisProject.getUniqueId() + "/post/" + post.getId()));
((Map) bodyMappings.get("link")).put("settings", getLink(context, "show/" + thisProject.getUniqueId() + "/members"));
// Send to those members that requested notifications
TeamMemberList members = new TeamMemberList();
members.setProjectId(thisProject.getId());
members.setWithNotificationsSet(Constants.TRUE);
members.buildList(db);
for (TeamMember thisMember : members) {
User recipient = UserUtils.loadUser(thisMember.getUserId());
if (StringUtils.hasText(recipient.getEmail())) {
// Tailor the email to the recipient
bodyMappings.put("recipient", UserUtils.loadUser(thisMember.getUserId()));
// Parse and send
StringWriter inviteBodyTextWriter = new StringWriter();
template.process(bodyMappings, inviteBodyTextWriter);
mail.setBody(inviteBodyTextWriter.toString());
mail.setTo(recipient.getEmail());
mail.send();
}
}
}
context.getRequest().setAttribute("project", thisProject);
context.getRequest().setAttribute("IncludeSection", "news_email_ok");
context.getRequest().setAttribute("pid", projectId);
return "EmailTeamOK";
} catch (Exception errorMessage) {
context.getRequest().setAttribute("Error", errorMessage);
return ("SystemError");
} finally {
this.freeConnection(context, db);
}
}
public String executeCommandArchive(ActionContext context) {
Connection db = null;
//Parameters
String projectId = context.getRequest().getParameter("pid");
String newsId = context.getRequest().getParameter("id");
boolean recordUpdated = false;
try {
db = getConnection(context);
//Load the project
Project thisProject = retrieveAuthorizedProject(Integer.parseInt(projectId), context);
if (!hasProjectAccess(context, thisProject.getId(), "project-news-edit")) {
return "PermissionError";
}
context.getRequest().setAttribute("project", thisProject);
// Update the archive status of the article
BlogPost thisArticle = new BlogPost(db, Integer.parseInt(newsId), thisProject.getId());
context.getRequest().setAttribute("newsArticle", thisArticle);
thisArticle.setModifiedBy(getUserId(context));
recordUpdated = thisArticle.archive(db);
if (recordUpdated) {
indexAddItem(context, thisArticle);
} else {
processErrors(context, thisArticle.getErrors());
}
} catch (Exception errorMessage) {
context.getRequest().setAttribute("Error", errorMessage);
return ("SystemError");
} finally {
this.freeConnection(context, db);
}
if (recordUpdated) {
return ("ArchiveOK");
} else {
return ("ArchiveERROR");
}
}
public String executeCommandImg(ActionContext context) {
Connection db = null;
String pid = context.getRequest().getParameter("pid");
String filename = context.getRequest().getParameter("subject");
String thumbnailValue = context.getRequest().getParameter("th");
FileDownload fileDownload = null;
FileItem fileItem = null;
Thumbnail thumbnail = null;
try {
int projectId = Integer.parseInt(pid);
boolean showThumbnail = "true".equals(thumbnailValue);
fileDownload = new FileDownload();
db = getConnection(context);
// Check project permissions
Project thisProject = retrieveAuthorizedProject(projectId, context);
// Check access to this project
boolean allowed = false;
if (thisProject.getPortal() && thisProject.getApproved()) {
allowed = true;
} else if (hasProjectAccess(context, thisProject.getId(), "project-news-view")) {
allowed = true;
}
if (!allowed) {
return "PermissionError";
}
// Load the file for download
FileItemList fileItemList = new FileItemList();
fileItemList.setLinkModuleId(Constants.PROJECT_BLOG_FILES);
fileItemList.setLinkItemId(projectId);
fileItemList.setFilename(filename);
fileItemList.buildList(db);
if (fileItemList.size() > 0) {
fileItem = fileItemList.get(0);
if (showThumbnail) {
thumbnail = ThumbnailUtils.retrieveThumbnail(db, fileItem, 0, 0, this.getPath(context, "projects"));
String filePath = this.getPath(context, "projects") + getDatePath(fileItem.getModified()) + thumbnail.getFilename();
fileDownload.setFullPath(filePath);
fileDownload.setFileTimestamp(fileItem.getModificationDate().getTime());
} else {
String filePath = this.getPath(context, "projects") + getDatePath(fileItem.getModified()) + (showThumbnail ? fileItem.getThumbnailFilename() : fileItem.getFilename());
fileDownload.setFullPath(filePath);
fileDownload.setDisplayName(fileItem.getClientFilename());
}
}
} catch (Exception e) {
e.printStackTrace(System.out);
} finally {
freeConnection(context, db);
}
try {
// Stream the file
if (thumbnail != null) {
fileDownload.streamThumbnail(context, thumbnail);
} else if (fileItem != null && fileDownload.fileExists()) {
fileDownload.setFileTimestamp(fileItem.getModificationDate().getTime());
fileDownload.streamContent(context);
}
} catch (Exception e) {
e.printStackTrace(System.out);
}
return null;
}
public String executeCommandImageSelect(ActionContext context) {
Connection db = null;
//Parameters
String projectId = context.getRequest().getParameter("pid");
try {
db = getConnection(context);
//Load the project
Project thisProject = retrieveAuthorizedProject(Integer.parseInt(projectId), context);
if (!hasProjectAccess(context, thisProject.getId(), "project-news-view")) {
return "PermissionError";
}
context.getRequest().setAttribute("project", thisProject);
// Load the file for download
FileItemList imageList = new FileItemList();
imageList.setLinkModuleId(Constants.PROJECT_BLOG_FILES);
imageList.setLinkItemId(thisProject.getId());
imageList.buildList(db);
context.getRequest().setAttribute("imageList", imageList);
return ("ImageSelectOK");
} catch (Exception errorMessage) {
context.getRequest().setAttribute("Error", errorMessage);
return ("SystemError");
} finally {
this.freeConnection(context, db);
}
}
public String executeCommandUploadImage(ActionContext context) {
Connection db = null;
boolean recordInserted = false;
try {
String filePath = this.getPath(context, "projects");
//Process the form data
HttpMultiPartParser multiPart = new HttpMultiPartParser();
multiPart.setUsePathParam(false);
multiPart.setUseUniqueName(true);
multiPart.setUseDateForFolder(true);
multiPart.setExtensionId(getUserId(context));
HashMap parts = multiPart.parseData(context.getRequest(), filePath);
String projectId = (String) parts.get("pid");
String subject = (String) parts.get("subject");
db = getConnection(context);
// Project
Project thisProject = retrieveAuthorizedProject(Integer.parseInt(projectId), context);
if (!hasProjectAccess(context, thisProject.getId(), "project-news-edit")) {
//TODO: Should delete the uploads, then exit
return "PermissionError";
}
context.getRequest().setAttribute("project", thisProject);
// Update the database with the resulting file
if (parts.get("id" + projectId) instanceof FileInfo) {
FileInfo newFileInfo = (FileInfo) parts.get("id" + projectId);
FileItem thisItem = new FileItem();
thisItem.setLinkModuleId(Constants.PROJECT_BLOG_FILES);
thisItem.setLinkItemId(thisProject.getId());
thisItem.setEnteredBy(getUserId(context));
thisItem.setModifiedBy(getUserId(context));
thisItem.setSubject("Blog Image");
thisItem.setClientFilename(newFileInfo.getClientFileName());
thisItem.setFilename(newFileInfo.getRealFilename());
thisItem.setSize(newFileInfo.getSize());
// Verify the integrity of the image
thisItem.setImageSize(ImageUtils.getImageSize(newFileInfo.getLocalFile()));
if (thisItem.getImageWidth() == 0 || thisItem.getImageHeight() == 0) {
// A bad image was sent
return ("ImageUploadERROR");
}
// check to see if this filename already exists for automatic versioning
FileItemList fileItemList = new FileItemList();
fileItemList.setLinkModuleId(Constants.PROJECT_BLOG_FILES);
fileItemList.setLinkItemId(thisProject.getId());
fileItemList.setFilename(newFileInfo.getClientFileName());
fileItemList.buildList(db);
if (fileItemList.size() == 0) {
// this is a new document
thisItem.setVersion(1.0);
recordInserted = thisItem.insert(db);
} else {
// this is a new version of an existing document
FileItem previousItem = fileItemList.get(0);
thisItem.setId(previousItem.getId());
thisItem.setVersion(previousItem.getVersionNextMajor());
recordInserted = thisItem.insertVersion(db);
}
thisItem.setDirectory(filePath);
if (!recordInserted) {
processErrors(context, thisItem.getErrors());
} else {
- if (thisItem.isImageFormat()) {
+ if (thisItem.isImageFormat() && thisItem.hasValidImageSize()) {
// Create a thumbnail if this is an image
String format = thisItem.getExtension().substring(1);
File thumbnailFile = new File(newFileInfo.getLocalFile().getPath() + "TH");
Thumbnail thumbnail = new Thumbnail(ImageUtils.saveThumbnail(newFileInfo.getLocalFile(), thumbnailFile, 200d, 200d, format));
- // Store thumbnail in database
- thumbnail.setId(thisItem.getId());
- thumbnail.setFilename(newFileInfo.getRealFilename() + "TH");
- thumbnail.setVersion(thisItem.getVersion());
- thumbnail.setSize((int) thumbnailFile.length());
- thumbnail.setEnteredBy(thisItem.getEnteredBy());
- thumbnail.setModifiedBy(thisItem.getModifiedBy());
- recordInserted = thumbnail.insert(db);
+ if (thumbnail != null) {
+ // Store thumbnail in database
+ thumbnail.setId(thisItem.getId());
+ thumbnail.setFilename(newFileInfo.getRealFilename() + "TH");
+ thumbnail.setVersion(thisItem.getVersion());
+ thumbnail.setSize((int) thumbnailFile.length());
+ thumbnail.setEnteredBy(thisItem.getEnteredBy());
+ thumbnail.setModifiedBy(thisItem.getModifiedBy());
+ recordInserted = thumbnail.insert(db);
+ }
}
}
context.getRequest().setAttribute("popup", "true");
context.getRequest().setAttribute("PageLayout", "/layout1.jsp");
// Image List
FileItemList imageList = new FileItemList();
imageList.setLinkModuleId(Constants.PROJECT_BLOG_FILES);
imageList.setLinkItemId(thisProject.getId());
imageList.buildList(db);
context.getRequest().setAttribute("imageList", imageList);
// Send the image name so it can be auto-selected
context.getRequest().setAttribute("uploadedImage", newFileInfo.getClientFileName());
}
} catch (Exception e) {
context.getRequest().setAttribute("Error", e);
return ("SystemError");
} finally {
freeConnection(context, db);
}
return "UploadImageOK";
}
public String executeCommandVideoSelect(ActionContext context) {
Connection db = null;
//Parameters
String projectId = context.getRequest().getParameter("pid");
try {
db = getConnection(context);
// Load the project
Project thisProject = retrieveAuthorizedProject(Integer.parseInt(projectId), context);
if (!hasProjectAccess(context, thisProject.getId(), "project-news-view")) {
return "PermissionError";
}
context.getRequest().setAttribute("project", thisProject);
return ("VideoSelectOK");
} catch (Exception errorMessage) {
context.getRequest().setAttribute("Error", errorMessage);
return ("SystemError");
} finally {
this.freeConnection(context, db);
}
}
}
| false | true | public String executeCommandUploadImage(ActionContext context) {
Connection db = null;
boolean recordInserted = false;
try {
String filePath = this.getPath(context, "projects");
//Process the form data
HttpMultiPartParser multiPart = new HttpMultiPartParser();
multiPart.setUsePathParam(false);
multiPart.setUseUniqueName(true);
multiPart.setUseDateForFolder(true);
multiPart.setExtensionId(getUserId(context));
HashMap parts = multiPart.parseData(context.getRequest(), filePath);
String projectId = (String) parts.get("pid");
String subject = (String) parts.get("subject");
db = getConnection(context);
// Project
Project thisProject = retrieveAuthorizedProject(Integer.parseInt(projectId), context);
if (!hasProjectAccess(context, thisProject.getId(), "project-news-edit")) {
//TODO: Should delete the uploads, then exit
return "PermissionError";
}
context.getRequest().setAttribute("project", thisProject);
// Update the database with the resulting file
if (parts.get("id" + projectId) instanceof FileInfo) {
FileInfo newFileInfo = (FileInfo) parts.get("id" + projectId);
FileItem thisItem = new FileItem();
thisItem.setLinkModuleId(Constants.PROJECT_BLOG_FILES);
thisItem.setLinkItemId(thisProject.getId());
thisItem.setEnteredBy(getUserId(context));
thisItem.setModifiedBy(getUserId(context));
thisItem.setSubject("Blog Image");
thisItem.setClientFilename(newFileInfo.getClientFileName());
thisItem.setFilename(newFileInfo.getRealFilename());
thisItem.setSize(newFileInfo.getSize());
// Verify the integrity of the image
thisItem.setImageSize(ImageUtils.getImageSize(newFileInfo.getLocalFile()));
if (thisItem.getImageWidth() == 0 || thisItem.getImageHeight() == 0) {
// A bad image was sent
return ("ImageUploadERROR");
}
// check to see if this filename already exists for automatic versioning
FileItemList fileItemList = new FileItemList();
fileItemList.setLinkModuleId(Constants.PROJECT_BLOG_FILES);
fileItemList.setLinkItemId(thisProject.getId());
fileItemList.setFilename(newFileInfo.getClientFileName());
fileItemList.buildList(db);
if (fileItemList.size() == 0) {
// this is a new document
thisItem.setVersion(1.0);
recordInserted = thisItem.insert(db);
} else {
// this is a new version of an existing document
FileItem previousItem = fileItemList.get(0);
thisItem.setId(previousItem.getId());
thisItem.setVersion(previousItem.getVersionNextMajor());
recordInserted = thisItem.insertVersion(db);
}
thisItem.setDirectory(filePath);
if (!recordInserted) {
processErrors(context, thisItem.getErrors());
} else {
if (thisItem.isImageFormat()) {
// Create a thumbnail if this is an image
String format = thisItem.getExtension().substring(1);
File thumbnailFile = new File(newFileInfo.getLocalFile().getPath() + "TH");
Thumbnail thumbnail = new Thumbnail(ImageUtils.saveThumbnail(newFileInfo.getLocalFile(), thumbnailFile, 200d, 200d, format));
// Store thumbnail in database
thumbnail.setId(thisItem.getId());
thumbnail.setFilename(newFileInfo.getRealFilename() + "TH");
thumbnail.setVersion(thisItem.getVersion());
thumbnail.setSize((int) thumbnailFile.length());
thumbnail.setEnteredBy(thisItem.getEnteredBy());
thumbnail.setModifiedBy(thisItem.getModifiedBy());
recordInserted = thumbnail.insert(db);
}
}
context.getRequest().setAttribute("popup", "true");
context.getRequest().setAttribute("PageLayout", "/layout1.jsp");
// Image List
FileItemList imageList = new FileItemList();
imageList.setLinkModuleId(Constants.PROJECT_BLOG_FILES);
imageList.setLinkItemId(thisProject.getId());
imageList.buildList(db);
context.getRequest().setAttribute("imageList", imageList);
// Send the image name so it can be auto-selected
context.getRequest().setAttribute("uploadedImage", newFileInfo.getClientFileName());
}
} catch (Exception e) {
context.getRequest().setAttribute("Error", e);
return ("SystemError");
} finally {
freeConnection(context, db);
}
return "UploadImageOK";
}
| public String executeCommandUploadImage(ActionContext context) {
Connection db = null;
boolean recordInserted = false;
try {
String filePath = this.getPath(context, "projects");
//Process the form data
HttpMultiPartParser multiPart = new HttpMultiPartParser();
multiPart.setUsePathParam(false);
multiPart.setUseUniqueName(true);
multiPart.setUseDateForFolder(true);
multiPart.setExtensionId(getUserId(context));
HashMap parts = multiPart.parseData(context.getRequest(), filePath);
String projectId = (String) parts.get("pid");
String subject = (String) parts.get("subject");
db = getConnection(context);
// Project
Project thisProject = retrieveAuthorizedProject(Integer.parseInt(projectId), context);
if (!hasProjectAccess(context, thisProject.getId(), "project-news-edit")) {
//TODO: Should delete the uploads, then exit
return "PermissionError";
}
context.getRequest().setAttribute("project", thisProject);
// Update the database with the resulting file
if (parts.get("id" + projectId) instanceof FileInfo) {
FileInfo newFileInfo = (FileInfo) parts.get("id" + projectId);
FileItem thisItem = new FileItem();
thisItem.setLinkModuleId(Constants.PROJECT_BLOG_FILES);
thisItem.setLinkItemId(thisProject.getId());
thisItem.setEnteredBy(getUserId(context));
thisItem.setModifiedBy(getUserId(context));
thisItem.setSubject("Blog Image");
thisItem.setClientFilename(newFileInfo.getClientFileName());
thisItem.setFilename(newFileInfo.getRealFilename());
thisItem.setSize(newFileInfo.getSize());
// Verify the integrity of the image
thisItem.setImageSize(ImageUtils.getImageSize(newFileInfo.getLocalFile()));
if (thisItem.getImageWidth() == 0 || thisItem.getImageHeight() == 0) {
// A bad image was sent
return ("ImageUploadERROR");
}
// check to see if this filename already exists for automatic versioning
FileItemList fileItemList = new FileItemList();
fileItemList.setLinkModuleId(Constants.PROJECT_BLOG_FILES);
fileItemList.setLinkItemId(thisProject.getId());
fileItemList.setFilename(newFileInfo.getClientFileName());
fileItemList.buildList(db);
if (fileItemList.size() == 0) {
// this is a new document
thisItem.setVersion(1.0);
recordInserted = thisItem.insert(db);
} else {
// this is a new version of an existing document
FileItem previousItem = fileItemList.get(0);
thisItem.setId(previousItem.getId());
thisItem.setVersion(previousItem.getVersionNextMajor());
recordInserted = thisItem.insertVersion(db);
}
thisItem.setDirectory(filePath);
if (!recordInserted) {
processErrors(context, thisItem.getErrors());
} else {
if (thisItem.isImageFormat() && thisItem.hasValidImageSize()) {
// Create a thumbnail if this is an image
String format = thisItem.getExtension().substring(1);
File thumbnailFile = new File(newFileInfo.getLocalFile().getPath() + "TH");
Thumbnail thumbnail = new Thumbnail(ImageUtils.saveThumbnail(newFileInfo.getLocalFile(), thumbnailFile, 200d, 200d, format));
if (thumbnail != null) {
// Store thumbnail in database
thumbnail.setId(thisItem.getId());
thumbnail.setFilename(newFileInfo.getRealFilename() + "TH");
thumbnail.setVersion(thisItem.getVersion());
thumbnail.setSize((int) thumbnailFile.length());
thumbnail.setEnteredBy(thisItem.getEnteredBy());
thumbnail.setModifiedBy(thisItem.getModifiedBy());
recordInserted = thumbnail.insert(db);
}
}
}
context.getRequest().setAttribute("popup", "true");
context.getRequest().setAttribute("PageLayout", "/layout1.jsp");
// Image List
FileItemList imageList = new FileItemList();
imageList.setLinkModuleId(Constants.PROJECT_BLOG_FILES);
imageList.setLinkItemId(thisProject.getId());
imageList.buildList(db);
context.getRequest().setAttribute("imageList", imageList);
// Send the image name so it can be auto-selected
context.getRequest().setAttribute("uploadedImage", newFileInfo.getClientFileName());
}
} catch (Exception e) {
context.getRequest().setAttribute("Error", e);
return ("SystemError");
} finally {
freeConnection(context, db);
}
return "UploadImageOK";
}
|
diff --git a/common/mods/cc/rock/event/CookingCraftLivingDropsEvent.java b/common/mods/cc/rock/event/CookingCraftLivingDropsEvent.java
index dca381e..41dd138 100644
--- a/common/mods/cc/rock/event/CookingCraftLivingDropsEvent.java
+++ b/common/mods/cc/rock/event/CookingCraftLivingDropsEvent.java
@@ -1,22 +1,22 @@
package mods.cc.rock.event;
import mods.cc.rock.core.helpers.ItemHelper;
import mods.cc.rock.lib.ItemIDs;
import net.minecraft.entity.monster.EntityZombie;
import net.minecraftforge.event.ForgeSubscribe;
import net.minecraftforge.event.entity.living.LivingDropsEvent;
public class CookingCraftLivingDropsEvent
{
@ForgeSubscribe
public void onEntityDrop(LivingDropsEvent event)
{
- if(event.entityLiving instanceof EntityZombie)
+ if(event.entityLiving instanceof EntityZombie && event.source.getDamageType().equals("player"))
{
- ItemHelper.dropItem(event.entityLiving, ItemIDs.ID_HAMMER, 40);
+ ItemHelper.dropItem(event.entityLiving, ItemIDs.ID_HAMMER, 50);
}
}
}
| false | true | public void onEntityDrop(LivingDropsEvent event)
{
if(event.entityLiving instanceof EntityZombie)
{
ItemHelper.dropItem(event.entityLiving, ItemIDs.ID_HAMMER, 40);
}
}
| public void onEntityDrop(LivingDropsEvent event)
{
if(event.entityLiving instanceof EntityZombie && event.source.getDamageType().equals("player"))
{
ItemHelper.dropItem(event.entityLiving, ItemIDs.ID_HAMMER, 50);
}
}
|
diff --git a/src/net/sf/freecol/server/model/ServerPlayer.java b/src/net/sf/freecol/server/model/ServerPlayer.java
index 26ee2fb2a..170985f67 100644
--- a/src/net/sf/freecol/server/model/ServerPlayer.java
+++ b/src/net/sf/freecol/server/model/ServerPlayer.java
@@ -1,3028 +1,3029 @@
/**
* Copyright (C) 2002-2011 The FreeCol Team
*
* This file is part of FreeCol.
*
* FreeCol 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.
*
* FreeCol 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 FreeCol. If not, see <http://www.gnu.org/licenses/>.
*/
package net.sf.freecol.server.model;
import java.net.Socket;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.EnumMap;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map.Entry;
import java.util.Random;
import java.util.Set;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamReader;
import javax.xml.stream.XMLStreamWriter;
import net.sf.freecol.common.model.Ability;
import net.sf.freecol.common.model.AbstractGoods;
import net.sf.freecol.common.model.AbstractUnit;
import net.sf.freecol.common.model.Building;
import net.sf.freecol.common.model.BuildingType;
import net.sf.freecol.common.model.Colony;
import net.sf.freecol.common.model.CombatModel;
import net.sf.freecol.common.model.CombatModel.CombatResult;
import net.sf.freecol.common.model.EquipmentType;
import net.sf.freecol.common.model.Europe;
import net.sf.freecol.common.model.Europe.MigrationType;
import net.sf.freecol.common.model.Event;
import net.sf.freecol.common.model.FeatureContainer;
import net.sf.freecol.common.model.FoundingFather;
import net.sf.freecol.common.model.FoundingFather.FoundingFatherType;
import net.sf.freecol.common.model.FreeColGameObject;
import net.sf.freecol.common.model.Game;
import net.sf.freecol.common.model.GameOptions;
import net.sf.freecol.common.model.Goods;
import net.sf.freecol.common.model.GoodsContainer;
import net.sf.freecol.common.model.GoodsType;
import net.sf.freecol.common.model.HistoryEvent;
import net.sf.freecol.common.model.IndianSettlement;
import net.sf.freecol.common.model.Location;
import net.sf.freecol.common.model.Map;
import net.sf.freecol.common.model.Market;
import net.sf.freecol.common.model.ModelMessage;
import net.sf.freecol.common.model.Modifier;
import net.sf.freecol.common.model.Monarch;
import net.sf.freecol.common.model.Monarch.MonarchAction;
import net.sf.freecol.common.model.Nation;
import net.sf.freecol.common.model.Player;
import net.sf.freecol.common.model.RandomRange;
import net.sf.freecol.common.model.Settlement;
import net.sf.freecol.common.model.SettlementType;
import net.sf.freecol.common.model.Specification;
import net.sf.freecol.common.model.StringTemplate;
import net.sf.freecol.common.model.Tension;
import net.sf.freecol.common.model.Tile;
import net.sf.freecol.common.model.Unit;
import net.sf.freecol.common.model.Unit.UnitState;
import net.sf.freecol.common.model.UnitType;
import net.sf.freecol.common.model.UnitTypeChange.ChangeType;
import net.sf.freecol.common.networking.Connection;
import net.sf.freecol.common.option.BooleanOption;
import net.sf.freecol.common.util.RandomChoice;
import net.sf.freecol.common.util.Utils;
import net.sf.freecol.server.control.ChangeSet;
import net.sf.freecol.server.control.ChangeSet.ChangePriority;
import net.sf.freecol.server.control.ChangeSet.See;
import net.sf.freecol.server.model.ServerColony;
import net.sf.freecol.server.model.ServerEurope;
import net.sf.freecol.server.model.ServerIndianSettlement;
import net.sf.freecol.server.model.ServerModelObject;
import net.sf.freecol.server.model.ServerUnit;
import net.sf.freecol.server.model.TransactionSession;
/**
* A <code>Player</code> with additional (server specific) information.
*
* That is: pointers to this player's
* {@link Connection} and {@link Socket}
*/
public class ServerPlayer extends Player implements ServerModelObject {
private static final Logger logger = Logger.getLogger(ServerPlayer.class.getName());
// TODO: move to options or spec?
public static final int ALARM_RADIUS = 2;
public static final int ALARM_TILE_IN_USE = 2;
public static final int ALARM_MISSIONARY_PRESENT = -10;
// How far to search for a colony to add an Indian convert to.
public static final int MAX_CONVERT_DISTANCE = 10;
/** The network socket to the player's client. */
private Socket socket;
/** The connection for this player. */
private Connection connection;
private boolean connected = false;
/** Remaining emigrants to select due to a fountain of youth */
private int remainingEmigrants = 0;
/**
* Trivial constructor required for all ServerModelObjects.
*/
public ServerPlayer(Game game, String id) {
super(game, id);
}
/**
* Creates a new ServerPlayer.
*
* @param game The <code>Game</code> this object belongs to.
* @param name The player name.
* @param admin Whether the player is the game administrator or not.
* @param nation The nation of the <code>Player</code>.
* @param socket The socket to the player's client.
* @param connection The <code>Connection</code> for the socket.
*/
public ServerPlayer(Game game, String name, boolean admin, Nation nation,
Socket socket, Connection connection) {
super(game);
this.name = name;
this.admin = admin;
featureContainer = new FeatureContainer(game.getSpecification());
europe = null;
if (nation != null && nation.getType() != null) {
this.nationType = nation.getType();
this.nationID = nation.getId();
try {
featureContainer.add(nationType.getFeatureContainer());
} catch (Throwable error) {
error.printStackTrace();
}
if (nationType.isEuropean()) {
/*
* Setting the amount of gold to
* "getGameOptions().getInteger(GameOptions.STARTING_MONEY)"
*
* just before starting the game. See
* "net.sf.freecol.server.control.PreGameController".
*/
gold = 0;
europe = new ServerEurope(game, this);
playerType = (nationType.isREF()) ? PlayerType.ROYAL
: PlayerType.COLONIAL;
if (playerType == PlayerType.COLONIAL) {
monarch = new Monarch(game, this, nation.getRulerNameKey());
}
} else { // indians
gold = 1500;
playerType = PlayerType.NATIVE;
}
} else {
// virtual "enemy privateer" player
// or undead ?
this.nationID = Nation.UNKNOWN_NATION_ID;
this.playerType = PlayerType.COLONIAL;
}
market = new Market(getGame(), this);
immigration = 0;
liberty = 0;
currentFather = null;
//call of super() will lead to this object being registered with AIMain
//before playerType has been set. AIMain will fall back to use of
//standard AIPlayer in this case. Set object again to fix this.
//Possible TODO: Is there a better way to do this?
final String curId = getId();
game.removeFreeColGameObject(curId);
game.setFreeColGameObject(curId, this);
this.socket = socket;
this.connection = connection;
connected = connection != null;
resetExploredTiles(getGame().getMap());
invalidateCanSeeTiles();
}
/**
* Checks if this player is currently connected to the server.
* @return <i>true</i> if this player is currently connected to the server
* and <code>false</code> otherwise.
*/
public boolean isConnected() {
return connected;
}
/**
* Sets the "connected"-status of this player.
*
* @param connected Should be <i>true</i> if this player is currently
* connected to the server and <code>false</code> otherwise.
* @see #isConnected
*/
public void setConnected(boolean connected) {
this.connected = connected;
}
/**
* Gets the socket of this player.
* @return The <code>Socket</code>.
*/
public Socket getSocket() {
return socket;
}
/**
* Gets the connection of this player.
*
* @return The <code>Connection</code>.
*/
public Connection getConnection() {
return connection;
}
/**
* Sets the connection of this player.
*
* @param connection The <code>Connection</code>.
*/
public void setConnection(Connection connection) {
this.connection = connection;
connected = (connection != null);
}
/**
* Checks if this player has died.
*
* @return True if this player should die.
*/
public boolean checkForDeath() {
/*
* Die if: (isNative && (no colonies or units))
* || ((rebel or independent) && !(has coastal colony))
* || (isREF && !(rebel nation left) && (all units in Europe))
* || ((no units in New World)
* && ((year > 1600) || (cannot get a unit from Europe)))
*/
switch (getPlayerType()) {
case NATIVE: // All natives units are viable
return getUnits().isEmpty();
case COLONIAL: // Handle the hard case below
if (isUnknownEnemy()) return false;
break;
case REBEL: case INDEPENDENT:
// Post-declaration European player needs a coastal colony
// and can not hope for resupply from Europe.
for (Colony colony : getColonies()) {
if (colony.isConnected()) return false;
}
return true;
case ROYAL: // Still alive if there are rebels to quell
for (Player enemy : getGame().getPlayers()) {
if (enemy.getREFPlayer() == (Player) this
&& enemy.getPlayerType() == PlayerType.REBEL) {
return false;
}
}
// Still alive if there are units not in Europe
for (Unit u : getUnits()) {
if (!u.isInEurope()) return false;
}
// Otherwise, the REF has been defeated and gone home.
return true;
case UNDEAD:
return getUnits().isEmpty();
default:
throw new IllegalStateException("Bogus player type");
}
// Quick check for a colony
if (!getColonies().isEmpty()) {
return false;
}
// Verify player units
boolean hasCarrier = false;
List<Unit> unitList = getUnits();
for(Unit unit : unitList){
boolean isValidUnit = false;
if(unit.isCarrier()){
hasCarrier = true;
continue;
}
// Can found new colony
if(unit.isColonist()){
isValidUnit = true;
}
// Can capture units
if(unit.isOffensiveUnit()){
isValidUnit = true;
}
if(!isValidUnit){
continue;
}
// Verify if unit is in new world
Location unitLocation = unit.getLocation();
// unit in new world
if(unitLocation instanceof Tile){
logger.info(getName() + " found colonist in new world");
return false;
}
// onboard a carrier
if(unit.isOnCarrier()){
Unit carrier = (Unit) unitLocation;
// carrier in new world
if(carrier.getLocation() instanceof Tile){
logger.info(getName() + " found colonist aboard carrier in new world");
return false;
}
}
}
/*
* At this point we know the player does not have any valid units or
* settlements on the map.
*/
// After the year 1600, no presence in New World means endgame
if (getGame().getTurn().getYear() >= 1600) {
logger.info(getName() + " no presence in new world after 1600");
return true;
}
int goldNeeded = 0;
/*
* No carrier, check if has gold to buy one
*/
if(!hasCarrier){
/*
* Find the cheapest naval unit
*/
Iterator<UnitType> navalUnits = getSpecification()
.getUnitTypesWithAbility("model.ability.navalUnit").iterator();
int lowerPrice = Integer.MAX_VALUE;
while(navalUnits.hasNext()){
UnitType unit = navalUnits.next();
int unitPrice = getEurope().getUnitPrice(unit);
// cannot be bought
if(unitPrice == UnitType.UNDEFINED){
continue;
}
if(unitPrice < lowerPrice){
lowerPrice = unitPrice;
}
}
//Sanitation
if(lowerPrice == Integer.MAX_VALUE){
logger.warning(getName() + " could not find naval unit to buy");
return true;
}
goldNeeded += lowerPrice;
// cannot buy carrier
if(goldNeeded > getGold()){
logger.info(getName() + " does not have enough money to buy carrier");
return true;
}
logger.info(getName() + " has enough money to buy carrier, has=" + getGold() + ", needs=" + lowerPrice);
}
/*
* Check if player has colonists.
* We already checked that it has (or can buy) a carrier to
* transport them to New World
*/
for (Unit eu : getEurope().getUnitList()) {
if (eu.isCarrier()) {
/*
* The carrier has colonist units on board
*/
for (Unit u : eu.getUnitList()) {
if (u.isColonist()) return false;
}
// The carrier has units or goods that can be sold.
if (eu.getGoodsCount() > 0) {
logger.info(getName() + " has goods to sell");
return false;
}
continue;
}
if (eu.isColonist()) {
logger.info(getName() + " has colonist unit waiting in port");
return false;
}
}
// No colonists, check if has gold to train or recruit one.
int goldToRecruit = getEurope().getRecruitPrice();
/*
* Find the cheapest colonist, either by recruiting or training
*/
Iterator<UnitType> trainedUnits = getSpecification().getUnitTypesTrainedInEurope().iterator();
int goldToTrain = Integer.MAX_VALUE;
while(trainedUnits.hasNext()){
UnitType unit = trainedUnits.next();
if(!unit.hasAbility("model.ability.foundColony")){
continue;
}
int unitPrice = getEurope().getUnitPrice(unit);
// cannot be bought
if(unitPrice == UnitType.UNDEFINED){
continue;
}
if(unitPrice < goldToTrain){
goldToTrain = unitPrice;
}
}
goldNeeded += Math.min(goldToTrain, goldToRecruit);
if (goldNeeded <= getGold()) return false;
// Does not have enough money for recruiting or training
logger.info(getName() + " does not have enough money for recruiting or training");
return true;
}
/**
* Marks a player dead and remove any leftovers.
*
* @param cs A <code>ChangeSet</code> to update.
*/
public ChangeSet csKill(ChangeSet cs) {
// Mark the player as dead.
setDead(true);
cs.addDead(this);
// Notify everyone.
cs.addMessage(See.all().except(this),
new ModelMessage(ModelMessage.MessageType.FOREIGN_DIPLOMACY,
((isEuropean())
? "model.diplomacy.dead.european"
: "model.diplomacy.dead.native"),
this)
.addStringTemplate("%nation%", getNationName()));
// Clean up missions
if (isEuropean()) {
for (Player other : getGame().getPlayers()) {
for (IndianSettlement s : other.getIndianSettlementsWithMission(this)) {
Unit unit = s.getMissionary();
s.changeMissionary(null);
cs.addDispose(this, s.getTile(), unit);
cs.add(See.perhaps(), s.getTile());
}
}
}
// Remove settlements. Update formerly owned tiles.
List<Settlement> settlements = getSettlements();
while (!settlements.isEmpty()) {
Settlement settlement = settlements.remove(0);
cs.addDispose(this, settlement.getTile(), settlement);
}
// Clean up remaining tile ownerships
for (Tile tile : getGame().getMap().getAllTiles()) {
if (tile.getOwner() == this) tile.changeOwnership(null, null);
}
// Remove units
List<Unit> units = getUnits();
while (!units.isEmpty()) {
Unit unit = units.remove(0);
if (unit.getLocation() instanceof Tile) {
cs.add(See.perhaps(), unit.getTile());
}
cs.addDispose(this, unit.getLocation(), unit);
}
return cs;
}
public int getRemainingEmigrants() {
return remainingEmigrants;
}
public void setRemainingEmigrants(int emigrants) {
remainingEmigrants = emigrants;
}
/**
* Checks whether the current founding father has been recruited.
*
* @return The new founding father, or null if none available or ready.
*/
public FoundingFather checkFoundingFather() {
FoundingFather father = null;
if (currentFather != null) {
int extraLiberty = getRemainingFoundingFatherCost();
if (extraLiberty <= 0) {
boolean overflow = getSpecification()
.getBoolean(GameOptions.SAVE_PRODUCTION_OVERFLOW);
setLiberty((overflow) ? -extraLiberty : 0);
father = currentFather;
currentFather = null;
}
}
return father;
}
/**
* Checks whether to start recruiting a founding father.
*
* @return True if a new father should be chosen.
*/
public boolean canRecruitFoundingFather() {
return getPlayerType() == PlayerType.COLONIAL
&& canHaveFoundingFathers()
&& currentFather == null
&& !getSettlements().isEmpty();
}
/**
* Build a list of random FoundingFathers, one per type.
* Do not include any the player has or are not available.
*
* @param random A pseudo-random number source.
* @return A list of FoundingFathers.
*/
public List<FoundingFather> getRandomFoundingFathers(Random random) {
// Build weighted random choice for each father type
Specification spec = getGame().getSpecification();
int age = getGame().getTurn().getAge();
EnumMap<FoundingFatherType, List<RandomChoice<FoundingFather>>> choices
= new EnumMap<FoundingFatherType,
List<RandomChoice<FoundingFather>>>(FoundingFatherType.class);
for (FoundingFather father : spec.getFoundingFathers()) {
if (!hasFather(father) && father.isAvailableTo(this)) {
FoundingFatherType type = father.getType();
List<RandomChoice<FoundingFather>> rc = choices.get(type);
if (rc == null) {
rc = new ArrayList<RandomChoice<FoundingFather>>();
}
int weight = father.getWeight(age);
rc.add(new RandomChoice<FoundingFather>(father, weight));
choices.put(father.getType(), rc);
}
}
// Select one from each father type
List<FoundingFather> randomFathers = new ArrayList<FoundingFather>();
String logMessage = "Random fathers";
for (FoundingFatherType type : FoundingFatherType.values()) {
List<RandomChoice<FoundingFather>> rc = choices.get(type);
if (rc != null) {
FoundingFather f = RandomChoice.getWeightedRandom(logger,
"Choose founding father", random, rc);
randomFathers.add(f);
logMessage += ":" + f.getNameKey();
}
}
logger.info(logMessage);
return randomFathers;
}
/**
* Generate a weighted list of unit types recruitable by this player.
*
* @return A weighted list of recruitable unit types.
*/
public List<RandomChoice<UnitType>> generateRecruitablesList() {
ArrayList<RandomChoice<UnitType>> recruitables
= new ArrayList<RandomChoice<UnitType>>();
FeatureContainer fc = getFeatureContainer();
for (UnitType unitType : getSpecification().getUnitTypeList()) {
if (unitType.isRecruitable()
&& fc.hasAbility("model.ability.canRecruitUnit", unitType)) {
recruitables.add(new RandomChoice<UnitType>(unitType,
unitType.getRecruitProbability()));
}
}
return recruitables;
}
/**
* Add a HistoryEvent to this player.
*
* @param event The <code>HistoryEvent</code> to add.
*/
public void addHistory(HistoryEvent event) {
history.add(event);
}
/**
* Resets this player's explored tiles. This is done by setting
* all the tiles within a {@link Unit}s line of sight visible.
* The other tiles are made unvisible.
*
* @param map The <code>Map</code> to reset the explored tiles on.
* @see #hasExplored
*/
public void resetExploredTiles(Map map) {
if (map != null) {
for (Unit unit : getUnits()) {
Tile tile = unit.getTile();
setExplored(tile);
int radius = (unit.getColony() != null)
? unit.getColony().getLineOfSight()
: unit.getLineOfSight();
for (Tile t : tile.getSurroundingTiles(radius)) {
setExplored(t);
}
}
}
}
/**
* Checks if this <code>Player</code> has explored the given
* <code>Tile</code>.
*
* @param tile The <code>Tile</code>.
* @return <i>true</i> if the <code>Tile</code> has been explored and
* <i>false</i> otherwise.
*/
public boolean hasExplored(Tile tile) {
return tile.isExploredBy(this);
}
/**
* Sets the given tile to be explored by this player and updates
* the player's information about the tile.
*/
public void setExplored(Tile tile) {
tile.setExploredBy(this, true);
}
/**
* Sets the tiles within the given <code>Unit</code>'s line of
* sight to be explored by this player.
*
* @param unit The <code>Unit</code>.
* @see #setExplored(Tile)
* @see #hasExplored
*/
public void setExplored(Unit unit) {
if (getGame() == null || getGame().getMap() == null || unit == null
|| unit.getLocation() == null || unit.getTile() == null) {
return;
}
Tile tile = unit.getTile();
setExplored(tile);
for (Tile t : tile.getSurroundingTiles(unit.getLineOfSight())) {
setExplored(t);
}
invalidateCanSeeTiles();
}
/**
* Create units from a list of abstract units. Only used by
* Europeans at present, so the units are created in Europe.
*
* @param abstractUnits The list of <code>AbstractUnit</code>s to create.
* @return A list of units created.
*/
public List<Unit> createUnits(List<AbstractUnit> abstractUnits) {
Game game = getGame();
Specification spec = game.getSpecification();
List<Unit> units = new ArrayList<Unit>();
Europe europe = getEurope();
if (europe == null) return units;
for (AbstractUnit au : abstractUnits) {
for (int i = 0; i < au.getNumber(); i++) {
units.add(new ServerUnit(game, europe, this,
au.getUnitType(spec),
UnitState.ACTIVE,
au.getEquipment(spec)));
}
}
return units;
}
/**
* Makes the entire map visible.
* Debug mode helper.
*/
public void revealMap() {
for (Tile tile: getGame().getMap().getAllTiles()) {
setExplored(tile);
}
getSpecification().getBooleanOption(GameOptions.FOG_OF_WAR)
.setValue(false);
invalidateCanSeeTiles();
}
/**
* Propagate an European market change to the other European markets.
*
* @param type The type of goods that was traded.
* @param amount The amount of goods that was traded.
* @param random A <code>Random</code> number source.
*/
private void propagateToEuropeanMarkets(GoodsType type, int amount,
Random random) {
if (!type.isStorable()) return;
// Propagate 5-30% of the original change.
final int lowerBound = 5; // TODO: make into game option?
final int upperBound = 30;// TODO: make into game option?
amount *= Utils.randomInt(logger, "Propagate goods", random,
upperBound - lowerBound + 1) + lowerBound;
amount /= 100;
if (amount == 0) return;
// Do not need to update the clients here, these changes happen
// while it is not their turn.
for (Player other : getGame().getEuropeanPlayers()) {
Market market;
if ((ServerPlayer) other != this
&& (market = other.getMarket()) != null) {
market.addGoodsToMarket(type, amount);
}
}
}
/**
* Flush any market price changes for a specified goods type.
*
* @param type The <code>GoodsType</code> to check.
* @param cs A <code>ChangeSet</code> to update.
*/
public void csFlushMarket(GoodsType type, ChangeSet cs) {
Market market = getMarket();
if (market.hasPriceChanged(type)) {
// This type of goods has changed price, so we will update
// the market and send a message as well.
cs.addMessage(See.only(this),
market.makePriceChangeMessage(type));
market.flushPriceChange(type);
cs.add(See.only(this), market.getMarketData(type));
}
}
/**
* Buy goods in Europe.
*
* @param container The <code>GoodsContainer</code> to carry the goods.
* @param type The <code>GoodsType</code> to buy.
* @param amount The amount of goods to buy.
* @param random A <code>Random</code> number source.
* @throws IllegalStateException If the <code>player</code> cannot afford
* to buy the goods.
*/
public void buy(GoodsContainer container, GoodsType type, int amount,
Random random)
throws IllegalStateException {
logger.finest(getName() + " buys " + amount + " " + type);
Market market = getMarket();
int price = market.getBidPrice(type, amount);
if (price > getGold()) {
throw new IllegalStateException("Player " + getName()
+ " tried to buy " + Integer.toString(amount)
+ " " + type.toString()
+ " for " + Integer.toString(price)
+ " but has " + Integer.toString(getGold()) + " gold.");
}
modifyGold(-price);
market.modifySales(type, -amount);
market.modifyIncomeBeforeTaxes(type, -price);
market.modifyIncomeAfterTaxes(type, -price);
int marketAmount = -(int) getFeatureContainer()
.applyModifier(amount, "model.modifier.tradeBonus",
type, getGame().getTurn());
market.addGoodsToMarket(type, marketAmount);
propagateToEuropeanMarkets(type, marketAmount, random);
container.addGoods(type, amount);
}
/**
* Sell goods in Europe.
*
* @param container An optional <code>GoodsContainer</code>
* carrying the goods.
* @param type The <code>GoodsType</code> to sell.
* @param amount The amount of goods to sell.
* @param random A <code>Random</code> number source.
*/
public void sell(GoodsContainer container, GoodsType type, int amount,
Random random) {
logger.finest(getName() + " sells " + amount + " " + type);
Market market = getMarket();
int tax = getTax();
int incomeBeforeTaxes = market.getSalePrice(type, amount);
int incomeAfterTaxes = ((100 - tax) * incomeBeforeTaxes) / 100;
modifyGold(incomeAfterTaxes);
market.modifySales(type, amount);
market.modifyIncomeBeforeTaxes(type, incomeBeforeTaxes);
market.modifyIncomeAfterTaxes(type, incomeAfterTaxes);
int marketAmount = (int) getFeatureContainer()
.applyModifier(amount, "model.modifier.tradeBonus",
type, getGame().getTurn());
market.addGoodsToMarket(type, marketAmount);
propagateToEuropeanMarkets(type, marketAmount, random);
if (container != null) container.addGoods(type, -amount);
}
/**
* Change stance and collect changes that need updating.
*
* @param stance The new <code>Stance</code>.
* @param otherPlayer The <code>Player</code> wrt which the stance changes.
* @param symmetric If true, change the otherPlayer stance as well.
* @param cs A <code>ChangeSet</code> containing the changes.
* @return True if there was a change in stance at all.
*/
public boolean csChangeStance(Stance stance, Player otherPlayer,
boolean symmetric, ChangeSet cs) {
boolean change = false;
Stance old = getStance(otherPlayer);
if (old != stance) {
try {
int modifier = old.getTensionModifier(stance);
setStance(otherPlayer, stance);
if (modifier != 0) {
cs.add(See.only(null).perhaps((ServerPlayer) otherPlayer),
modifyTension(otherPlayer, modifier));
}
cs.addStance(See.perhaps(), this, stance, otherPlayer);
change = true;
logger.finest("Stance change " + getName()
+ " " + old.toString()
+ " -> " + stance.toString()
+ " wrt " + otherPlayer.getName());
} catch (IllegalStateException e) { // Catch illegal transitions
logger.log(Level.WARNING, "Illegal stance transition", e);
}
}
if (symmetric && (old = otherPlayer.getStance(this)) != stance) {
try {
int modifier = old.getTensionModifier(stance);
otherPlayer.setStance(this, stance);
if (modifier != 0) {
cs.add(See.only(null).perhaps(this),
otherPlayer.modifyTension(this, modifier));
}
cs.addStance(See.perhaps(), otherPlayer, stance, this);
change = true;
logger.finest("Stance change " + otherPlayer.getName()
+ " " + old.toString()
+ " -> " + stance.toString()
+ " wrt " + getName());
} catch (IllegalStateException e) { // Catch illegal transitions
logger.log(Level.WARNING, "Illegal stance transition", e);
}
}
return change;
}
/**
* New turn for this player.
*
* @param random A <code>Random</code> number source.
* @param cs A <code>ChangeSet</code> to update.
*/
public void csNewTurn(Random random, ChangeSet cs) {
logger.finest("ServerPlayer.csNewTurn, for " + toString());
// Settlements
List<Settlement> settlements
= new ArrayList<Settlement>(getSettlements());
int newSoL = 0;
for (Settlement settlement : settlements) {
((ServerModelObject) settlement).csNewTurn(random, cs);
newSoL += settlement.getSoL();
}
int numberOfColonies = settlements.size();
if (numberOfColonies > 0) {
newSoL = newSoL / numberOfColonies;
if (oldSoL / 10 != newSoL / 10) {
cs.addMessage(See.only(this),
new ModelMessage(ModelMessage.MessageType.SONS_OF_LIBERTY,
(newSoL > oldSoL)
? "model.player.SoLIncrease"
: "model.player.SoLDecrease", this)
.addAmount("%oldSoL%", oldSoL)
.addAmount("%newSoL%", newSoL));
}
oldSoL = newSoL; // Remember SoL for check changes at next turn.
}
// Europe.
if (europe != null) {
((ServerModelObject) europe).csNewTurn(random, cs);
}
// Units.
for (Unit unit : new ArrayList<Unit>(getUnits())) {
try {
((ServerModelObject) unit).csNewTurn(random, cs);
} catch (ClassCastException e) {
logger.log(Level.SEVERE, "Not a ServerUnit: " + unit.getId(), e);
}
}
if (isEuropean()) { // Update liberty and immigration
if (checkEmigrate()
&& !hasAbility("model.ability.selectRecruit")) {
// Auto-emigrate if selection not allowed.
csEmigrate(0, MigrationType.NORMAL, random, cs);
} else {
cs.addPartial(See.only(this), this, "immigration");
}
cs.addPartial(See.only(this), this, "liberty");
}
}
/**
* Starts a new turn for a player.
* Carefully do any random number generation outside of any
* threads that start so as to keep random number generation
* deterministic.
*
* @param random A pseudo-random number source.
* @param cs A <code>ChangeSet</code> to update.
*/
public void csStartTurn(Random random, ChangeSet cs) {
Game game = getGame();
if (isEuropean()) {
csBombardEnemyShips(random, cs);
csYearlyGoodsRemoval(random, cs);
FoundingFather father = checkFoundingFather();
if (father != null) {
csAddFoundingFather(father, random, cs);
}
} else if (isIndian()) {
// We do not have to worry about Player level stance
// changes driving Stance, as that is delegated to the AI.
//
// However we want to notify of individual settlements
// that change tension level, but there are complex
// interactions between settlement and player tensions.
// The simple way to do it is just to save all old tension
// levels and check if they have changed after applying
// all the changes.
List<IndianSettlement> allSettlements = getIndianSettlements();
java.util.Map<IndianSettlement,
java.util.Map<Player, Tension.Level>> oldLevels
= new HashMap<IndianSettlement,
java.util.Map<Player, Tension.Level>>();
for (IndianSettlement settlement : allSettlements) {
java.util.Map<Player, Tension.Level> oldLevel
= new HashMap<Player, Tension.Level>();
oldLevels.put(settlement, oldLevel);
for (Player enemy : game.getEuropeanPlayers()) {
Tension alarm = settlement.getAlarm(enemy);
if (alarm != null) oldLevel.put(enemy, alarm.getLevel());
}
}
// Do the settlement alarms first.
for (IndianSettlement settlement : allSettlements) {
java.util.Map<Player, Integer> extra
= new HashMap<Player, Integer>();
for (Player enemy : game.getEuropeanPlayers()) {
extra.put(enemy, new Integer(0));
}
// Look at the uses of tiles surrounding the settlement.
int alarmRadius = settlement.getRadius() + ALARM_RADIUS;
int alarm = 0;
for (Tile tile: settlement.getTile()
.getSurroundingTiles(alarmRadius)) {
Colony colony = tile.getColony();
if (tile.getFirstUnit() != null) { // Military units
Player enemy = tile.getFirstUnit().getOwner();
if (enemy.isEuropean()) {
alarm = extra.get(enemy);
for (Unit unit : tile.getUnitList()) {
if (unit.isOffensiveUnit() && !unit.isNaval()) {
alarm += unit.getType().getOffence();
}
}
extra.put(enemy, alarm);
}
} else if (colony != null) { // Colonies
Player enemy = colony.getOwner();
extra.put(enemy, extra.get(enemy).intValue()
+ ALARM_TILE_IN_USE
+ colony.getUnitCount());
} else if (tile.getOwningSettlement() != null) { // Control
Player enemy = tile.getOwningSettlement().getOwner();
if (enemy != null && enemy.isEuropean()) {
extra.put(enemy, extra.get(enemy).intValue()
+ ALARM_TILE_IN_USE);
}
}
}
// Missionary helps reducing alarm a bit
if (settlement.getMissionary() != null) {
Unit mission = settlement.getMissionary();
int missionAlarm = ALARM_MISSIONARY_PRESENT;
if (mission.hasAbility("model.ability.expertMissionary")) {
missionAlarm *= 2;
}
Player enemy = mission.getOwner();
extra.put(enemy,
extra.get(enemy).intValue() + missionAlarm);
}
// Apply modifiers, and commit the total change.
for (Entry<Player, Integer> entry : extra.entrySet()) {
Player player = entry.getKey();
int change = entry.getValue().intValue();
if (change != 0) {
change = (int) player.getFeatureContainer()
.applyModifier(change,
"model.modifier.nativeAlarmModifier",
null, game.getTurn());
settlement.modifyAlarm(player, change);
}
}
}
// Calm down a bit at the whole-tribe level.
for (Player enemy : game.getEuropeanPlayers()) {
if (getTension(enemy).getValue() > 0) {
int change = -getTension(enemy).getValue()/100 - 4;
modifyTension(enemy, change);
}
}
// Now collect the settlements that changed.
for (IndianSettlement settlement : allSettlements) {
java.util.Map<Player, Tension.Level> oldLevel
= oldLevels.get(settlement);
for (Entry<Player, Tension.Level> entry : oldLevel.entrySet()) {
Player enemy = entry.getKey();
Tension.Level newLevel
= settlement.getAlarm(enemy).getLevel();
if (entry.getValue() != newLevel) {
cs.add(See.only(null).perhaps((ServerPlayer) enemy),
settlement);
}
}
}
// Check for braves converted by missionaries
List<UnitType> converts = game.getSpecification()
.getUnitTypesWithAbility("model.ability.convert");
StringTemplate nation = getNationName();
for (IndianSettlement settlement : allSettlements) {
if (settlement.checkForNewMissionaryConvert()) {
Unit missionary = settlement.getMissionary();
ServerPlayer other = (ServerPlayer) missionary.getOwner();
Settlement colony = settlement.getTile()
.getNearestSettlement(other, MAX_CONVERT_DISTANCE);
if (colony != null && converts.size() > 0) {
Unit brave = settlement.getFirstUnit();
brave.setOwner(other);
brave.setType(Utils.getRandomMember(logger,
"Choose brave", converts, random));
brave.setLocation(colony.getTile());
cs.add(See.perhaps(), colony.getTile(), settlement);
cs.addMessage(See.only(other),
new ModelMessage(ModelMessage.MessageType.UNIT_ADDED,
"model.colony.newConvert", brave)
.addStringTemplate("%nation%", nation)
.addName("%colony%", colony.getName()));
}
}
}
}
}
/**
* All player colonies bombard all available targets.
*
* @param random A random number source.
* @param cs A <code>ChangeSet</code> to update.
*/
private void csBombardEnemyShips(Random random, ChangeSet cs) {
for (Colony colony : getColonies()) {
if (colony.canBombardEnemyShip()) {
for (Tile tile : colony.getTile().getSurroundingTiles(1)) {
if (!tile.isLand() && tile.getFirstUnit() != null
&& tile.getFirstUnit().getOwner() != this) {
for (Unit unit : new ArrayList<Unit>(tile.getUnitList())) {
if (atWarWith(unit.getOwner())
|| unit.hasAbility("model.ability.piracy")) {
csCombat(colony, unit, null, random, cs);
}
}
}
}
}
}
}
/**
* Remove a standard yearly amount of storable goods, and
* a random extra amount of a random type.
*
* @param random A pseudo-random number source.
* @param cs A <code>ChangeSet</code> to update.
*/
public void csYearlyGoodsRemoval(Random random, ChangeSet cs) {
List<GoodsType> goodsTypes = getGame().getSpecification()
.getGoodsTypeList();
Market market = getMarket();
// Pick a random type of storable goods to remove an extra amount of.
GoodsType removeType;
for (;;) {
removeType = Utils.getRandomMember(logger, "Choose goods type",
goodsTypes, random);
if (removeType.isStorable()) break;
}
// Remove standard amount, and the extra amount.
for (GoodsType type : goodsTypes) {
if (type.isStorable() && market.hasBeenTraded(type)) {
int amount = getGame().getTurn().getNumber() / 10;
if (type == removeType && amount > 0) {
amount += Utils.randomInt(logger, "Remove from market",
random, 2 * amount + 1);
}
if (amount > 0) {
market.addGoodsToMarket(type, -amount);
logger.finest(getName() + " removal of " + amount
+ " " + type
+ ", total: " + market.getAmountInMarket(type));
}
}
csFlushMarket(type, cs);
}
}
/**
* Adds a founding father to a players continental congress.
*
* @param father The <code>FoundingFather</code> to add.
* @param random A pseudo-random number source.
* @param cs A <code>ChangeSet</code> to update.
*/
public void csAddFoundingFather(FoundingFather father, Random random,
ChangeSet cs) {
Game game = getGame();
Specification spec = game.getSpecification();
Europe europe = getEurope();
boolean europeDirty = false;
// TODO: We do not want to have to update the whole player
// just to get the FF into the client. Use this hack until
// the client gets proper containers.
cs.addFather(this, father);
cs.addMessage(See.only(this),
new ModelMessage(ModelMessage.MessageType.SONS_OF_LIBERTY,
"model.player.foundingFatherJoinedCongress",
this)
.add("%foundingFather%", father.getNameKey())
.add("%description%", father.getDescriptionKey()));
cs.addHistory(this,
new HistoryEvent(getGame().getTurn(),
HistoryEvent.EventType.FOUNDING_FATHER)
.add("%father%", father.getNameKey()));
List<AbstractUnit> units = father.getUnits();
if (units != null && !units.isEmpty() && europe != null) {
createUnits(father.getUnits());
europeDirty = true;
}
java.util.Map<UnitType, UnitType> upgrades = father.getUpgrades();
if (upgrades != null) {
for (Unit u : getUnits()) {
UnitType newType = upgrades.get(u.getType());
if (newType != null) {
u.setType(newType);
cs.add(See.perhaps(), u);
}
}
}
for (Ability ability : father.getFeatureContainer().getAbilities()) {
if ("model.ability.addTaxToBells".equals(ability.getId())) {
// Provoke a tax/liberty recalculation
setTax(getTax());
cs.addPartial(See.only(this), this, "tax");
}
}
for (Event event : father.getEvents()) {
String eventId = event.getId();
if (eventId.equals("model.event.resetNativeAlarm")) {
for (Player p : game.getPlayers()) {
if (!p.isEuropean() && p.hasContacted(this)) {
p.setTension(this, new Tension(Tension.TENSION_MIN));
for (IndianSettlement is : p.getIndianSettlements()) {
if (is.hasContactedSettlement(this)) {
is.setAlarm(this,
new Tension(Tension.TENSION_MIN));
cs.add(See.only(this), is);
}
}
}
}
} else if (eventId.equals("model.event.boycottsLifted")) {
Market market = getMarket();
for (GoodsType goodsType : spec.getGoodsTypeList()) {
if (market.getArrears(goodsType) > 0) {
market.setArrears(goodsType, 0);
cs.add(See.only(this), market.getMarketData(goodsType));
}
}
} else if (eventId.equals("model.event.freeBuilding")) {
BuildingType type = spec.getBuildingType(event.getValue());
for (Colony colony : getColonies()) {
if (colony.canBuild(type)) {
colony.addBuilding(new ServerBuilding(game, colony, type));
colony.getBuildQueue().remove(type);
cs.add(See.only(this), colony);
}
}
} else if (eventId.equals("model.event.seeAllColonies")) {
for (Tile t : game.getMap().getAllTiles()) {
Colony colony = t.getColony();
if (colony != null
&& (ServerPlayer) colony.getOwner() != this) {
if (!t.isExploredBy(this)) {
t.setExploredBy(this, true);
}
t.updatePlayerExploredTile(this, false);
cs.add(See.only(this), t);
for (Tile x : colony.getOwnedTiles()) {
if (!x.isExploredBy(this)) {
x.setExploredBy(this, true);
}
x.updatePlayerExploredTile(this, false);
cs.add(See.only(this), x);
}
}
}
} else if (eventId.equals("model.event.increaseSonsOfLiberty")) {
int value = Integer.parseInt(event.getValue());
GoodsType bells = spec.getLibertyGoodsTypeList().get(0);
for (Colony colony : getColonies()) {
int requiredLiberty = ((colony.getSoL() + value)
* Colony.LIBERTY_PER_REBEL
* colony.getUnitCount()) / 100;
GoodsContainer container = colony.getGoodsContainer();
container.saveState();
colony.addGoods(bells, requiredLiberty
- colony.getGoodsCount(bells));
cs.add(See.only(this), container);
}
} else if (eventId.equals("model.event.newRecruits")
&& europe != null) {
List<RandomChoice<UnitType>> recruits
= generateRecruitablesList();
FeatureContainer fc = getFeatureContainer();
for (int i = 0; i < Europe.RECRUIT_COUNT; i++) {
if (!fc.hasAbility("model.ability.canRecruitUnit",
europe.getRecruitable(i))) {
UnitType newType = RandomChoice
.getWeightedRandom(logger,
"Replace recruit", random, recruits);
europe.setRecruitable(i, newType);
europeDirty = true;
}
}
} else if (eventId.equals("model.event.movementChange")) {
for (Unit u : getUnits()) {
if (u.getMovesLeft() > 0) {
u.setMovesLeft(u.getInitialMovesLeft());
cs.addPartial(See.only(this), u, "movesLeft");
}
}
}
}
if (europeDirty) cs.add(See.only(this), europe);
}
/**
* Claim land.
*
* @param tile The <code>Tile</code> to claim.
* @param settlement The <code>Settlement</code> to claim for.
* @param price The price to pay for the land, which must agree
* with the owner valuation, unless negative which denotes stealing.
* @param cs A <code>ChangeSet</code> to update.
*/
public void csClaimLand(Tile tile, Settlement settlement, int price,
ChangeSet cs) {
Player owner = tile.getOwner();
Settlement ownerSettlement = tile.getOwningSettlement();
tile.changeOwnership(this, settlement);
// Update the tile for all, and privately any now-angrier
// owners, or the player gold if a price was paid.
cs.add(See.perhaps(), tile);
if (price > 0) {
modifyGold(-price);
owner.modifyGold(price);
cs.addPartial(See.only(this), this, "gold");
} else if (price < 0 && owner.isIndian()) {
IndianSettlement is = (IndianSettlement) ownerSettlement;
if (is != null) {
is.makeContactSettlement(this);
cs.add(See.only(null).perhaps(this),
owner.modifyTension(this, Tension.TENSION_ADD_LAND_TAKEN, is));
}
}
}
/**
* A unit migrates from Europe.
*
* @param slot The slot within <code>Europe</code> to select the unit from.
* @param type The type of migration occurring.
* @param random A pseudo-random number source.
* @param cs A <code>ChangeSet</code> to update.
*/
public void csEmigrate(int slot, MigrationType type, Random random,
ChangeSet cs) {
// Valid slots are in [1,3], recruitable indices are in [0,2].
// An invalid slot is normal when the player has no control over
// recruit type.
boolean selected = 1 <= slot && slot <= Europe.RECRUIT_COUNT;
int index = (selected) ? slot-1
: Utils.randomInt(logger, "Choose emigrant", random,
Europe.RECRUIT_COUNT);
// Create the recruit, move it to the docks.
Europe europe = getEurope();
UnitType recruitType = europe.getRecruitable(index);
Game game = getGame();
Unit unit = new ServerUnit(game, europe, this, recruitType,
UnitState.ACTIVE);
unit.setLocation(europe);
// Handle migration type specific changes.
switch (type) {
case FOUNTAIN:
setRemainingEmigrants(getRemainingEmigrants() - 1);
break;
case RECRUIT:
modifyGold(-europe.getRecruitPrice());
cs.addPartial(See.only(this), this, "gold");
europe.increaseRecruitmentDifficulty();
// Fall through
case NORMAL:
updateImmigrationRequired();
reduceImmigration();
cs.addPartial(See.only(this), this,
"immigration", "immigrationRequired");
break;
default:
throw new IllegalArgumentException("Bogus migration type");
}
// Replace the recruit we used.
List<RandomChoice<UnitType>> recruits = generateRecruitablesList();
europe.setRecruitable(index,
RandomChoice.getWeightedRandom(logger,
"Replace recruit", random, recruits));
cs.add(See.only(this), europe);
// Add an informative message only if this was an ordinary
// migration where we did not select the unit type.
// Other cases were selected.
if (!selected) {
cs.addMessage(See.only(this),
new ModelMessage(ModelMessage.MessageType.UNIT_ADDED,
"model.europe.emigrate",
this, unit)
.add("%europe%", europe.getNameKey())
.addStringTemplate("%unit%", unit.getLabel()));
}
}
/**
* Combat.
*
* @param attacker The <code>FreeColGameObject</code> that is attacking.
* @param defender The <code>FreeColGameObject</code> that is defending.
* @param crs A list of <code>CombatResult</code>s defining the result.
* @param random A pseudo-random number source.
* @param cs A <code>ChangeSet</code> to update.
*/
public void csCombat(FreeColGameObject attacker,
FreeColGameObject defender,
List<CombatResult> crs,
Random random,
ChangeSet cs) throws IllegalStateException {
CombatModel combatModel = getGame().getCombatModel();
boolean isAttack = combatModel.combatIsAttack(attacker, defender);
boolean isBombard = combatModel.combatIsBombard(attacker, defender);
Unit attackerUnit = null;
Settlement attackerSettlement = null;
Tile attackerTile = null;
Unit defenderUnit = null;
ServerPlayer defenderPlayer = null;
Tile defenderTile = null;
if (isAttack) {
attackerUnit = (Unit) attacker;
attackerTile = attackerUnit.getTile();
defenderUnit = (Unit) defender;
defenderPlayer = (ServerPlayer) defenderUnit.getOwner();
defenderTile = defenderUnit.getTile();
cs.addAttribute(See.only(this), "sound",
(attackerUnit.isNaval())
? "sound.attack.naval"
: (attackerUnit.hasAbility("model.ability.bombard"))
? "sound.attack.artillery"
: (attackerUnit.isMounted())
? "sound.attack.mounted"
: "sound.attack.foot");
} else if (isBombard) {
attackerSettlement = (Settlement) attacker;
attackerTile = attackerSettlement.getTile();
defenderUnit = (Unit) defender;
defenderPlayer = (ServerPlayer) defenderUnit.getOwner();
defenderTile = defenderUnit.getTile();
cs.addAttribute(See.only(this), "sound", "sound.attack.bombard");
} else {
throw new IllegalStateException("Bogus combat");
}
// If the combat results were not specified (usually the case),
// query the combat model.
if (crs == null) {
crs = combatModel.generateAttackResult(random, attacker, defender);
}
if (crs.isEmpty()) {
throw new IllegalStateException("empty attack result");
}
// Extract main result, insisting it is one of the fundamental cases,
// and add the animation.
// Set vis so that loser always sees things.
// TODO: Bombard animations
See vis; // Visibility that insists on the loser seeing the result.
CombatResult result = crs.remove(0);
switch (result) {
case NO_RESULT:
vis = See.perhaps();
break; // Do not animate if there is no result.
case WIN:
vis = See.perhaps().always(defenderPlayer);
if (isAttack) {
cs.addAttack(vis, attackerUnit, defenderUnit, true);
}
break;
case LOSE:
vis = See.perhaps().always(this);
if (isAttack) {
cs.addAttack(vis, attackerUnit, defenderUnit, false);
}
break;
default:
throw new IllegalStateException("generateAttackResult returned: "
+ result);
}
// Now process the details.
boolean attackerTileDirty = false;
boolean defenderTileDirty = false;
boolean moveAttacker = false;
boolean burnedNativeCapital = false;
Settlement settlement = defenderTile.getSettlement();
Colony colony = defenderTile.getColony();
IndianSettlement natives = (settlement instanceof IndianSettlement)
? (IndianSettlement) settlement
: null;
int attackerTension = 0;
int defenderTension = 0;
for (CombatResult cr : crs) {
boolean ok;
switch (cr) {
case AUTOEQUIP_UNIT:
ok = isAttack && settlement != null;
if (ok) {
csAutoequipUnit(defenderUnit, settlement, cs);
}
break;
case BURN_MISSIONS:
ok = isAttack && result == CombatResult.WIN
&& natives != null
&& isEuropean() && defenderPlayer.isIndian();
if (ok) {
defenderTileDirty |= natives.getMissionary(this) != null;
csBurnMissions(attackerUnit, natives, cs);
}
break;
case CAPTURE_AUTOEQUIP:
ok = isAttack && result == CombatResult.WIN
&& settlement != null
&& defenderPlayer.isEuropean();
if (ok) {
csCaptureAutoEquip(attackerUnit, defenderUnit, cs);
attackerTileDirty = defenderTileDirty = true;
}
break;
case CAPTURE_COLONY:
ok = isAttack && result == CombatResult.WIN
&& colony != null
&& isEuropean() && defenderPlayer.isEuropean();
if (ok) {
csCaptureColony(attackerUnit, colony, cs);
attackerTileDirty = defenderTileDirty = true;
moveAttacker = true;
defenderTension += Tension.TENSION_ADD_MAJOR;
}
break;
case CAPTURE_CONVERT:
ok = isAttack && result == CombatResult.WIN
&& natives != null
&& isEuropean() && defenderPlayer.isIndian();
if (ok) {
csCaptureConvert(attackerUnit, natives, random, cs);
attackerTileDirty = true;
}
break;
case CAPTURE_EQUIP:
ok = isAttack && result != CombatResult.NO_RESULT;
if (ok) {
if (result == CombatResult.WIN) {
csCaptureEquip(attackerUnit, defenderUnit, cs);
} else {
csCaptureEquip(defenderUnit, attackerUnit, cs);
}
attackerTileDirty = defenderTileDirty = true;
}
break;
case CAPTURE_UNIT:
ok = isAttack && result != CombatResult.NO_RESULT;
if (ok) {
if (result == CombatResult.WIN) {
csCaptureUnit(attackerUnit, defenderUnit, cs);
} else {
csCaptureUnit(defenderUnit, attackerUnit, cs);
}
attackerTileDirty = defenderTileDirty = true;
}
break;
case DAMAGE_COLONY_SHIPS:
ok = isAttack && result == CombatResult.WIN
&& colony != null;
if (ok) {
csDamageColonyShips(attackerUnit, colony, cs);
defenderTileDirty = true;
}
break;
case DAMAGE_SHIP_ATTACK:
ok = isAttack && result != CombatResult.NO_RESULT
&& ((result == CombatResult.WIN) ? defenderUnit
: attackerUnit).isNaval();
if (ok) {
if (result == CombatResult.WIN) {
csDamageShipAttack(attackerUnit, defenderUnit, cs);
defenderTileDirty = true;
} else {
csDamageShipAttack(defenderUnit, attackerUnit, cs);
attackerTileDirty = true;
}
}
break;
case DAMAGE_SHIP_BOMBARD:
ok = isBombard && result == CombatResult.WIN
&& defenderUnit.isNaval();
if (ok) {
csDamageShipBombard(attackerSettlement, defenderUnit, cs);
defenderTileDirty = true;
}
break;
case DEMOTE_UNIT:
ok = isAttack && result != CombatResult.NO_RESULT;
if (ok) {
if (result == CombatResult.WIN) {
csDemoteUnit(attackerUnit, defenderUnit, cs);
defenderTileDirty = true;
} else {
csDemoteUnit(defenderUnit, attackerUnit, cs);
attackerTileDirty = true;
}
}
break;
case DESTROY_COLONY:
ok = isAttack && result == CombatResult.WIN
&& colony != null
&& isIndian() && defenderPlayer.isEuropean();
if (ok) {
csDestroyColony(attackerUnit, colony, cs);
attackerTileDirty = defenderTileDirty = true;
moveAttacker = true;
attackerTension -= Tension.TENSION_ADD_NORMAL;
defenderTension += Tension.TENSION_ADD_MAJOR;
}
break;
case DESTROY_SETTLEMENT:
ok = isAttack && result == CombatResult.WIN
&& natives != null
&& defenderPlayer.isIndian();
if (ok) {
csDestroySettlement(attackerUnit, natives, random, cs);
attackerTileDirty = defenderTileDirty = true;
moveAttacker = true;
burnedNativeCapital = settlement.isCapital();
attackerTension -= Tension.TENSION_ADD_NORMAL;
if (!burnedNativeCapital) {
defenderTension += Tension.TENSION_ADD_MAJOR;
}
}
break;
case EVADE_ATTACK:
ok = isAttack && result == CombatResult.NO_RESULT
&& defenderUnit.isNaval();
if (ok) {
csEvadeAttack(attackerUnit, defenderUnit, cs);
}
break;
case EVADE_BOMBARD:
ok = isBombard && result == CombatResult.NO_RESULT
&& defenderUnit.isNaval();
if (ok) {
csEvadeBombard(attackerSettlement, defenderUnit, cs);
}
break;
case LOOT_SHIP:
ok = isAttack && result != CombatResult.NO_RESULT
&& attackerUnit.isNaval() && defenderUnit.isNaval();
if (ok) {
if (result == CombatResult.WIN) {
csLootShip(attackerUnit, defenderUnit, cs);
} else {
csLootShip(defenderUnit, attackerUnit, cs);
}
}
break;
case LOSE_AUTOEQUIP:
ok = isAttack && result == CombatResult.WIN
&& settlement != null
&& defenderPlayer.isEuropean();
if (ok) {
csLoseAutoEquip(attackerUnit, defenderUnit, cs);
defenderTileDirty = true;
}
break;
case LOSE_EQUIP:
ok = isAttack && result != CombatResult.NO_RESULT;
if (ok) {
if (result == CombatResult.WIN) {
csLoseEquip(attackerUnit, defenderUnit, cs);
defenderTileDirty = true;
} else {
csLoseEquip(defenderUnit, attackerUnit, cs);
attackerTileDirty = true;
}
}
break;
case PILLAGE_COLONY:
ok = isAttack && result == CombatResult.WIN
&& colony != null
&& isIndian() && defenderPlayer.isEuropean();
if (ok) {
csPillageColony(attackerUnit, colony, random, cs);
defenderTileDirty = true;
attackerTension -= Tension.TENSION_ADD_NORMAL;
}
break;
case PROMOTE_UNIT:
ok = isAttack && result != CombatResult.NO_RESULT;
if (ok) {
if (result == CombatResult.WIN) {
csPromoteUnit(attackerUnit, defenderUnit, cs);
attackerTileDirty = true;
} else {
csPromoteUnit(defenderUnit, attackerUnit, cs);
defenderTileDirty = true;
}
}
break;
case SINK_COLONY_SHIPS:
ok = isAttack && result == CombatResult.WIN
&& colony != null;
if (ok) {
csSinkColonyShips(attackerUnit, colony, cs);
defenderTileDirty = true;
}
break;
case SINK_SHIP_ATTACK:
ok = isAttack && result != CombatResult.NO_RESULT
&& ((result == CombatResult.WIN) ? defenderUnit
: attackerUnit).isNaval();
if (ok) {
if (result == CombatResult.WIN) {
csSinkShipAttack(attackerUnit, defenderUnit, cs);
defenderTileDirty = true;
} else {
csSinkShipAttack(defenderUnit, attackerUnit, cs);
attackerTileDirty = true;
}
}
break;
case SINK_SHIP_BOMBARD:
ok = isBombard && result == CombatResult.WIN
&& defenderUnit.isNaval();
if (ok) {
csSinkShipBombard(attackerSettlement, defenderUnit, cs);
defenderTileDirty = true;
}
break;
case SLAUGHTER_UNIT:
ok = isAttack && result != CombatResult.NO_RESULT;
if (ok) {
if (result == CombatResult.WIN) {
csSlaughterUnit(attackerUnit, defenderUnit, cs);
defenderTileDirty = true;
attackerTension -= Tension.TENSION_ADD_NORMAL;
defenderTension += getSlaughterTension(defenderUnit);
} else {
csSlaughterUnit(defenderUnit, attackerUnit, cs);
attackerTileDirty = true;
attackerTension += getSlaughterTension(attackerUnit);
defenderTension -= Tension.TENSION_ADD_NORMAL;
}
}
break;
default:
ok = false;
break;
}
if (!ok) {
throw new IllegalStateException("Attack (result=" + result
+ ") has bogus subresult: "
+ cr);
}
}
// Handle stance and tension.
// - Privateers do not provoke stance changes but can set the
// attackedByPrivateers flag
// - Attacks among Europeans imply war
// - Burning of a native capital results in surrender
// - Other attacks involving natives do not imply war, but
// changes in Tension can drive Stance, however this is
// decided by the native AI in their turn so just adjust tension.
if (attacker.hasAbility("model.ability.piracy")) {
if (!defenderPlayer.getAttackedByPrivateers()) {
defenderPlayer.setAttackedByPrivateers(true);
cs.addPartial(See.only(defenderPlayer), defenderPlayer,
"attackedByPrivateers");
}
} else if (defender.hasAbility("model.ability.piracy")) {
; // do nothing
} else if (isEuropean() && defenderPlayer.isEuropean()) {
csChangeStance(Stance.WAR, defenderPlayer, true, cs);
} else if (burnedNativeCapital) {
csChangeStance(Stance.PEACE, defenderPlayer, true, cs);
defenderPlayer.getTension(this).setValue(Tension.SURRENDERED);
for (IndianSettlement is : defenderPlayer.getIndianSettlements()) {
is.getAlarm(this).setValue(Tension.SURRENDERED);
cs.add(See.perhaps(), is);
}
} else { // At least one player is non-European
if (isEuropean()) {
csChangeStance(Stance.WAR, defenderPlayer, false, cs);
} else if (isIndian()) {
if (result == CombatResult.WIN) {
attackerTension -= Tension.TENSION_ADD_MINOR;
} else if (result == CombatResult.LOSE) {
attackerTension += Tension.TENSION_ADD_MINOR;
}
}
if (defenderPlayer.isEuropean()) {
defenderPlayer.csChangeStance(Stance.WAR, this, false, cs);
} else if (defenderPlayer.isIndian()) {
if (result == CombatResult.WIN) {
defenderTension += Tension.TENSION_ADD_MINOR;
} else if (result == CombatResult.LOSE) {
defenderTension -= Tension.TENSION_ADD_MINOR;
}
}
if (attackerTension != 0) {
cs.add(See.only(null).perhaps(defenderPlayer),
modifyTension(defenderPlayer, attackerTension));
}
if (defenderTension != 0) {
cs.add(See.only(null).perhaps(this),
defenderPlayer.modifyTension(this, defenderTension));
}
}
// Move the attacker if required.
if (moveAttacker) {
attackerUnit.setMovesLeft(attackerUnit.getInitialMovesLeft());
((ServerUnit) attackerUnit).csMove(defenderTile, random, cs);
+ attackerUnit.setMovesLeft(0);
// Move adds in updates for the tiles, but...
attackerTileDirty = defenderTileDirty = false;
// ...with visibility of perhaps().
// Thus the defender might see the change,
// but because its settlement is gone it also might not.
// So add in another defender-specific update.
// The worst that can happen is a duplicate update.
cs.add(See.only(defenderPlayer), defenderTile);
} else if (isAttack) {
// The Revenger unit can attack multiple times, so spend
// at least the eventual cost of moving to the tile.
// Other units consume the entire move.
if (attacker.hasAbility("model.ability.multipleAttacks")) {
int movecost = attackerUnit.getMoveCost(defenderTile);
attackerUnit.setMovesLeft(attackerUnit.getMovesLeft()
- movecost);
} else {
attackerUnit.setMovesLeft(0);
}
if (!attackerTileDirty) {
cs.addPartial(See.only(this), attacker, "movesLeft");
}
}
// Make sure we always update the attacker and defender tile
// if it is not already done yet.
if (attackerTileDirty) cs.add(vis, attackerTile);
if (defenderTileDirty) cs.add(vis, defenderTile);
}
/**
* Gets the amount to raise tension by when a unit is slaughtered.
*
* @param loser The <code>Unit</code> that dies.
* @return An amount to raise tension by.
*/
private int getSlaughterTension(Unit loser) {
// Tension rises faster when units die.
Settlement settlement = loser.getSettlement();
if (settlement != null) {
if (settlement instanceof IndianSettlement) {
return (((IndianSettlement) settlement).isCapital())
? Tension.TENSION_ADD_CAPITAL_ATTACKED
: Tension.TENSION_ADD_SETTLEMENT_ATTACKED;
} else {
return Tension.TENSION_ADD_NORMAL;
}
} else { // attack in the open
return (loser.getIndianSettlement() != null)
? Tension.TENSION_ADD_UNIT_DESTROYED
: Tension.TENSION_ADD_MINOR;
}
}
/**
* Notifies of automatic arming.
*
* @param unit The <code>Unit</code> that is auto-equipping.
* @param settlement The <code>Settlement</code> being defended.
* @param cs A <code>ChangeSet</code> to update.
*/
private void csAutoequipUnit(Unit unit, Settlement settlement,
ChangeSet cs) {
ServerPlayer player = (ServerPlayer) unit.getOwner();
cs.addMessage(See.only(player),
new ModelMessage(ModelMessage.MessageType.COMBAT_RESULT,
"model.unit.automaticDefence",
unit)
.addStringTemplate("%unit%", unit.getLabel())
.addName("%colony%", settlement.getName()));
}
/**
* Burns a players missions.
*
* @param attacker The <code>Unit</code> that attacked.
* @param settlement The <code>IndianSettlement</code> that was attacked.
* @param cs The <code>ChangeSet</code> to update.
*/
private void csBurnMissions(Unit attacker, IndianSettlement settlement,
ChangeSet cs) {
ServerPlayer attackerPlayer = (ServerPlayer) attacker.getOwner();
StringTemplate attackerNation = attackerPlayer.getNationName();
ServerPlayer nativePlayer = (ServerPlayer) settlement.getOwner();
StringTemplate nativeNation = nativePlayer.getNationName();
// Message only for the European player
cs.addMessage(See.only(attackerPlayer),
new ModelMessage(ModelMessage.MessageType.COMBAT_RESULT,
"model.unit.burnMissions",
attacker, settlement)
.addStringTemplate("%nation%", attackerNation)
.addStringTemplate("%enemyNation%", nativeNation));
// Burn down the missions
for (IndianSettlement s : nativePlayer.getIndianSettlements()) {
Unit missionary = s.getMissionary(attackerPlayer);
if (missionary != null) {
s.changeMissionary(null);
if (s != settlement) cs.add(See.perhaps(), s.getTile());
}
}
}
/**
* Defender autoequips but loses and attacker captures the equipment.
*
* @param attacker The <code>Unit</code> that attacked.
* @param defender The <code>Unit</code> that defended and loses equipment.
* @param cs A <code>ChangeSet</code> to update.
*/
private void csCaptureAutoEquip(Unit attacker, Unit defender,
ChangeSet cs) {
EquipmentType equip
= defender.getBestCombatEquipmentType(defender.getAutomaticEquipment());
csLoseAutoEquip(attacker, defender, cs);
csCaptureEquipment(attacker, defender, equip, cs);
}
/**
* Captures a colony.
*
* @param attacker The attacking <code>Unit</code>.
* @param colony The <code>Colony</code> to capture.
* @param cs The <code>ChangeSet</code> to update.
*/
private void csCaptureColony(Unit attacker, Colony colony, ChangeSet cs) {
Game game = attacker.getGame();
ServerPlayer attackerPlayer = (ServerPlayer) attacker.getOwner();
StringTemplate attackerNation = attackerPlayer.getNationName();
ServerPlayer colonyPlayer = (ServerPlayer) colony.getOwner();
StringTemplate colonyNation = colonyPlayer.getNationName();
Tile tile = colony.getTile();
int plunder = colony.getPlunder();
// Handle history and messages before colony handover
cs.addHistory(attackerPlayer,
new HistoryEvent(game.getTurn(),
HistoryEvent.EventType.CONQUER_COLONY)
.addStringTemplate("%nation%", colonyNation)
.addName("%colony%", colony.getName()));
cs.addHistory(colonyPlayer,
new HistoryEvent(game.getTurn(),
HistoryEvent.EventType.COLONY_CONQUERED)
.addStringTemplate("%nation%", attackerNation)
.addName("%colony%", colony.getName()));
cs.addMessage(See.only(attackerPlayer),
new ModelMessage(ModelMessage.MessageType.COMBAT_RESULT,
"model.unit.colonyCaptured",
colony)
.addName("%colony%", colony.getName())
.addAmount("%amount%", plunder));
cs.addMessage(See.only(colonyPlayer),
new ModelMessage(ModelMessage.MessageType.COMBAT_RESULT,
"model.unit.colonyCapturedBy",
colony.getTile())
.addName("%colony%", colony.getName())
.addAmount("%amount%", plunder)
.addStringTemplate("%player%", attackerNation));
// Allocate some plunder
attackerPlayer.modifyGold(plunder);
cs.addPartial(See.only(attackerPlayer), attackerPlayer, "gold");
colonyPlayer.modifyGold(-plunder);
cs.addPartial(See.only(colonyPlayer), colonyPlayer, "gold");
// Hand over the colony
colony.changeOwner(attackerPlayer);
// Inform former owner of loss of owned tiles, and process possible
// increase in line of sight. Leave other exploration etc to csMove.
for (Tile t : colony.getOwnedTiles()) {
cs.add(See.perhaps().always(colonyPlayer), t);
}
if (colony.getLineOfSight() > attacker.getLineOfSight()) {
for (Tile t : tile.getSurroundingTiles(attacker.getLineOfSight(),
colony.getLineOfSight())) {
// New owner has now explored within settlement line of sight.
attackerPlayer.setExplored(t);
cs.add(See.only(attackerPlayer), t);
}
}
cs.addAttribute(See.only(attackerPlayer), "sound",
"sound.event.captureColony");
}
/**
* Extracts a convert from a native settlement.
*
* @pamam attacker The <code>Unit</code> that is attacking.
* @param settlement The <code>IndianSettlement</code> under attack.
* @param random A pseudo-random number source.
* @param cs A <code>ChangeSet</code> to update.
*/
private void csCaptureConvert(Unit attacker, IndianSettlement natives,
Random random, ChangeSet cs) {
ServerPlayer attackerPlayer = (ServerPlayer) attacker.getOwner();
StringTemplate convertNation = natives.getOwner().getNationName();
List<UnitType> converts = getGame().getSpecification()
.getUnitTypesWithAbility("model.ability.convert");
UnitType type = Utils.getRandomMember(logger, "Choose convert",
converts, random);
Unit convert = natives.getLastUnit();
cs.addMessage(See.only(attackerPlayer),
new ModelMessage(ModelMessage.MessageType.COMBAT_RESULT,
"model.unit.newConvertFromAttack",
convert)
.addStringTemplate("%nation%", convertNation)
.addStringTemplate("%unit%", convert.getLabel()));
convert.setOwner(attacker.getOwner());
convert.setType(type);
convert.setLocation(attacker.getTile());
}
/**
* Captures equipment.
*
* @param winner The <code>Unit</code> that captures equipment.
* @param loser The <code>Unit</code> that defended and loses equipment.
* @param cs A <code>ChangeSet</code> to update.
*/
private void csCaptureEquip(Unit winner, Unit loser, ChangeSet cs) {
EquipmentType equip
= loser.getBestCombatEquipmentType(loser.getEquipment());
csLoseEquip(winner, loser, cs);
csCaptureEquipment(winner, loser, equip, cs);
}
/**
* Capture equipment.
*
* @param winner The <code>Unit</code> that is capturing equipment.
* @param loser The <code>Unit</code> that is losing equipment.
* @param equip The <code>EquipmentType</code> to capture.
* @param cs A <code>ChangeSet</code> to update.
*/
private void csCaptureEquipment(Unit winner, Unit loser,
EquipmentType equip, ChangeSet cs) {
ServerPlayer winnerPlayer = (ServerPlayer) winner.getOwner();
ServerPlayer loserPlayer = (ServerPlayer) loser.getOwner();
if ((equip = winner.canCaptureEquipment(equip, loser)) != null) {
// TODO: what if winner captures equipment that is
// incompatible with their current equipment?
// Currently, can-not-happen, so ignoring the return from
// changeEquipment. Beware.
winner.changeEquipment(equip, 1);
// Currently can not capture equipment back so this only
// makes sense for native players, and the message is
// native specific.
if (winnerPlayer.isIndian()) {
StringTemplate winnerNation = winnerPlayer.getNationName();
cs.addMessage(See.only(loserPlayer),
new ModelMessage(ModelMessage.MessageType.COMBAT_RESULT,
"model.unit.equipmentCaptured",
winnerPlayer)
.addStringTemplate("%nation%", winnerNation)
.add("%equipment%", equip.getNameKey()));
// CHEAT: Immediately transferring the captured goods
// back to a potentially remote settlement is pretty
// dubious. Apparently Col1 did it. Better would be
// to give the capturing unit a go-home-with-plunder mission.
IndianSettlement settlement = winner.getIndianSettlement();
if (settlement != null) {
for (AbstractGoods goods : equip.getGoodsRequired()) {
settlement.addGoods(goods);
logger.finest("CHEAT teleporting " + goods.toString()
+ " back to " + settlement.getName());
}
cs.add(See.only(winnerPlayer), settlement);
}
}
}
}
/**
* Capture a unit.
*
* @param winner A <code>Unit</code> that is capturing.
* @param loser A <code>Unit</code> to capture.
* @param cs A <code>ChangeSet</code> to update.
*/
private void csCaptureUnit(Unit winner, Unit loser, ChangeSet cs) {
ServerPlayer loserPlayer = (ServerPlayer) loser.getOwner();
StringTemplate loserNation = loserPlayer.getNationName();
StringTemplate loserLocation = loser.getLocation()
.getLocationNameFor(loserPlayer);
StringTemplate oldName = loser.getLabel();
String messageId = loser.getType().getId() + ".captured";
ServerPlayer winnerPlayer = (ServerPlayer) winner.getOwner();
StringTemplate winnerNation = winnerPlayer.getNationName();
StringTemplate winnerLocation = winner.getLocation()
.getLocationNameFor(winnerPlayer);
// Capture the unit
UnitType type = loser.getTypeChange((winnerPlayer.isUndead())
? ChangeType.UNDEAD
: ChangeType.CAPTURE, winnerPlayer);
loser.setOwner(winnerPlayer);
if (type != null) loser.setType(type);
loser.setLocation(winner.getTile());
loser.setState(UnitState.ACTIVE);
// Winner message post-capture when it owns the loser
cs.addMessage(See.only(winnerPlayer),
new ModelMessage(ModelMessage.MessageType.COMBAT_RESULT,
messageId, loser)
.setDefaultId("model.unit.unitCaptured")
.addStringTemplate("%nation%", loserNation)
.addStringTemplate("%unit%", oldName)
.addStringTemplate("%enemyNation%", winnerNation)
.addStringTemplate("%enemyUnit%", winner.getLabel())
.addStringTemplate("%location%", winnerLocation));
cs.addMessage(See.only(loserPlayer),
new ModelMessage(ModelMessage.MessageType.COMBAT_RESULT,
messageId, loser.getTile())
.setDefaultId("model.unit.unitCaptured")
.addStringTemplate("%nation%", loserNation)
.addStringTemplate("%unit%", oldName)
.addStringTemplate("%enemyNation%", winnerNation)
.addStringTemplate("%enemyUnit%", winner.getLabel())
.addStringTemplate("%location%", loserLocation));
}
/**
* Damages all ships in a colony.
*
* @param attacker The <code>Unit</code> that is damaging.
* @param colony The <code>Colony</code> to damage ships in.
* @param cs A <code>ChangeSet</code> to update.
*/
private void csDamageColonyShips(Unit attacker, Colony colony,
ChangeSet cs) {
List<Unit> units = new ArrayList<Unit>(colony.getTile().getUnitList());
while (!units.isEmpty()) {
Unit unit = units.remove(0);
if (unit.isNaval()) {
csDamageShipAttack(attacker, unit, cs);
}
}
}
/**
* Damage a ship through normal attack.
*
* @param attacker The attacker <code>Unit</code>.
* @param ship The <code>Unit</code> which is a ship to damage.
* @param cs A <code>ChangeSet</code> to update.
*/
private void csDamageShipAttack(Unit attacker, Unit ship,
ChangeSet cs) {
ServerPlayer attackerPlayer = (ServerPlayer) attacker.getOwner();
StringTemplate attackerNation = attacker.getApparentOwnerName();
ServerPlayer shipPlayer = (ServerPlayer) ship.getOwner();
Location repair = ship.getRepairLocation();
StringTemplate repairLocationName = repair.getLocationNameFor(shipPlayer);
Location oldLocation = ship.getLocation();
StringTemplate shipNation = ship.getApparentOwnerName();
cs.addMessage(See.only(attackerPlayer),
new ModelMessage(ModelMessage.MessageType.COMBAT_RESULT,
"model.unit.enemyShipDamaged",
attacker)
.addStringTemplate("%unit%", attacker.getLabel())
.addStringTemplate("%enemyNation%", shipNation)
.addStringTemplate("%enemyUnit%", ship.getLabel()));
cs.addMessage(See.only(shipPlayer),
new ModelMessage(ModelMessage.MessageType.COMBAT_RESULT,
"model.unit.shipDamaged",
ship)
.addStringTemplate("%unit%", ship.getLabel())
.addStringTemplate("%enemyUnit%", attacker.getLabel())
.addStringTemplate("%enemyNation%", attackerNation)
.addStringTemplate("%repairLocation%", repairLocationName));
csDamageShip(ship, repair, cs);
}
/**
* Damage a ship through bombard.
*
* @param settlement The attacker <code>Settlement</code>.
* @param ship The <code>Unit</code> which is a ship to damage.
* @param cs A <code>ChangeSet</code> to update.
*/
private void csDamageShipBombard(Settlement settlement, Unit ship,
ChangeSet cs) {
ServerPlayer attackerPlayer = (ServerPlayer) settlement.getOwner();
ServerPlayer shipPlayer = (ServerPlayer) ship.getOwner();
Location repair = ship.getRepairLocation();
StringTemplate repairLocationName = repair.getLocationNameFor(shipPlayer);
StringTemplate shipNation = ship.getApparentOwnerName();
cs.addMessage(See.only(attackerPlayer),
new ModelMessage(ModelMessage.MessageType.COMBAT_RESULT,
"model.unit.enemyShipDamagedByBombardment",
settlement)
.addName("%colony%", settlement.getName())
.addStringTemplate("%nation%", shipNation)
.addStringTemplate("%unit%", ship.getLabel()));
cs.addMessage(See.only(shipPlayer),
new ModelMessage(ModelMessage.MessageType.COMBAT_RESULT,
"model.unit.shipDamagedByBombardment",
ship)
.addName("%colony%", settlement.getName())
.addStringTemplate("%unit%", ship.getLabel())
.addStringTemplate("%repairLocation%", repairLocationName));
csDamageShip(ship, repair, cs);
}
/**
* Damage a ship.
*
* @param ship The naval <code>Unit</code> to damage.
* @param repair The <code>Location</code> to send it to.
* @param cs A <code>ChangeSet</code> to update.
*/
private void csDamageShip(Unit ship, Location repair, ChangeSet cs) {
ServerPlayer player = (ServerPlayer) ship.getOwner();
// Lose the units aboard
Unit u;
while ((u = ship.getFirstUnit()) != null) {
u.setLocation(null);
cs.addDispose(player, ship, u);
}
// Damage the ship and send it off for repair
ship.getGoodsContainer().removeAll();
ship.setHitpoints(1);
ship.setDestination(null);
ship.setLocation(repair);
ship.setState(UnitState.ACTIVE);
ship.setMovesLeft(0);
cs.add(See.only(player), (FreeColGameObject) repair);
}
/**
* Demotes a unit.
*
* @param winner The <code>Unit</code> that won.
* @param loser The <code>Unit</code> that lost and should be demoted.
* @param cs A <code>ChangeSet</code> to update.
*/
private void csDemoteUnit(Unit winner, Unit loser, ChangeSet cs) {
ServerPlayer loserPlayer = (ServerPlayer) loser.getOwner();
StringTemplate loserNation = loserPlayer.getNationName();
StringTemplate loserLocation = loser.getLocation()
.getLocationNameFor(loserPlayer);
StringTemplate oldName = loser.getLabel();
String messageId = loser.getType().getId() + ".demoted";
ServerPlayer winnerPlayer = (ServerPlayer) winner.getOwner();
StringTemplate winnerNation = winnerPlayer.getNationName();
StringTemplate winnerLocation = winner.getLocation()
.getLocationNameFor(winnerPlayer);
UnitType type = loser.getTypeChange(ChangeType.DEMOTION, loserPlayer);
if (type == null || type == loser.getType()) {
logger.warning("Demotion failed, type="
+ ((type == null) ? "null"
: "same type: " + type));
return;
}
loser.setType(type);
cs.addMessage(See.only(winnerPlayer),
new ModelMessage(ModelMessage.MessageType.COMBAT_RESULT,
messageId, winner)
.setDefaultId("model.unit.unitDemoted")
.addStringTemplate("%nation%", loserNation)
.addStringTemplate("%oldName%", oldName)
.addStringTemplate("%unit%", loser.getLabel())
.addStringTemplate("%enemyNation%", winnerNation)
.addStringTemplate("%enemyUnit%", winner.getLabel())
.addStringTemplate("%location%", winnerLocation));
cs.addMessage(See.only(loserPlayer),
new ModelMessage(ModelMessage.MessageType.COMBAT_RESULT,
messageId, loser)
.setDefaultId("model.unit.unitDemoted")
.addStringTemplate("%nation%", loserNation)
.addStringTemplate("%oldName%", oldName)
.addStringTemplate("%unit%", loser.getLabel())
.addStringTemplate("%enemyNation%", winnerNation)
.addStringTemplate("%enemyUnit%", winner.getLabel())
.addStringTemplate("%location%", loserLocation));
}
/**
* Destroy a colony.
*
* @param attacker The <code>Unit</code> that attacked.
* @param colony The <code>Colony</code> that was attacked.
* @param cs The <code>ChangeSet</code> to update.
*/
private void csDestroyColony(Unit attacker, Colony colony,
ChangeSet cs) {
Game game = attacker.getGame();
ServerPlayer attackerPlayer = (ServerPlayer) attacker.getOwner();
StringTemplate attackerNation = attackerPlayer.getNationName();
ServerPlayer colonyPlayer = (ServerPlayer) colony.getOwner();
StringTemplate colonyNation = colonyPlayer.getNationName();
int plunder = colony.getPlunder();
Tile tile = colony.getTile();
// Handle history and messages before colony destruction.
cs.addHistory(colonyPlayer,
new HistoryEvent(game.getTurn(),
HistoryEvent.EventType.COLONY_DESTROYED)
.addStringTemplate("%nation%", attackerNation)
.addName("%colony%", colony.getName()));
cs.addMessage(See.only(colonyPlayer),
new ModelMessage(ModelMessage.MessageType.COMBAT_RESULT,
"model.unit.colonyBurning",
colony.getTile())
.addName("%colony%", colony.getName())
.addAmount("%amount%", plunder)
.addStringTemplate("%nation%", attackerNation)
.addStringTemplate("%unit%", attacker.getLabel()));
cs.addMessage(See.all().except(colonyPlayer),
new ModelMessage(ModelMessage.MessageType.COMBAT_RESULT,
"model.unit.colonyBurning.other",
attackerPlayer)
.addName("%colony%", colony.getName())
.addStringTemplate("%nation%", colonyNation)
.addStringTemplate("%attackerNation%", attackerNation));
// Allocate some plunder.
attackerPlayer.modifyGold(plunder);
cs.addPartial(See.only(attackerPlayer), attackerPlayer, "gold");
colonyPlayer.modifyGold(-plunder);
cs.addPartial(See.only(colonyPlayer), colonyPlayer, "gold");
// Dispose of the colony and its contents.
csDisposeSettlement(colony, cs);
}
/**
* Destroys an Indian settlement.
*
* @param attacker an <code>Unit</code> value
* @param settlement an <code>IndianSettlement</code> value
* @param random A pseudo-random number source.
* @param cs A <code>ChangeSet</code> to update.
*/
private void csDestroySettlement(Unit attacker,
IndianSettlement settlement,
Random random, ChangeSet cs) {
Game game = getGame();
Tile tile = settlement.getTile();
ServerPlayer attackerPlayer = (ServerPlayer) attacker.getOwner();
ServerPlayer nativePlayer = (ServerPlayer) settlement.getOwner();
StringTemplate nativeNation = nativePlayer.getNationName();
String settlementName = settlement.getName();
boolean capital = settlement.isCapital();
SettlementType settlementType = settlement.getType();
// Calculate the treasure amount. Larger if Hernan Cortes is
// present in the congress, from cities, and capitals.
RandomRange plunder = settlementType.getPlunder(attacker);
int treasure = 0;
int r = plunder.getRandomLimit();
if (r > 0) {
r = Utils.randomInt(logger, "Plunder native settlement", random, r);
treasure = plunder.getAmount(r);
}
// Destroy the settlement, update settlement tiles.
csDisposeSettlement(settlement, cs);
// Make the treasure train if there is treasure.
if (treasure > 0) {
List<UnitType> unitTypes = game.getSpecification()
.getUnitTypesWithAbility("model.ability.carryTreasure");
UnitType type = Utils.getRandomMember(logger, "Choose train",
unitTypes, random);
Unit train = new ServerUnit(game, tile, attackerPlayer, type,
UnitState.ACTIVE);
train.setTreasureAmount(treasure);
}
// This is an atrocity.
int atrocities = Player.SCORE_SETTLEMENT_DESTROYED;
if (settlementType.getClaimableRadius() > 1) atrocities *= 2;
if (capital) atrocities = (atrocities * 3) / 2;
attackerPlayer.modifyScore(atrocities);
cs.addPartial(See.only(attackerPlayer), attackerPlayer, "score");
// Finish with messages and history.
cs.addMessage(See.only(attackerPlayer),
new ModelMessage(ModelMessage.MessageType.COMBAT_RESULT,
"model.unit.indianTreasure",
attacker)
.addName("%settlement%", settlementName)
.addAmount("%amount%", treasure));
cs.addHistory(attackerPlayer,
new HistoryEvent(game.getTurn(),
HistoryEvent.EventType.DESTROY_SETTLEMENT)
.addStringTemplate("%nation%", nativeNation)
.addName("%settlement%", settlementName));
if (capital) {
cs.addMessage(See.only(this),
new ModelMessage(ModelMessage.MessageType.FOREIGN_DIPLOMACY,
"indianSettlement.capitalBurned",
attacker)
.addName("%name%", settlementName)
.addStringTemplate("%nation%", nativeNation));
}
if (nativePlayer.checkForDeath()) {
cs.addHistory(attackerPlayer,
new HistoryEvent(game.getTurn(),
HistoryEvent.EventType.DESTROY_NATION)
.addStringTemplate("%nation%", nativeNation));
}
cs.addAttribute(See.only(attackerPlayer), "sound",
"sound.event.destroySettlement");
}
/**
* Disposes of a settlement and reassign its tiles.
*
* @param settlement The <code>Settlement</code> under attack.
* @param cs A <code>ChangeSet</code> to update.
*/
private void csDisposeSettlement(Settlement settlement, ChangeSet cs) {
ServerPlayer owner = (ServerPlayer) settlement.getOwner();
HashMap<Settlement, Integer> votes = new HashMap<Settlement, Integer>();
// Try to reassign the tiles
List<Tile> owned = settlement.getOwnedTiles();
Tile centerTile = settlement.getTile();
Settlement centerClaimant = null;
while (!owned.isEmpty()) {
Tile tile = owned.remove(0);
votes.clear();
for (Tile t : tile.getSurroundingTiles(1)) {
// For each lost tile, find any neighbouring
// settlements and give them a shout at claiming the tile.
// Note that settlements now can own tiles outside
// their radius--- if we encounter any of these clean
// them up too.
Settlement s = t.getOwningSettlement();
if (s == null) {
;
} else if (s == settlement) {
// Add this to the tiles to process if its not
// there already.
if (!owned.contains(t)) owned.add(t);
} else if (s.getOwner().canOwnTile(tile)
&& (s.getOwner().isIndian()
|| s.getTile().getDistanceTo(tile) <= s.getRadius())) {
// Weight claimant settlements:
// settlements owned by the same player
// > settlements owned by same type of player
// > other settlements
int value = (s.getOwner() == owner) ? 3
: (s.getOwner().isEuropean() == owner.isEuropean()) ? 2
: 1;
if (votes.get(s) != null) value += votes.get(s).intValue();
votes.put(s, new Integer(value));
}
}
Settlement bestClaimant = null;
int bestClaim = 0;
for (Entry<Settlement, Integer> vote : votes.entrySet()) {
if (vote.getValue().intValue() > bestClaim) {
bestClaimant = vote.getKey();
bestClaim = vote.getValue().intValue();
}
}
if (tile == centerTile) {
centerClaimant = bestClaimant; // Defer until settlement gone
} else {
if (bestClaimant == null) {
tile.changeOwnership(null, null);
} else {
tile.changeOwnership(bestClaimant.getOwner(), bestClaimant);
}
cs.add(See.perhaps().always(owner), tile);
}
}
// Settlement goes away
cs.addDispose(owner, centerTile, settlement);
if (centerClaimant != null) {
centerTile.changeOwnership(centerClaimant.getOwner(),
centerClaimant);
}
}
/**
* Evade a normal attack.
*
* @param attacker The attacker <code>Unit</code>.
* @param defender A naval <code>Unit</code> that evades the attacker.
* @param cs A <code>ChangeSet</code> to update.
*/
private void csEvadeAttack(Unit attacker, Unit defender, ChangeSet cs) {
ServerPlayer attackerPlayer = (ServerPlayer) attacker.getOwner();
StringTemplate attackerNation = attacker.getApparentOwnerName();
ServerPlayer defenderPlayer = (ServerPlayer) defender.getOwner();
StringTemplate defenderNation = defender.getApparentOwnerName();
cs.addMessage(See.only(attackerPlayer),
new ModelMessage(ModelMessage.MessageType.COMBAT_RESULT,
"model.unit.enemyShipEvaded",
attacker)
.addStringTemplate("%unit%", attacker.getLabel())
.addStringTemplate("%enemyUnit%", defender.getLabel())
.addStringTemplate("%enemyNation%", defenderNation));
cs.addMessage(See.only(defenderPlayer),
new ModelMessage(ModelMessage.MessageType.COMBAT_RESULT,
"model.unit.shipEvaded",
defender)
.addStringTemplate("%unit%", defender.getLabel())
.addStringTemplate("%enemyUnit%", attacker.getLabel())
.addStringTemplate("%enemyNation%", attackerNation));
}
/**
* Evade a bombardment.
*
* @param settlement The attacker <code>Settlement</code>.
* @param defender A naval <code>Unit</code> that evades the attacker.
* @param cs A <code>ChangeSet</code> to update.
*/
private void csEvadeBombard(Settlement settlement, Unit defender,
ChangeSet cs) {
ServerPlayer attackerPlayer = (ServerPlayer) settlement.getOwner();
ServerPlayer defenderPlayer = (ServerPlayer) defender.getOwner();
StringTemplate defenderNation = defender.getApparentOwnerName();
cs.addMessage(See.only(attackerPlayer),
new ModelMessage(ModelMessage.MessageType.COMBAT_RESULT,
"model.unit.shipEvadedBombardment",
settlement)
.addName("%colony%", settlement.getName())
.addStringTemplate("%unit%", defender.getLabel())
.addStringTemplate("%nation%", defenderNation));
cs.addMessage(See.only(defenderPlayer),
new ModelMessage(ModelMessage.MessageType.COMBAT_RESULT,
"model.unit.shipEvadedBombardment",
defender)
.addName("%colony%", settlement.getName())
.addStringTemplate("%unit%", defender.getLabel())
.addStringTemplate("%nation%", defenderNation));
}
/**
* Loot a ship.
*
* @param winner The winning naval <code>Unit</code>.
* @param loser The losing naval <code>Unit</code>
* @param cs A <code>ChangeSet</code> to update.
*/
private void csLootShip(Unit winner, Unit loser, ChangeSet cs) {
List<Goods> capture = new ArrayList<Goods>(loser.getGoodsList());
ServerPlayer winnerPlayer = (ServerPlayer) winner.getOwner();
if (capture.size() <= 0) return;
if (winnerPlayer.isAI()) {
// This should be in the AI code.
// Just loot in order of sale value.
final Market market = winnerPlayer.getMarket();
Collections.sort(capture, new Comparator<Goods>() {
public int compare(Goods g1, Goods g2) {
int p1 = market.getPaidForSale(g1.getType())
* g1.getAmount();
int p2 = market.getPaidForSale(g2.getType())
* g2.getAmount();
return p2 - p1;
}
});
while (capture.size() > 0) {
Goods g = capture.remove(0);
if (!winner.canAdd(g)) break;
winner.add(g);
}
} else if (winner.getSpaceLeft() > 0) {
for (Goods g : capture) g.setLocation(null);
TransactionSession.establishLootSession(winner, loser, capture);
cs.addAttribute(See.only(winnerPlayer), "loot", "true");
}
loser.getGoodsContainer().removeAll();
loser.setState(UnitState.ACTIVE);
}
/**
* Unit autoequips but loses equipment.
*
* @param attacker The <code>Unit</code> that attacked.
* @param defender The <code>Unit</code> that defended and loses equipment.
* @param cs A <code>ChangeSet</code> to update.
*/
private void csLoseAutoEquip(Unit attacker, Unit defender, ChangeSet cs) {
ServerPlayer defenderPlayer = (ServerPlayer) defender.getOwner();
StringTemplate defenderNation = defenderPlayer.getNationName();
Settlement settlement = defender.getSettlement();
StringTemplate defenderLocation = defender.getLocation()
.getLocationNameFor(defenderPlayer);
EquipmentType equip = defender
.getBestCombatEquipmentType(defender.getAutomaticEquipment());
ServerPlayer attackerPlayer = (ServerPlayer) attacker.getOwner();
StringTemplate attackerLocation = attacker.getLocation()
.getLocationNameFor(attackerPlayer);
StringTemplate attackerNation = attackerPlayer.getNationName();
// Autoequipment is not actually with the unit, it is stored
// in the settlement of the unit. Remove it from there.
for (AbstractGoods goods : equip.getGoodsRequired()) {
settlement.removeGoods(goods);
}
cs.addMessage(See.only(attackerPlayer),
new ModelMessage(ModelMessage.MessageType.COMBAT_RESULT,
"model.unit.unitWinColony",
attacker)
.addStringTemplate("%location%", attackerLocation)
.addStringTemplate("%nation%", attackerNation)
.addStringTemplate("%unit%", attacker.getLabel())
.addName("%settlement%", settlement.getNameFor(attackerPlayer))
.addStringTemplate("%enemyNation%", defenderNation)
.addStringTemplate("%enemyUnit%", defender.getLabel()));
cs.addMessage(See.only(defenderPlayer),
new ModelMessage(ModelMessage.MessageType.COMBAT_RESULT,
"model.unit.unitLoseAutoEquip",
defender)
.addStringTemplate("%location%", defenderLocation)
.addStringTemplate("%nation%", defenderNation)
.addStringTemplate("%unit%", defender.getLabel())
.addName("%settlement%", settlement.getNameFor(defenderPlayer))
.addStringTemplate("%enemyNation%", attackerNation)
.addStringTemplate("%enemyUnit%", attacker.getLabel()));
}
/**
* Unit drops some equipment.
*
* @param winner The <code>Unit</code> that won.
* @param loser The <code>Unit</code> that lost and loses equipment.
* @param cs A <code>ChangeSet</code> to update.
*/
private void csLoseEquip(Unit winner, Unit loser, ChangeSet cs) {
ServerPlayer loserPlayer = (ServerPlayer) loser.getOwner();
StringTemplate loserNation = loserPlayer.getNationName();
StringTemplate loserLocation = loser.getLocation()
.getLocationNameFor(loserPlayer);
StringTemplate oldName = loser.getLabel();
ServerPlayer winnerPlayer = (ServerPlayer) winner.getOwner();
StringTemplate winnerNation = winnerPlayer.getNationName();
StringTemplate winnerLocation = winner.getLocation()
.getLocationNameFor(winnerPlayer);
EquipmentType equip
= loser.getBestCombatEquipmentType(loser.getEquipment());
// Remove the equipment, accounting for possible loss of
// mobility due to horses going away.
loser.changeEquipment(equip, -1);
loser.setMovesLeft(Math.min(loser.getMovesLeft(),
loser.getInitialMovesLeft()));
String messageId;
if (loser.getEquipment().isEmpty()) {
messageId = "model.unit.unitDemotedToUnarmed";
loser.setState(UnitState.ACTIVE);
} else {
messageId = loser.getType().getId() + ".demoted";
}
cs.addMessage(See.only(winnerPlayer),
new ModelMessage(ModelMessage.MessageType.COMBAT_RESULT,
messageId, winner)
.setDefaultId("model.unit.unitDemoted")
.addStringTemplate("%nation%", loserNation)
.addStringTemplate("%oldName%", oldName)
.addStringTemplate("%unit%", loser.getLabel())
.addStringTemplate("%enemyNation%", winnerNation)
.addStringTemplate("%enemyUnit%", winner.getLabel())
.addStringTemplate("%location%", winnerLocation));
cs.addMessage(See.only(loserPlayer),
new ModelMessage(ModelMessage.MessageType.COMBAT_RESULT,
messageId, loser)
.setDefaultId("model.unit.unitDemoted")
.addStringTemplate("%nation%", loserNation)
.addStringTemplate("%oldName%", oldName)
.addStringTemplate("%unit%", loser.getLabel())
.addStringTemplate("%enemyNation%", winnerNation)
.addStringTemplate("%enemyUnit%", winner.getLabel())
.addStringTemplate("%location%", loserLocation));
}
/**
* Damage a building or a ship or steal some goods or gold.
*
* @param attacker The attacking <code>Unit</code>.
* @param colony The <code>Colony</code> to pillage.
* @param random A pseudo-random number source.
* @param cs A <code>ChangeSet</code> to update.
*/
private void csPillageColony(Unit attacker, Colony colony,
Random random, ChangeSet cs) {
ServerPlayer attackerPlayer = (ServerPlayer) attacker.getOwner();
StringTemplate attackerNation = attackerPlayer.getNationName();
ServerPlayer colonyPlayer = (ServerPlayer) colony.getOwner();
// Collect the damagable buildings, ships, movable goods.
List<Building> buildingList = colony.getBurnableBuildingList();
List<Unit> shipList = colony.getShipList();
List<Goods> goodsList = colony.getLootableGoodsList();
// Pick one, with one extra choice for stealing gold.
int pillage = Utils.randomInt(logger, "Pillage choice", random,
buildingList.size() + shipList.size()
+ goodsList.size()
+ ((colony.getPlunder() == 0) ? 0 : 1));
if (pillage < buildingList.size()) {
Building building = buildingList.get(pillage);
cs.addMessage(See.only(colonyPlayer),
new ModelMessage(ModelMessage.MessageType.COMBAT_RESULT,
"model.unit.buildingDamaged",
colony)
.add("%building%", building.getNameKey())
.addName("%colony%", colony.getName())
.addStringTemplate("%enemyNation%", attackerNation)
.addStringTemplate("%enemyUnit%", attacker.getLabel()));
colony.damageBuilding(building);
} else if (pillage < buildingList.size() + shipList.size()) {
Unit ship = shipList.get(pillage - buildingList.size());
if (ship.getRepairLocation() == null) {
csSinkShipAttack(attacker, ship, cs);
} else {
csDamageShipAttack(attacker, ship, cs);
}
} else if (pillage < buildingList.size() + shipList.size()
+ goodsList.size()) {
Goods goods = goodsList.get(pillage - buildingList.size()
- shipList.size());
goods.setAmount(Math.min(goods.getAmount() / 2, 50));
colony.removeGoods(goods);
if (attacker.getSpaceLeft() > 0) attacker.add(goods);
cs.addMessage(See.only(colonyPlayer),
new ModelMessage(ModelMessage.MessageType.COMBAT_RESULT,
"model.unit.goodsStolen",
colony, goods)
.addAmount("%amount%", goods.getAmount())
.add("%goods%", goods.getNameKey())
.addName("%colony%", colony.getName())
.addStringTemplate("%enemyNation%", attackerNation)
.addStringTemplate("%enemyUnit%", attacker.getLabel()));
} else {
int gold = colonyPlayer.getGold() / 10;
colonyPlayer.modifyGold(-gold);
attackerPlayer.modifyGold(gold);
cs.addMessage(See.only(colonyPlayer),
new ModelMessage(ModelMessage.MessageType.COMBAT_RESULT,
"model.unit.indianPlunder",
colony)
.addAmount("%amount%", gold)
.addName("%colony%", colony.getName())
.addStringTemplate("%enemyNation%", attackerNation)
.addStringTemplate("%enemyUnit%", attacker.getLabel()));
}
}
/**
* Promotes a unit.
*
* @param winner The <code>Unit</code> that won and should be promoted.
* @param loser The <code>Unit</code> that lost.
* @param cs A <code>ChangeSet</code> to update.
*/
private void csPromoteUnit(Unit winner, Unit loser, ChangeSet cs) {
ServerPlayer winnerPlayer = (ServerPlayer) winner.getOwner();
StringTemplate winnerNation = winnerPlayer.getNationName();
StringTemplate oldName = winner.getLabel();
UnitType type = winner.getTypeChange(ChangeType.PROMOTION,
winnerPlayer);
if (type == null || type == winner.getType()) {
logger.warning("Promotion failed, type="
+ ((type == null) ? "null"
: "same type: " + type));
return;
}
winner.setType(type);
cs.addMessage(See.only(winnerPlayer),
new ModelMessage(ModelMessage.MessageType.COMBAT_RESULT,
"model.unit.unitPromoted", winner)
.addStringTemplate("%oldName%", oldName)
.addStringTemplate("%unit%", winner.getLabel())
.addStringTemplate("%nation%", winnerNation));
}
/**
* Sinks all ships in a colony.
*
* @param attacker The attacker <code>Unit</code>.
* @param colony The <code>Colony</code> to sink ships in.
* @param cs A <code>ChangeSet</code> to update.
*/
private void csSinkColonyShips(Unit attacker, Colony colony, ChangeSet cs) {
List<Unit> units = new ArrayList<Unit>(colony.getTile().getUnitList());
while (!units.isEmpty()) {
Unit unit = units.remove(0);
if (unit.isNaval()) {
csSinkShipAttack(attacker, unit, cs);
}
}
}
/**
* Sinks this ship as result of a normal attack.
*
* @param attacker The attacker <code>Unit</code>.
* @param ship The naval <code>Unit</code> to sink.
* @param cs A <code>ChangeSet</code> to update.
*/
private void csSinkShipAttack(Unit attacker, Unit ship, ChangeSet cs) {
ServerPlayer shipPlayer = (ServerPlayer) ship.getOwner();
StringTemplate shipNation = ship.getApparentOwnerName();
Unit attackerUnit = (Unit) attacker;
ServerPlayer attackerPlayer = (ServerPlayer) attackerUnit.getOwner();
StringTemplate attackerNation = attackerUnit.getApparentOwnerName();
cs.addMessage(See.only(attackerPlayer),
new ModelMessage(ModelMessage.MessageType.COMBAT_RESULT,
"model.unit.enemyShipSunk",
attackerUnit)
.addStringTemplate("%unit%", attackerUnit.getLabel())
.addStringTemplate("%enemyUnit%", ship.getLabel())
.addStringTemplate("%enemyNation%", shipNation));
cs.addMessage(See.only(shipPlayer),
new ModelMessage(ModelMessage.MessageType.COMBAT_RESULT,
"model.unit.shipSunk",
ship.getTile())
.addStringTemplate("%unit%", ship.getLabel())
.addStringTemplate("%enemyUnit%", attackerUnit.getLabel())
.addStringTemplate("%enemyNation%", attackerNation));
csSinkShip(ship, attackerPlayer, cs);
}
/**
* Sinks this ship as result of a bombard.
*
* @param settlement The bombarding <code>Settlement</code>.
* @param ship The naval <code>Unit</code> to sink.
* @param cs A <code>ChangeSet</code> to update.
*/
private void csSinkShipBombard(Settlement settlement, Unit ship,
ChangeSet cs) {
ServerPlayer attackerPlayer = (ServerPlayer) settlement.getOwner();
ServerPlayer shipPlayer = (ServerPlayer) ship.getOwner();
StringTemplate shipNation = ship.getApparentOwnerName();
cs.addMessage(See.only(attackerPlayer),
new ModelMessage(ModelMessage.MessageType.COMBAT_RESULT,
"model.unit.shipSunkByBombardment",
settlement)
.addName("%colony%", settlement.getName())
.addStringTemplate("%unit%", ship.getLabel())
.addStringTemplate("%nation%", shipNation));
cs.addMessage(See.only(shipPlayer),
new ModelMessage(ModelMessage.MessageType.COMBAT_RESULT,
"model.unit.shipSunkByBombardment",
ship.getTile())
.addName("%colony%", settlement.getName())
.addStringTemplate("%unit%", ship.getLabel()));
csSinkShip(ship, attackerPlayer, cs);
}
/**
* Sink the ship.
*
* @param ship The naval <code>Unit</code> to sink.
* @param attackerPlayer The <code>ServerPlayer</code> that attacked.
* @param cs A <code>ChangeSet</code> to update.
*/
private void csSinkShip(Unit ship, ServerPlayer attackerPlayer,
ChangeSet cs) {
ServerPlayer shipPlayer = (ServerPlayer) ship.getOwner();
cs.addDispose(shipPlayer, ship.getLocation(), ship);
cs.addAttribute(See.only(attackerPlayer), "sound",
"sound.event.shipSunk");
}
/**
* Slaughter a unit.
*
* @param winner The <code>Unit</code> that is slaughtering.
* @param loser The <code>Unit</code> to slaughter.
* @param cs A <code>ChangeSet</code> to update.
*/
private void csSlaughterUnit(Unit winner, Unit loser, ChangeSet cs) {
ServerPlayer winnerPlayer = (ServerPlayer) winner.getOwner();
StringTemplate winnerNation = winnerPlayer.getNationName();
StringTemplate winnerLocation = winner.getLocation()
.getLocationNameFor(winnerPlayer);
ServerPlayer loserPlayer = (ServerPlayer) loser.getOwner();
StringTemplate loserNation = loserPlayer.getNationName();
StringTemplate loserLocation = loser.getLocation()
.getLocationNameFor(loserPlayer);
String messageId = loser.getType().getId() + ".destroyed";
cs.addMessage(See.only(winnerPlayer),
new ModelMessage(ModelMessage.MessageType.COMBAT_RESULT,
messageId, winner)
.setDefaultId("model.unit.unitSlaughtered")
.addStringTemplate("%nation%", loserNation)
.addStringTemplate("%unit%", loser.getLabel())
.addStringTemplate("%enemyNation%", winnerNation)
.addStringTemplate("%enemyUnit%", winner.getLabel())
.addStringTemplate("%location%", winnerLocation));
cs.addMessage(See.only(loserPlayer),
new ModelMessage(ModelMessage.MessageType.COMBAT_RESULT,
messageId, loser.getTile())
.setDefaultId("model.unit.unitSlaughtered")
.addStringTemplate("%nation%", loserNation)
.addStringTemplate("%unit%", loser.getLabel())
.addStringTemplate("%enemyNation%", winnerNation)
.addStringTemplate("%enemyUnit%", winner.getLabel())
.addStringTemplate("%location%", loserLocation));
if (loserPlayer.isIndian() && loserPlayer.checkForDeath()) {
StringTemplate nativeNation = loserPlayer.getNationName();
cs.addHistory(winnerPlayer,
new HistoryEvent(getGame().getTurn(),
HistoryEvent.EventType.DESTROY_NATION)
.addStringTemplate("%nation%", nativeNation));
}
// Transfer equipment, do not generate messages for the loser.
EquipmentType equip;
while ((equip = loser.getBestCombatEquipmentType(loser.getEquipment()))
!= null) {
loser.changeEquipment(equip, -loser.getEquipmentCount(equip));
csCaptureEquipment(winner, loser, equip, cs);
}
// Destroy unit.
cs.addDispose(loserPlayer, loser.getLocation(), loser);
}
@Override
public String toString() {
return "ServerPlayer[name=" + getName() + ",ID=" + getId()
+ ",conn=" + connection + "]";
}
/**
* Returns the tag name of the root element representing this object.
*
* @return "serverPlayer"
*/
public String getServerXMLElementTagName() {
return "serverPlayer";
}
}
| true | true | public void csCombat(FreeColGameObject attacker,
FreeColGameObject defender,
List<CombatResult> crs,
Random random,
ChangeSet cs) throws IllegalStateException {
CombatModel combatModel = getGame().getCombatModel();
boolean isAttack = combatModel.combatIsAttack(attacker, defender);
boolean isBombard = combatModel.combatIsBombard(attacker, defender);
Unit attackerUnit = null;
Settlement attackerSettlement = null;
Tile attackerTile = null;
Unit defenderUnit = null;
ServerPlayer defenderPlayer = null;
Tile defenderTile = null;
if (isAttack) {
attackerUnit = (Unit) attacker;
attackerTile = attackerUnit.getTile();
defenderUnit = (Unit) defender;
defenderPlayer = (ServerPlayer) defenderUnit.getOwner();
defenderTile = defenderUnit.getTile();
cs.addAttribute(See.only(this), "sound",
(attackerUnit.isNaval())
? "sound.attack.naval"
: (attackerUnit.hasAbility("model.ability.bombard"))
? "sound.attack.artillery"
: (attackerUnit.isMounted())
? "sound.attack.mounted"
: "sound.attack.foot");
} else if (isBombard) {
attackerSettlement = (Settlement) attacker;
attackerTile = attackerSettlement.getTile();
defenderUnit = (Unit) defender;
defenderPlayer = (ServerPlayer) defenderUnit.getOwner();
defenderTile = defenderUnit.getTile();
cs.addAttribute(See.only(this), "sound", "sound.attack.bombard");
} else {
throw new IllegalStateException("Bogus combat");
}
// If the combat results were not specified (usually the case),
// query the combat model.
if (crs == null) {
crs = combatModel.generateAttackResult(random, attacker, defender);
}
if (crs.isEmpty()) {
throw new IllegalStateException("empty attack result");
}
// Extract main result, insisting it is one of the fundamental cases,
// and add the animation.
// Set vis so that loser always sees things.
// TODO: Bombard animations
See vis; // Visibility that insists on the loser seeing the result.
CombatResult result = crs.remove(0);
switch (result) {
case NO_RESULT:
vis = See.perhaps();
break; // Do not animate if there is no result.
case WIN:
vis = See.perhaps().always(defenderPlayer);
if (isAttack) {
cs.addAttack(vis, attackerUnit, defenderUnit, true);
}
break;
case LOSE:
vis = See.perhaps().always(this);
if (isAttack) {
cs.addAttack(vis, attackerUnit, defenderUnit, false);
}
break;
default:
throw new IllegalStateException("generateAttackResult returned: "
+ result);
}
// Now process the details.
boolean attackerTileDirty = false;
boolean defenderTileDirty = false;
boolean moveAttacker = false;
boolean burnedNativeCapital = false;
Settlement settlement = defenderTile.getSettlement();
Colony colony = defenderTile.getColony();
IndianSettlement natives = (settlement instanceof IndianSettlement)
? (IndianSettlement) settlement
: null;
int attackerTension = 0;
int defenderTension = 0;
for (CombatResult cr : crs) {
boolean ok;
switch (cr) {
case AUTOEQUIP_UNIT:
ok = isAttack && settlement != null;
if (ok) {
csAutoequipUnit(defenderUnit, settlement, cs);
}
break;
case BURN_MISSIONS:
ok = isAttack && result == CombatResult.WIN
&& natives != null
&& isEuropean() && defenderPlayer.isIndian();
if (ok) {
defenderTileDirty |= natives.getMissionary(this) != null;
csBurnMissions(attackerUnit, natives, cs);
}
break;
case CAPTURE_AUTOEQUIP:
ok = isAttack && result == CombatResult.WIN
&& settlement != null
&& defenderPlayer.isEuropean();
if (ok) {
csCaptureAutoEquip(attackerUnit, defenderUnit, cs);
attackerTileDirty = defenderTileDirty = true;
}
break;
case CAPTURE_COLONY:
ok = isAttack && result == CombatResult.WIN
&& colony != null
&& isEuropean() && defenderPlayer.isEuropean();
if (ok) {
csCaptureColony(attackerUnit, colony, cs);
attackerTileDirty = defenderTileDirty = true;
moveAttacker = true;
defenderTension += Tension.TENSION_ADD_MAJOR;
}
break;
case CAPTURE_CONVERT:
ok = isAttack && result == CombatResult.WIN
&& natives != null
&& isEuropean() && defenderPlayer.isIndian();
if (ok) {
csCaptureConvert(attackerUnit, natives, random, cs);
attackerTileDirty = true;
}
break;
case CAPTURE_EQUIP:
ok = isAttack && result != CombatResult.NO_RESULT;
if (ok) {
if (result == CombatResult.WIN) {
csCaptureEquip(attackerUnit, defenderUnit, cs);
} else {
csCaptureEquip(defenderUnit, attackerUnit, cs);
}
attackerTileDirty = defenderTileDirty = true;
}
break;
case CAPTURE_UNIT:
ok = isAttack && result != CombatResult.NO_RESULT;
if (ok) {
if (result == CombatResult.WIN) {
csCaptureUnit(attackerUnit, defenderUnit, cs);
} else {
csCaptureUnit(defenderUnit, attackerUnit, cs);
}
attackerTileDirty = defenderTileDirty = true;
}
break;
case DAMAGE_COLONY_SHIPS:
ok = isAttack && result == CombatResult.WIN
&& colony != null;
if (ok) {
csDamageColonyShips(attackerUnit, colony, cs);
defenderTileDirty = true;
}
break;
case DAMAGE_SHIP_ATTACK:
ok = isAttack && result != CombatResult.NO_RESULT
&& ((result == CombatResult.WIN) ? defenderUnit
: attackerUnit).isNaval();
if (ok) {
if (result == CombatResult.WIN) {
csDamageShipAttack(attackerUnit, defenderUnit, cs);
defenderTileDirty = true;
} else {
csDamageShipAttack(defenderUnit, attackerUnit, cs);
attackerTileDirty = true;
}
}
break;
case DAMAGE_SHIP_BOMBARD:
ok = isBombard && result == CombatResult.WIN
&& defenderUnit.isNaval();
if (ok) {
csDamageShipBombard(attackerSettlement, defenderUnit, cs);
defenderTileDirty = true;
}
break;
case DEMOTE_UNIT:
ok = isAttack && result != CombatResult.NO_RESULT;
if (ok) {
if (result == CombatResult.WIN) {
csDemoteUnit(attackerUnit, defenderUnit, cs);
defenderTileDirty = true;
} else {
csDemoteUnit(defenderUnit, attackerUnit, cs);
attackerTileDirty = true;
}
}
break;
case DESTROY_COLONY:
ok = isAttack && result == CombatResult.WIN
&& colony != null
&& isIndian() && defenderPlayer.isEuropean();
if (ok) {
csDestroyColony(attackerUnit, colony, cs);
attackerTileDirty = defenderTileDirty = true;
moveAttacker = true;
attackerTension -= Tension.TENSION_ADD_NORMAL;
defenderTension += Tension.TENSION_ADD_MAJOR;
}
break;
case DESTROY_SETTLEMENT:
ok = isAttack && result == CombatResult.WIN
&& natives != null
&& defenderPlayer.isIndian();
if (ok) {
csDestroySettlement(attackerUnit, natives, random, cs);
attackerTileDirty = defenderTileDirty = true;
moveAttacker = true;
burnedNativeCapital = settlement.isCapital();
attackerTension -= Tension.TENSION_ADD_NORMAL;
if (!burnedNativeCapital) {
defenderTension += Tension.TENSION_ADD_MAJOR;
}
}
break;
case EVADE_ATTACK:
ok = isAttack && result == CombatResult.NO_RESULT
&& defenderUnit.isNaval();
if (ok) {
csEvadeAttack(attackerUnit, defenderUnit, cs);
}
break;
case EVADE_BOMBARD:
ok = isBombard && result == CombatResult.NO_RESULT
&& defenderUnit.isNaval();
if (ok) {
csEvadeBombard(attackerSettlement, defenderUnit, cs);
}
break;
case LOOT_SHIP:
ok = isAttack && result != CombatResult.NO_RESULT
&& attackerUnit.isNaval() && defenderUnit.isNaval();
if (ok) {
if (result == CombatResult.WIN) {
csLootShip(attackerUnit, defenderUnit, cs);
} else {
csLootShip(defenderUnit, attackerUnit, cs);
}
}
break;
case LOSE_AUTOEQUIP:
ok = isAttack && result == CombatResult.WIN
&& settlement != null
&& defenderPlayer.isEuropean();
if (ok) {
csLoseAutoEquip(attackerUnit, defenderUnit, cs);
defenderTileDirty = true;
}
break;
case LOSE_EQUIP:
ok = isAttack && result != CombatResult.NO_RESULT;
if (ok) {
if (result == CombatResult.WIN) {
csLoseEquip(attackerUnit, defenderUnit, cs);
defenderTileDirty = true;
} else {
csLoseEquip(defenderUnit, attackerUnit, cs);
attackerTileDirty = true;
}
}
break;
case PILLAGE_COLONY:
ok = isAttack && result == CombatResult.WIN
&& colony != null
&& isIndian() && defenderPlayer.isEuropean();
if (ok) {
csPillageColony(attackerUnit, colony, random, cs);
defenderTileDirty = true;
attackerTension -= Tension.TENSION_ADD_NORMAL;
}
break;
case PROMOTE_UNIT:
ok = isAttack && result != CombatResult.NO_RESULT;
if (ok) {
if (result == CombatResult.WIN) {
csPromoteUnit(attackerUnit, defenderUnit, cs);
attackerTileDirty = true;
} else {
csPromoteUnit(defenderUnit, attackerUnit, cs);
defenderTileDirty = true;
}
}
break;
case SINK_COLONY_SHIPS:
ok = isAttack && result == CombatResult.WIN
&& colony != null;
if (ok) {
csSinkColonyShips(attackerUnit, colony, cs);
defenderTileDirty = true;
}
break;
case SINK_SHIP_ATTACK:
ok = isAttack && result != CombatResult.NO_RESULT
&& ((result == CombatResult.WIN) ? defenderUnit
: attackerUnit).isNaval();
if (ok) {
if (result == CombatResult.WIN) {
csSinkShipAttack(attackerUnit, defenderUnit, cs);
defenderTileDirty = true;
} else {
csSinkShipAttack(defenderUnit, attackerUnit, cs);
attackerTileDirty = true;
}
}
break;
case SINK_SHIP_BOMBARD:
ok = isBombard && result == CombatResult.WIN
&& defenderUnit.isNaval();
if (ok) {
csSinkShipBombard(attackerSettlement, defenderUnit, cs);
defenderTileDirty = true;
}
break;
case SLAUGHTER_UNIT:
ok = isAttack && result != CombatResult.NO_RESULT;
if (ok) {
if (result == CombatResult.WIN) {
csSlaughterUnit(attackerUnit, defenderUnit, cs);
defenderTileDirty = true;
attackerTension -= Tension.TENSION_ADD_NORMAL;
defenderTension += getSlaughterTension(defenderUnit);
} else {
csSlaughterUnit(defenderUnit, attackerUnit, cs);
attackerTileDirty = true;
attackerTension += getSlaughterTension(attackerUnit);
defenderTension -= Tension.TENSION_ADD_NORMAL;
}
}
break;
default:
ok = false;
break;
}
if (!ok) {
throw new IllegalStateException("Attack (result=" + result
+ ") has bogus subresult: "
+ cr);
}
}
// Handle stance and tension.
// - Privateers do not provoke stance changes but can set the
// attackedByPrivateers flag
// - Attacks among Europeans imply war
// - Burning of a native capital results in surrender
// - Other attacks involving natives do not imply war, but
// changes in Tension can drive Stance, however this is
// decided by the native AI in their turn so just adjust tension.
if (attacker.hasAbility("model.ability.piracy")) {
if (!defenderPlayer.getAttackedByPrivateers()) {
defenderPlayer.setAttackedByPrivateers(true);
cs.addPartial(See.only(defenderPlayer), defenderPlayer,
"attackedByPrivateers");
}
} else if (defender.hasAbility("model.ability.piracy")) {
; // do nothing
} else if (isEuropean() && defenderPlayer.isEuropean()) {
csChangeStance(Stance.WAR, defenderPlayer, true, cs);
} else if (burnedNativeCapital) {
csChangeStance(Stance.PEACE, defenderPlayer, true, cs);
defenderPlayer.getTension(this).setValue(Tension.SURRENDERED);
for (IndianSettlement is : defenderPlayer.getIndianSettlements()) {
is.getAlarm(this).setValue(Tension.SURRENDERED);
cs.add(See.perhaps(), is);
}
} else { // At least one player is non-European
if (isEuropean()) {
csChangeStance(Stance.WAR, defenderPlayer, false, cs);
} else if (isIndian()) {
if (result == CombatResult.WIN) {
attackerTension -= Tension.TENSION_ADD_MINOR;
} else if (result == CombatResult.LOSE) {
attackerTension += Tension.TENSION_ADD_MINOR;
}
}
if (defenderPlayer.isEuropean()) {
defenderPlayer.csChangeStance(Stance.WAR, this, false, cs);
} else if (defenderPlayer.isIndian()) {
if (result == CombatResult.WIN) {
defenderTension += Tension.TENSION_ADD_MINOR;
} else if (result == CombatResult.LOSE) {
defenderTension -= Tension.TENSION_ADD_MINOR;
}
}
if (attackerTension != 0) {
cs.add(See.only(null).perhaps(defenderPlayer),
modifyTension(defenderPlayer, attackerTension));
}
if (defenderTension != 0) {
cs.add(See.only(null).perhaps(this),
defenderPlayer.modifyTension(this, defenderTension));
}
}
// Move the attacker if required.
if (moveAttacker) {
attackerUnit.setMovesLeft(attackerUnit.getInitialMovesLeft());
((ServerUnit) attackerUnit).csMove(defenderTile, random, cs);
// Move adds in updates for the tiles, but...
attackerTileDirty = defenderTileDirty = false;
// ...with visibility of perhaps().
// Thus the defender might see the change,
// but because its settlement is gone it also might not.
// So add in another defender-specific update.
// The worst that can happen is a duplicate update.
cs.add(See.only(defenderPlayer), defenderTile);
} else if (isAttack) {
// The Revenger unit can attack multiple times, so spend
// at least the eventual cost of moving to the tile.
// Other units consume the entire move.
if (attacker.hasAbility("model.ability.multipleAttacks")) {
int movecost = attackerUnit.getMoveCost(defenderTile);
attackerUnit.setMovesLeft(attackerUnit.getMovesLeft()
- movecost);
} else {
attackerUnit.setMovesLeft(0);
}
if (!attackerTileDirty) {
cs.addPartial(See.only(this), attacker, "movesLeft");
}
}
// Make sure we always update the attacker and defender tile
// if it is not already done yet.
if (attackerTileDirty) cs.add(vis, attackerTile);
if (defenderTileDirty) cs.add(vis, defenderTile);
}
| public void csCombat(FreeColGameObject attacker,
FreeColGameObject defender,
List<CombatResult> crs,
Random random,
ChangeSet cs) throws IllegalStateException {
CombatModel combatModel = getGame().getCombatModel();
boolean isAttack = combatModel.combatIsAttack(attacker, defender);
boolean isBombard = combatModel.combatIsBombard(attacker, defender);
Unit attackerUnit = null;
Settlement attackerSettlement = null;
Tile attackerTile = null;
Unit defenderUnit = null;
ServerPlayer defenderPlayer = null;
Tile defenderTile = null;
if (isAttack) {
attackerUnit = (Unit) attacker;
attackerTile = attackerUnit.getTile();
defenderUnit = (Unit) defender;
defenderPlayer = (ServerPlayer) defenderUnit.getOwner();
defenderTile = defenderUnit.getTile();
cs.addAttribute(See.only(this), "sound",
(attackerUnit.isNaval())
? "sound.attack.naval"
: (attackerUnit.hasAbility("model.ability.bombard"))
? "sound.attack.artillery"
: (attackerUnit.isMounted())
? "sound.attack.mounted"
: "sound.attack.foot");
} else if (isBombard) {
attackerSettlement = (Settlement) attacker;
attackerTile = attackerSettlement.getTile();
defenderUnit = (Unit) defender;
defenderPlayer = (ServerPlayer) defenderUnit.getOwner();
defenderTile = defenderUnit.getTile();
cs.addAttribute(See.only(this), "sound", "sound.attack.bombard");
} else {
throw new IllegalStateException("Bogus combat");
}
// If the combat results were not specified (usually the case),
// query the combat model.
if (crs == null) {
crs = combatModel.generateAttackResult(random, attacker, defender);
}
if (crs.isEmpty()) {
throw new IllegalStateException("empty attack result");
}
// Extract main result, insisting it is one of the fundamental cases,
// and add the animation.
// Set vis so that loser always sees things.
// TODO: Bombard animations
See vis; // Visibility that insists on the loser seeing the result.
CombatResult result = crs.remove(0);
switch (result) {
case NO_RESULT:
vis = See.perhaps();
break; // Do not animate if there is no result.
case WIN:
vis = See.perhaps().always(defenderPlayer);
if (isAttack) {
cs.addAttack(vis, attackerUnit, defenderUnit, true);
}
break;
case LOSE:
vis = See.perhaps().always(this);
if (isAttack) {
cs.addAttack(vis, attackerUnit, defenderUnit, false);
}
break;
default:
throw new IllegalStateException("generateAttackResult returned: "
+ result);
}
// Now process the details.
boolean attackerTileDirty = false;
boolean defenderTileDirty = false;
boolean moveAttacker = false;
boolean burnedNativeCapital = false;
Settlement settlement = defenderTile.getSettlement();
Colony colony = defenderTile.getColony();
IndianSettlement natives = (settlement instanceof IndianSettlement)
? (IndianSettlement) settlement
: null;
int attackerTension = 0;
int defenderTension = 0;
for (CombatResult cr : crs) {
boolean ok;
switch (cr) {
case AUTOEQUIP_UNIT:
ok = isAttack && settlement != null;
if (ok) {
csAutoequipUnit(defenderUnit, settlement, cs);
}
break;
case BURN_MISSIONS:
ok = isAttack && result == CombatResult.WIN
&& natives != null
&& isEuropean() && defenderPlayer.isIndian();
if (ok) {
defenderTileDirty |= natives.getMissionary(this) != null;
csBurnMissions(attackerUnit, natives, cs);
}
break;
case CAPTURE_AUTOEQUIP:
ok = isAttack && result == CombatResult.WIN
&& settlement != null
&& defenderPlayer.isEuropean();
if (ok) {
csCaptureAutoEquip(attackerUnit, defenderUnit, cs);
attackerTileDirty = defenderTileDirty = true;
}
break;
case CAPTURE_COLONY:
ok = isAttack && result == CombatResult.WIN
&& colony != null
&& isEuropean() && defenderPlayer.isEuropean();
if (ok) {
csCaptureColony(attackerUnit, colony, cs);
attackerTileDirty = defenderTileDirty = true;
moveAttacker = true;
defenderTension += Tension.TENSION_ADD_MAJOR;
}
break;
case CAPTURE_CONVERT:
ok = isAttack && result == CombatResult.WIN
&& natives != null
&& isEuropean() && defenderPlayer.isIndian();
if (ok) {
csCaptureConvert(attackerUnit, natives, random, cs);
attackerTileDirty = true;
}
break;
case CAPTURE_EQUIP:
ok = isAttack && result != CombatResult.NO_RESULT;
if (ok) {
if (result == CombatResult.WIN) {
csCaptureEquip(attackerUnit, defenderUnit, cs);
} else {
csCaptureEquip(defenderUnit, attackerUnit, cs);
}
attackerTileDirty = defenderTileDirty = true;
}
break;
case CAPTURE_UNIT:
ok = isAttack && result != CombatResult.NO_RESULT;
if (ok) {
if (result == CombatResult.WIN) {
csCaptureUnit(attackerUnit, defenderUnit, cs);
} else {
csCaptureUnit(defenderUnit, attackerUnit, cs);
}
attackerTileDirty = defenderTileDirty = true;
}
break;
case DAMAGE_COLONY_SHIPS:
ok = isAttack && result == CombatResult.WIN
&& colony != null;
if (ok) {
csDamageColonyShips(attackerUnit, colony, cs);
defenderTileDirty = true;
}
break;
case DAMAGE_SHIP_ATTACK:
ok = isAttack && result != CombatResult.NO_RESULT
&& ((result == CombatResult.WIN) ? defenderUnit
: attackerUnit).isNaval();
if (ok) {
if (result == CombatResult.WIN) {
csDamageShipAttack(attackerUnit, defenderUnit, cs);
defenderTileDirty = true;
} else {
csDamageShipAttack(defenderUnit, attackerUnit, cs);
attackerTileDirty = true;
}
}
break;
case DAMAGE_SHIP_BOMBARD:
ok = isBombard && result == CombatResult.WIN
&& defenderUnit.isNaval();
if (ok) {
csDamageShipBombard(attackerSettlement, defenderUnit, cs);
defenderTileDirty = true;
}
break;
case DEMOTE_UNIT:
ok = isAttack && result != CombatResult.NO_RESULT;
if (ok) {
if (result == CombatResult.WIN) {
csDemoteUnit(attackerUnit, defenderUnit, cs);
defenderTileDirty = true;
} else {
csDemoteUnit(defenderUnit, attackerUnit, cs);
attackerTileDirty = true;
}
}
break;
case DESTROY_COLONY:
ok = isAttack && result == CombatResult.WIN
&& colony != null
&& isIndian() && defenderPlayer.isEuropean();
if (ok) {
csDestroyColony(attackerUnit, colony, cs);
attackerTileDirty = defenderTileDirty = true;
moveAttacker = true;
attackerTension -= Tension.TENSION_ADD_NORMAL;
defenderTension += Tension.TENSION_ADD_MAJOR;
}
break;
case DESTROY_SETTLEMENT:
ok = isAttack && result == CombatResult.WIN
&& natives != null
&& defenderPlayer.isIndian();
if (ok) {
csDestroySettlement(attackerUnit, natives, random, cs);
attackerTileDirty = defenderTileDirty = true;
moveAttacker = true;
burnedNativeCapital = settlement.isCapital();
attackerTension -= Tension.TENSION_ADD_NORMAL;
if (!burnedNativeCapital) {
defenderTension += Tension.TENSION_ADD_MAJOR;
}
}
break;
case EVADE_ATTACK:
ok = isAttack && result == CombatResult.NO_RESULT
&& defenderUnit.isNaval();
if (ok) {
csEvadeAttack(attackerUnit, defenderUnit, cs);
}
break;
case EVADE_BOMBARD:
ok = isBombard && result == CombatResult.NO_RESULT
&& defenderUnit.isNaval();
if (ok) {
csEvadeBombard(attackerSettlement, defenderUnit, cs);
}
break;
case LOOT_SHIP:
ok = isAttack && result != CombatResult.NO_RESULT
&& attackerUnit.isNaval() && defenderUnit.isNaval();
if (ok) {
if (result == CombatResult.WIN) {
csLootShip(attackerUnit, defenderUnit, cs);
} else {
csLootShip(defenderUnit, attackerUnit, cs);
}
}
break;
case LOSE_AUTOEQUIP:
ok = isAttack && result == CombatResult.WIN
&& settlement != null
&& defenderPlayer.isEuropean();
if (ok) {
csLoseAutoEquip(attackerUnit, defenderUnit, cs);
defenderTileDirty = true;
}
break;
case LOSE_EQUIP:
ok = isAttack && result != CombatResult.NO_RESULT;
if (ok) {
if (result == CombatResult.WIN) {
csLoseEquip(attackerUnit, defenderUnit, cs);
defenderTileDirty = true;
} else {
csLoseEquip(defenderUnit, attackerUnit, cs);
attackerTileDirty = true;
}
}
break;
case PILLAGE_COLONY:
ok = isAttack && result == CombatResult.WIN
&& colony != null
&& isIndian() && defenderPlayer.isEuropean();
if (ok) {
csPillageColony(attackerUnit, colony, random, cs);
defenderTileDirty = true;
attackerTension -= Tension.TENSION_ADD_NORMAL;
}
break;
case PROMOTE_UNIT:
ok = isAttack && result != CombatResult.NO_RESULT;
if (ok) {
if (result == CombatResult.WIN) {
csPromoteUnit(attackerUnit, defenderUnit, cs);
attackerTileDirty = true;
} else {
csPromoteUnit(defenderUnit, attackerUnit, cs);
defenderTileDirty = true;
}
}
break;
case SINK_COLONY_SHIPS:
ok = isAttack && result == CombatResult.WIN
&& colony != null;
if (ok) {
csSinkColonyShips(attackerUnit, colony, cs);
defenderTileDirty = true;
}
break;
case SINK_SHIP_ATTACK:
ok = isAttack && result != CombatResult.NO_RESULT
&& ((result == CombatResult.WIN) ? defenderUnit
: attackerUnit).isNaval();
if (ok) {
if (result == CombatResult.WIN) {
csSinkShipAttack(attackerUnit, defenderUnit, cs);
defenderTileDirty = true;
} else {
csSinkShipAttack(defenderUnit, attackerUnit, cs);
attackerTileDirty = true;
}
}
break;
case SINK_SHIP_BOMBARD:
ok = isBombard && result == CombatResult.WIN
&& defenderUnit.isNaval();
if (ok) {
csSinkShipBombard(attackerSettlement, defenderUnit, cs);
defenderTileDirty = true;
}
break;
case SLAUGHTER_UNIT:
ok = isAttack && result != CombatResult.NO_RESULT;
if (ok) {
if (result == CombatResult.WIN) {
csSlaughterUnit(attackerUnit, defenderUnit, cs);
defenderTileDirty = true;
attackerTension -= Tension.TENSION_ADD_NORMAL;
defenderTension += getSlaughterTension(defenderUnit);
} else {
csSlaughterUnit(defenderUnit, attackerUnit, cs);
attackerTileDirty = true;
attackerTension += getSlaughterTension(attackerUnit);
defenderTension -= Tension.TENSION_ADD_NORMAL;
}
}
break;
default:
ok = false;
break;
}
if (!ok) {
throw new IllegalStateException("Attack (result=" + result
+ ") has bogus subresult: "
+ cr);
}
}
// Handle stance and tension.
// - Privateers do not provoke stance changes but can set the
// attackedByPrivateers flag
// - Attacks among Europeans imply war
// - Burning of a native capital results in surrender
// - Other attacks involving natives do not imply war, but
// changes in Tension can drive Stance, however this is
// decided by the native AI in their turn so just adjust tension.
if (attacker.hasAbility("model.ability.piracy")) {
if (!defenderPlayer.getAttackedByPrivateers()) {
defenderPlayer.setAttackedByPrivateers(true);
cs.addPartial(See.only(defenderPlayer), defenderPlayer,
"attackedByPrivateers");
}
} else if (defender.hasAbility("model.ability.piracy")) {
; // do nothing
} else if (isEuropean() && defenderPlayer.isEuropean()) {
csChangeStance(Stance.WAR, defenderPlayer, true, cs);
} else if (burnedNativeCapital) {
csChangeStance(Stance.PEACE, defenderPlayer, true, cs);
defenderPlayer.getTension(this).setValue(Tension.SURRENDERED);
for (IndianSettlement is : defenderPlayer.getIndianSettlements()) {
is.getAlarm(this).setValue(Tension.SURRENDERED);
cs.add(See.perhaps(), is);
}
} else { // At least one player is non-European
if (isEuropean()) {
csChangeStance(Stance.WAR, defenderPlayer, false, cs);
} else if (isIndian()) {
if (result == CombatResult.WIN) {
attackerTension -= Tension.TENSION_ADD_MINOR;
} else if (result == CombatResult.LOSE) {
attackerTension += Tension.TENSION_ADD_MINOR;
}
}
if (defenderPlayer.isEuropean()) {
defenderPlayer.csChangeStance(Stance.WAR, this, false, cs);
} else if (defenderPlayer.isIndian()) {
if (result == CombatResult.WIN) {
defenderTension += Tension.TENSION_ADD_MINOR;
} else if (result == CombatResult.LOSE) {
defenderTension -= Tension.TENSION_ADD_MINOR;
}
}
if (attackerTension != 0) {
cs.add(See.only(null).perhaps(defenderPlayer),
modifyTension(defenderPlayer, attackerTension));
}
if (defenderTension != 0) {
cs.add(See.only(null).perhaps(this),
defenderPlayer.modifyTension(this, defenderTension));
}
}
// Move the attacker if required.
if (moveAttacker) {
attackerUnit.setMovesLeft(attackerUnit.getInitialMovesLeft());
((ServerUnit) attackerUnit).csMove(defenderTile, random, cs);
attackerUnit.setMovesLeft(0);
// Move adds in updates for the tiles, but...
attackerTileDirty = defenderTileDirty = false;
// ...with visibility of perhaps().
// Thus the defender might see the change,
// but because its settlement is gone it also might not.
// So add in another defender-specific update.
// The worst that can happen is a duplicate update.
cs.add(See.only(defenderPlayer), defenderTile);
} else if (isAttack) {
// The Revenger unit can attack multiple times, so spend
// at least the eventual cost of moving to the tile.
// Other units consume the entire move.
if (attacker.hasAbility("model.ability.multipleAttacks")) {
int movecost = attackerUnit.getMoveCost(defenderTile);
attackerUnit.setMovesLeft(attackerUnit.getMovesLeft()
- movecost);
} else {
attackerUnit.setMovesLeft(0);
}
if (!attackerTileDirty) {
cs.addPartial(See.only(this), attacker, "movesLeft");
}
}
// Make sure we always update the attacker and defender tile
// if it is not already done yet.
if (attackerTileDirty) cs.add(vis, attackerTile);
if (defenderTileDirty) cs.add(vis, defenderTile);
}
|
diff --git a/jsf/tests/org.jboss.tools.jsf.vpe.jsf.test/src/org/jboss/tools/jsf/vpe/jsf/test/jbide/JBIDE1494Test.java b/jsf/tests/org.jboss.tools.jsf.vpe.jsf.test/src/org/jboss/tools/jsf/vpe/jsf/test/jbide/JBIDE1494Test.java
index 502e2741a..1c7c73acf 100644
--- a/jsf/tests/org.jboss.tools.jsf.vpe.jsf.test/src/org/jboss/tools/jsf/vpe/jsf/test/jbide/JBIDE1494Test.java
+++ b/jsf/tests/org.jboss.tools.jsf.vpe.jsf.test/src/org/jboss/tools/jsf/vpe/jsf/test/jbide/JBIDE1494Test.java
@@ -1,105 +1,105 @@
/*******************************************************************************
* 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 java.util.HashSet;
import java.util.Set;
import org.eclipse.core.resources.IFile;
import org.eclipse.swt.custom.StyledText;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.part.FileEditorInput;
import org.eclipse.wst.sse.ui.internal.contentassist.ContentAssistUtils;
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;
import org.jboss.tools.vpe.editor.VpeController;
import org.jboss.tools.vpe.editor.template.VpeTemplate;
import org.jboss.tools.vpe.editor.template.VpeTemplateManager;
import org.w3c.dom.Node;
/**
* @author mareshkau
*
*/
public class JBIDE1494Test extends VpeTest{
private static final String TEST_PAGE_NAME = "JBIDE/1494/JBIDE-1494.xhtml"; //$NON-NLS-1$
public JBIDE1494Test(String name) {
super(name);
}
public void testJBIDE1494() throws Throwable {
// wait
TestUtil.waitForJobs();
// set exception
setException(null);
// Tests CA
// get test page path
IFile file = (IFile) TestUtil.getComponentPath(TEST_PAGE_NAME,
JsfAllTests.IMPORT_PROJECT_NAME);
assertNotNull("Could not open specified file " + TEST_PAGE_NAME, file); //$NON-NLS-1$
IEditorInput input = new FileEditorInput(file);
assertNotNull("Editor input is null", input); //$NON-NLS-1$
// open and get editor
JSPMultiPageEditor part = openEditor(input);
StyledText styledText = part.getSourceEditor().getTextViewer()
.getTextWidget();
styledText.setCaretOffset(424);
Node h_outputText = (Node) ContentAssistUtils.getNodeAt(part
.getSourceEditor().getTextViewer(), 424);
assertNotNull(h_outputText);
VpeController vpeController = TestUtil.getVpeController(part);
VpeTemplateManager templateManager= vpeController.getPageContext().getVisualBuilder().getTemplateManager();
assertNotNull(templateManager);
Set<?> dependencySet = new HashSet();
VpeTemplate h_output_template = templateManager.getTemplate(vpeController.getPageContext(),h_outputText, dependencySet);
assertNotNull(h_output_template.getTextFormattingData());
//text formating for h:output
- assertEquals(7,h_output_template.getTextFormattingData().getAllFormatData().length);
+ assertEquals(8, h_output_template.getTextFormattingData().getAllFormatData().length);
Node h_dataTable = (Node) ContentAssistUtils.getNodeAt(part
.getSourceEditor().getTextViewer(), 473);
assertNotNull(h_dataTable);
dependencySet=new HashSet();
VpeTemplate h_data_Table = templateManager.getTemplate(vpeController.getPageContext(),h_dataTable , dependencySet);
assertNotNull(h_data_Table.getTextFormattingData());
- assertEquals(8,h_data_Table.getTextFormattingData().getAllFormatData().length);
+ assertEquals(9, h_data_Table.getTextFormattingData().getAllFormatData().length);
Node span =(Node) ContentAssistUtils.getNodeAt(part
.getSourceEditor().getTextViewer(), 615);
dependencySet=new HashSet();
VpeTemplate spanTemplate = templateManager.getTemplate(vpeController.getPageContext(),span, dependencySet);
assertNotNull(spanTemplate);
- assertEquals(10,spanTemplate.getTextFormattingData().getAllFormatData().length);
+ assertEquals(11,spanTemplate.getTextFormattingData().getAllFormatData().length);
}
}
| false | true | public void testJBIDE1494() throws Throwable {
// wait
TestUtil.waitForJobs();
// set exception
setException(null);
// Tests CA
// get test page path
IFile file = (IFile) TestUtil.getComponentPath(TEST_PAGE_NAME,
JsfAllTests.IMPORT_PROJECT_NAME);
assertNotNull("Could not open specified file " + TEST_PAGE_NAME, file); //$NON-NLS-1$
IEditorInput input = new FileEditorInput(file);
assertNotNull("Editor input is null", input); //$NON-NLS-1$
// open and get editor
JSPMultiPageEditor part = openEditor(input);
StyledText styledText = part.getSourceEditor().getTextViewer()
.getTextWidget();
styledText.setCaretOffset(424);
Node h_outputText = (Node) ContentAssistUtils.getNodeAt(part
.getSourceEditor().getTextViewer(), 424);
assertNotNull(h_outputText);
VpeController vpeController = TestUtil.getVpeController(part);
VpeTemplateManager templateManager= vpeController.getPageContext().getVisualBuilder().getTemplateManager();
assertNotNull(templateManager);
Set<?> dependencySet = new HashSet();
VpeTemplate h_output_template = templateManager.getTemplate(vpeController.getPageContext(),h_outputText, dependencySet);
assertNotNull(h_output_template.getTextFormattingData());
//text formating for h:output
assertEquals(7,h_output_template.getTextFormattingData().getAllFormatData().length);
Node h_dataTable = (Node) ContentAssistUtils.getNodeAt(part
.getSourceEditor().getTextViewer(), 473);
assertNotNull(h_dataTable);
dependencySet=new HashSet();
VpeTemplate h_data_Table = templateManager.getTemplate(vpeController.getPageContext(),h_dataTable , dependencySet);
assertNotNull(h_data_Table.getTextFormattingData());
assertEquals(8,h_data_Table.getTextFormattingData().getAllFormatData().length);
Node span =(Node) ContentAssistUtils.getNodeAt(part
.getSourceEditor().getTextViewer(), 615);
dependencySet=new HashSet();
VpeTemplate spanTemplate = templateManager.getTemplate(vpeController.getPageContext(),span, dependencySet);
assertNotNull(spanTemplate);
assertEquals(10,spanTemplate.getTextFormattingData().getAllFormatData().length);
}
| public void testJBIDE1494() throws Throwable {
// wait
TestUtil.waitForJobs();
// set exception
setException(null);
// Tests CA
// get test page path
IFile file = (IFile) TestUtil.getComponentPath(TEST_PAGE_NAME,
JsfAllTests.IMPORT_PROJECT_NAME);
assertNotNull("Could not open specified file " + TEST_PAGE_NAME, file); //$NON-NLS-1$
IEditorInput input = new FileEditorInput(file);
assertNotNull("Editor input is null", input); //$NON-NLS-1$
// open and get editor
JSPMultiPageEditor part = openEditor(input);
StyledText styledText = part.getSourceEditor().getTextViewer()
.getTextWidget();
styledText.setCaretOffset(424);
Node h_outputText = (Node) ContentAssistUtils.getNodeAt(part
.getSourceEditor().getTextViewer(), 424);
assertNotNull(h_outputText);
VpeController vpeController = TestUtil.getVpeController(part);
VpeTemplateManager templateManager= vpeController.getPageContext().getVisualBuilder().getTemplateManager();
assertNotNull(templateManager);
Set<?> dependencySet = new HashSet();
VpeTemplate h_output_template = templateManager.getTemplate(vpeController.getPageContext(),h_outputText, dependencySet);
assertNotNull(h_output_template.getTextFormattingData());
//text formating for h:output
assertEquals(8, h_output_template.getTextFormattingData().getAllFormatData().length);
Node h_dataTable = (Node) ContentAssistUtils.getNodeAt(part
.getSourceEditor().getTextViewer(), 473);
assertNotNull(h_dataTable);
dependencySet=new HashSet();
VpeTemplate h_data_Table = templateManager.getTemplate(vpeController.getPageContext(),h_dataTable , dependencySet);
assertNotNull(h_data_Table.getTextFormattingData());
assertEquals(9, h_data_Table.getTextFormattingData().getAllFormatData().length);
Node span =(Node) ContentAssistUtils.getNodeAt(part
.getSourceEditor().getTextViewer(), 615);
dependencySet=new HashSet();
VpeTemplate spanTemplate = templateManager.getTemplate(vpeController.getPageContext(),span, dependencySet);
assertNotNull(spanTemplate);
assertEquals(11,spanTemplate.getTextFormattingData().getAllFormatData().length);
}
|
diff --git a/src/com/android/phone/DataUsageListener.java b/src/com/android/phone/DataUsageListener.java
index 6122a8ec..a72c088a 100644
--- a/src/com/android/phone/DataUsageListener.java
+++ b/src/com/android/phone/DataUsageListener.java
@@ -1,231 +1,233 @@
/*
* 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.phone;
import com.android.phone.R;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.preference.Preference;
import android.preference.PreferenceActivity;
import android.preference.PreferenceScreen;
import android.net.Uri;
import android.net.ThrottleManager;
import android.util.Log;
import java.util.Calendar;
import java.util.GregorianCalendar;
import java.text.DateFormat;
/**
* Listener for broadcasts from ThrottleManager
*/
public class DataUsageListener {
private ThrottleManager mThrottleManager;
private Preference mCurrentUsagePref = null;
private Preference mTimeFramePref = null;
private Preference mThrottleRatePref = null;
private Preference mSummaryPref = null;
private PreferenceScreen mPrefScreen = null;
private boolean mSummaryPrefEnabled = false;
private final Context mContext;
private IntentFilter mFilter;
private BroadcastReceiver mReceiver;
private int mPolicyThrottleValue; //in kbps
private long mPolicyThreshold;
private int mCurrentThrottleRate;
private long mDataUsed;
private Calendar mStart;
private Calendar mEnd;
public DataUsageListener(Context context, Preference summary, PreferenceScreen prefScreen) {
mContext = context;
mSummaryPref = summary;
mPrefScreen = prefScreen;
mSummaryPrefEnabled = true;
initialize();
}
public DataUsageListener(Context context, Preference currentUsage,
Preference timeFrame, Preference throttleRate) {
mContext = context;
mCurrentUsagePref = currentUsage;
mTimeFramePref = timeFrame;
mThrottleRatePref = throttleRate;
initialize();
}
private void initialize() {
mThrottleManager = (ThrottleManager) mContext.getSystemService(Context.THROTTLE_SERVICE);
mStart = GregorianCalendar.getInstance();
mEnd = GregorianCalendar.getInstance();
mFilter = new IntentFilter();
mFilter.addAction(ThrottleManager.THROTTLE_POLL_ACTION);
mFilter.addAction(ThrottleManager.THROTTLE_ACTION);
mFilter.addAction(ThrottleManager.POLICY_CHANGED_ACTION);
mReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
String action = intent.getAction();
if (ThrottleManager.THROTTLE_POLL_ACTION.equals(action)) {
updateUsageStats(intent.getLongExtra(ThrottleManager.EXTRA_CYCLE_READ, 0),
intent.getLongExtra(ThrottleManager.EXTRA_CYCLE_WRITE, 0),
intent.getLongExtra(ThrottleManager.EXTRA_CYCLE_START, 0),
intent.getLongExtra(ThrottleManager.EXTRA_CYCLE_END, 0));
} else if (ThrottleManager.POLICY_CHANGED_ACTION.equals(action)) {
updatePolicy();
} else if (ThrottleManager.THROTTLE_ACTION.equals(action)) {
updateThrottleRate(intent.getIntExtra(ThrottleManager.EXTRA_THROTTLE_LEVEL, -1));
}
}
};
}
void resume() {
mContext.registerReceiver(mReceiver, mFilter);
updatePolicy();
}
void pause() {
mContext.unregisterReceiver(mReceiver);
}
private void updatePolicy() {
/* Fetch values for default interface */
mPolicyThrottleValue = mThrottleManager.getCliffLevel(null, 1);
mPolicyThreshold = mThrottleManager.getCliffThreshold(null, 1);
if (mSummaryPref != null) { /* Settings preference */
/**
* Remove data usage preference in settings
* if policy change disables throttling
*/
if (mPolicyThreshold == 0) {
if (mSummaryPrefEnabled) {
mPrefScreen.removePreference(mSummaryPref);
mSummaryPrefEnabled = false;
}
} else {
if (!mSummaryPrefEnabled) {
mSummaryPrefEnabled = true;
mPrefScreen.addPreference(mSummaryPref);
}
}
}
updateUI();
}
private void updateThrottleRate(int throttleRate) {
mCurrentThrottleRate = throttleRate;
updateUI();
}
private void updateUsageStats(long readByteCount, long writeByteCount,
long startTime, long endTime) {
mDataUsed = readByteCount + writeByteCount;
mStart.setTimeInMillis(startTime);
mEnd.setTimeInMillis(endTime);
updateUI();
}
private void updateUI() {
if (mPolicyThreshold == 0)
return;
int dataUsedPercent = (int) ((mDataUsed * 100) / mPolicyThreshold);
long cycleTime = mEnd.getTimeInMillis() - mStart.getTimeInMillis();
long currentTime = GregorianCalendar.getInstance().getTimeInMillis()
- mStart.getTimeInMillis();
int cycleThroughPercent = (cycleTime == 0) ? 0 : (int) ((currentTime * 100) / cycleTime);
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(cycleTime - currentTime);
int daysLeft = cal.get(Calendar.DAY_OF_YEAR);
+ //cal.get() returns 365 for less than a day
+ if (daysLeft >= 365) daysLeft = 0;
if (mCurrentUsagePref != null) {
/* Update the UI based on whether we are in a throttled state */
if (mCurrentThrottleRate > 0) {
mCurrentUsagePref.setSummary(mContext.getString(
R.string.throttle_data_rate_reduced_subtext,
toReadable(mPolicyThreshold),
mCurrentThrottleRate));
} else {
mCurrentUsagePref.setSummary(mContext.getString(
R.string.throttle_data_usage_subtext,
toReadable(mDataUsed), dataUsedPercent, toReadable(mPolicyThreshold)));
}
}
if (mTimeFramePref != null) {
mTimeFramePref.setSummary(mContext.getString(R.string.throttle_time_frame_subtext,
cycleThroughPercent, daysLeft,
DateFormat.getDateInstance(DateFormat.SHORT).format(mEnd.getTime())));
}
if (mThrottleRatePref != null) {
mThrottleRatePref.setSummary(mContext.getString(R.string.throttle_rate_subtext,
mPolicyThrottleValue));
}
if (mSummaryPref != null && mSummaryPrefEnabled) {
/* Update the UI based on whether we are in a throttled state */
if (mCurrentThrottleRate > 0) {
mSummaryPref.setSummary(mContext.getString(
R.string.throttle_data_rate_reduced_subtext,
toReadable(mPolicyThreshold),
mCurrentThrottleRate));
} else {
mSummaryPref.setSummary(mContext.getString(R.string.throttle_status_subtext,
toReadable(mDataUsed),
dataUsedPercent,
toReadable(mPolicyThreshold),
daysLeft,
DateFormat.getDateInstance(DateFormat.SHORT).format(mEnd.getTime())));
}
}
}
private String toReadable (long data) {
long KB = 1024;
long MB = 1024 * KB;
long GB = 1024 * MB;
long TB = 1024 * GB;
String ret;
if (data < KB) {
ret = data + " bytes";
} else if (data < MB) {
ret = (data / KB) + " KB";
} else if (data < GB) {
ret = (data / MB) + " MB";
} else if (data < TB) {
ret = (data / GB) + " GB";
} else {
ret = (data / TB) + " TB";
}
return ret;
}
}
| true | true | private void updateUI() {
if (mPolicyThreshold == 0)
return;
int dataUsedPercent = (int) ((mDataUsed * 100) / mPolicyThreshold);
long cycleTime = mEnd.getTimeInMillis() - mStart.getTimeInMillis();
long currentTime = GregorianCalendar.getInstance().getTimeInMillis()
- mStart.getTimeInMillis();
int cycleThroughPercent = (cycleTime == 0) ? 0 : (int) ((currentTime * 100) / cycleTime);
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(cycleTime - currentTime);
int daysLeft = cal.get(Calendar.DAY_OF_YEAR);
if (mCurrentUsagePref != null) {
/* Update the UI based on whether we are in a throttled state */
if (mCurrentThrottleRate > 0) {
mCurrentUsagePref.setSummary(mContext.getString(
R.string.throttle_data_rate_reduced_subtext,
toReadable(mPolicyThreshold),
mCurrentThrottleRate));
} else {
mCurrentUsagePref.setSummary(mContext.getString(
R.string.throttle_data_usage_subtext,
toReadable(mDataUsed), dataUsedPercent, toReadable(mPolicyThreshold)));
}
}
if (mTimeFramePref != null) {
mTimeFramePref.setSummary(mContext.getString(R.string.throttle_time_frame_subtext,
cycleThroughPercent, daysLeft,
DateFormat.getDateInstance(DateFormat.SHORT).format(mEnd.getTime())));
}
if (mThrottleRatePref != null) {
mThrottleRatePref.setSummary(mContext.getString(R.string.throttle_rate_subtext,
mPolicyThrottleValue));
}
if (mSummaryPref != null && mSummaryPrefEnabled) {
/* Update the UI based on whether we are in a throttled state */
if (mCurrentThrottleRate > 0) {
mSummaryPref.setSummary(mContext.getString(
R.string.throttle_data_rate_reduced_subtext,
toReadable(mPolicyThreshold),
mCurrentThrottleRate));
} else {
mSummaryPref.setSummary(mContext.getString(R.string.throttle_status_subtext,
toReadable(mDataUsed),
dataUsedPercent,
toReadable(mPolicyThreshold),
daysLeft,
DateFormat.getDateInstance(DateFormat.SHORT).format(mEnd.getTime())));
}
}
}
| private void updateUI() {
if (mPolicyThreshold == 0)
return;
int dataUsedPercent = (int) ((mDataUsed * 100) / mPolicyThreshold);
long cycleTime = mEnd.getTimeInMillis() - mStart.getTimeInMillis();
long currentTime = GregorianCalendar.getInstance().getTimeInMillis()
- mStart.getTimeInMillis();
int cycleThroughPercent = (cycleTime == 0) ? 0 : (int) ((currentTime * 100) / cycleTime);
Calendar cal = Calendar.getInstance();
cal.setTimeInMillis(cycleTime - currentTime);
int daysLeft = cal.get(Calendar.DAY_OF_YEAR);
//cal.get() returns 365 for less than a day
if (daysLeft >= 365) daysLeft = 0;
if (mCurrentUsagePref != null) {
/* Update the UI based on whether we are in a throttled state */
if (mCurrentThrottleRate > 0) {
mCurrentUsagePref.setSummary(mContext.getString(
R.string.throttle_data_rate_reduced_subtext,
toReadable(mPolicyThreshold),
mCurrentThrottleRate));
} else {
mCurrentUsagePref.setSummary(mContext.getString(
R.string.throttle_data_usage_subtext,
toReadable(mDataUsed), dataUsedPercent, toReadable(mPolicyThreshold)));
}
}
if (mTimeFramePref != null) {
mTimeFramePref.setSummary(mContext.getString(R.string.throttle_time_frame_subtext,
cycleThroughPercent, daysLeft,
DateFormat.getDateInstance(DateFormat.SHORT).format(mEnd.getTime())));
}
if (mThrottleRatePref != null) {
mThrottleRatePref.setSummary(mContext.getString(R.string.throttle_rate_subtext,
mPolicyThrottleValue));
}
if (mSummaryPref != null && mSummaryPrefEnabled) {
/* Update the UI based on whether we are in a throttled state */
if (mCurrentThrottleRate > 0) {
mSummaryPref.setSummary(mContext.getString(
R.string.throttle_data_rate_reduced_subtext,
toReadable(mPolicyThreshold),
mCurrentThrottleRate));
} else {
mSummaryPref.setSummary(mContext.getString(R.string.throttle_status_subtext,
toReadable(mDataUsed),
dataUsedPercent,
toReadable(mPolicyThreshold),
daysLeft,
DateFormat.getDateInstance(DateFormat.SHORT).format(mEnd.getTime())));
}
}
}
|
diff --git a/org.eclipse.scout.rt.client.mobile/src/org/eclipse/scout/rt/client/mobile/navigation/BreadCrumb.java b/org.eclipse.scout.rt.client.mobile/src/org/eclipse/scout/rt/client/mobile/navigation/BreadCrumb.java
index 57e8cf5038..20f7c2d6e8 100644
--- a/org.eclipse.scout.rt.client.mobile/src/org/eclipse/scout/rt/client/mobile/navigation/BreadCrumb.java
+++ b/org.eclipse.scout.rt.client.mobile/src/org/eclipse/scout/rt/client/mobile/navigation/BreadCrumb.java
@@ -1,107 +1,109 @@
/*******************************************************************************
* Copyright (c) 2010 BSI Business Systems Integration AG.
* 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:
* BSI Business Systems Integration AG - initial API and implementation
******************************************************************************/
package org.eclipse.scout.rt.client.mobile.navigation;
import java.util.List;
import org.eclipse.scout.commons.StringUtility;
import org.eclipse.scout.commons.exception.ProcessingException;
import org.eclipse.scout.commons.logger.IScoutLogger;
import org.eclipse.scout.commons.logger.ScoutLogManager;
import org.eclipse.scout.rt.client.ClientJob;
import org.eclipse.scout.rt.client.mobile.ui.desktop.MobileDesktopUtility;
import org.eclipse.scout.rt.client.ui.desktop.IDesktop;
import org.eclipse.scout.rt.client.ui.desktop.outline.IOutline;
import org.eclipse.scout.rt.client.ui.desktop.outline.pages.IPage;
import org.eclipse.scout.rt.client.ui.form.IForm;
/**
* @since 3.9.0
*/
public class BreadCrumb implements IBreadCrumb {
private static final IScoutLogger LOG = ScoutLogManager.getLogger(BreadCrumb.class);
private IForm m_form;
private IPage m_page;
private IBreadCrumbsNavigation m_breadCrumbsNavigation;
public BreadCrumb(IBreadCrumbsNavigation breadCrumbsNavigation, IForm form, IPage page) {
m_breadCrumbsNavigation = breadCrumbsNavigation;
m_form = form;
m_page = page;
}
@Override
public void activate() throws ProcessingException {
List<IForm> currentNavigationForms = getBreadCrumbsNavigation().getCurrentNavigationForms();
for (IForm form : currentNavigationForms) {
if (form != getForm() && !getBreadCrumbsNavigation().containsFormInHistory(form)) {
MobileDesktopUtility.closeForm(form);
}
}
//Add form to desktop if it is open but has been removed
if (getForm() != null) {
IDesktop desktop = ClientJob.getCurrentSession().getDesktop();
if (getForm().isFormOpen() && !desktop.isShowing(getForm())) {
if (MobileDesktopUtility.isToolForm(getForm())) {
MobileDesktopUtility.openToolForm(getForm());
}
else {
desktop.addForm(getForm());
}
}
}
if (getPage() != null) {
IOutline outline = getPage().getOutline();
IDesktop desktop = getBreadCrumbsNavigation().getDesktop();
if (desktop.getOutline() != outline) {
desktop.setOutline(outline);
}
- outline.selectNode(getPage());
+ if (outline != null) {
+ outline.selectNode(getPage());
+ }
}
}
public IBreadCrumbsNavigation getBreadCrumbsNavigation() {
return m_breadCrumbsNavigation;
}
@Override
public IForm getForm() {
return m_form;
}
@Override
public IPage getPage() {
return m_page;
}
@Override
public String toString() {
if (getPage() != null) {
return "Page: " + getPage().toString();
}
else {
String formName = getForm().getTitle();
if (StringUtility.isNullOrEmpty(formName)) {
formName = getForm().toString();
}
return "Form: " + formName;
}
}
@Override
public boolean belongsTo(IForm form, IPage page) {
return getForm() == form && getPage() == page;
}
}
| true | true | public void activate() throws ProcessingException {
List<IForm> currentNavigationForms = getBreadCrumbsNavigation().getCurrentNavigationForms();
for (IForm form : currentNavigationForms) {
if (form != getForm() && !getBreadCrumbsNavigation().containsFormInHistory(form)) {
MobileDesktopUtility.closeForm(form);
}
}
//Add form to desktop if it is open but has been removed
if (getForm() != null) {
IDesktop desktop = ClientJob.getCurrentSession().getDesktop();
if (getForm().isFormOpen() && !desktop.isShowing(getForm())) {
if (MobileDesktopUtility.isToolForm(getForm())) {
MobileDesktopUtility.openToolForm(getForm());
}
else {
desktop.addForm(getForm());
}
}
}
if (getPage() != null) {
IOutline outline = getPage().getOutline();
IDesktop desktop = getBreadCrumbsNavigation().getDesktop();
if (desktop.getOutline() != outline) {
desktop.setOutline(outline);
}
outline.selectNode(getPage());
}
}
| public void activate() throws ProcessingException {
List<IForm> currentNavigationForms = getBreadCrumbsNavigation().getCurrentNavigationForms();
for (IForm form : currentNavigationForms) {
if (form != getForm() && !getBreadCrumbsNavigation().containsFormInHistory(form)) {
MobileDesktopUtility.closeForm(form);
}
}
//Add form to desktop if it is open but has been removed
if (getForm() != null) {
IDesktop desktop = ClientJob.getCurrentSession().getDesktop();
if (getForm().isFormOpen() && !desktop.isShowing(getForm())) {
if (MobileDesktopUtility.isToolForm(getForm())) {
MobileDesktopUtility.openToolForm(getForm());
}
else {
desktop.addForm(getForm());
}
}
}
if (getPage() != null) {
IOutline outline = getPage().getOutline();
IDesktop desktop = getBreadCrumbsNavigation().getDesktop();
if (desktop.getOutline() != outline) {
desktop.setOutline(outline);
}
if (outline != null) {
outline.selectNode(getPage());
}
}
}
|
diff --git a/PlayersInCubes/src/me/asofold/bukkit/pic/core/Cube.java b/PlayersInCubes/src/me/asofold/bukkit/pic/core/Cube.java
index fd8ef63..bce08f2 100644
--- a/PlayersInCubes/src/me/asofold/bukkit/pic/core/Cube.java
+++ b/PlayersInCubes/src/me/asofold/bukkit/pic/core/Cube.java
@@ -1,49 +1,49 @@
package me.asofold.bukkit.pic.core;
/**
* Extends the cube related coordinates by convenience measures to check faster if players are in range.
* @author mc_dev
*
*/
public final class Cube extends CubePos{
public final int size;
// Middle in real coordinates.
private final int mX;
private final int mY;
private final int mZ;
/**
* Real coordinates !
* @param x
* @param y
* @param z
* @param size
*/
public Cube(final int x, final int y, final int z, final int size){
super(x / size, y / size, z / size);
this.size = size;
// Real coordinates for the middle of the cube:
final int sz2 = size / 2;
- this.mX = x + sz2;
- this.mY = y + sz2;
- this.mZ = z + sz2;
+ this.mX = this.x * size + sz2;
+ this.mY = this.y * size + sz2;
+ this.mZ = this.z * size + sz2;
}
/**
* Check if the given real position is within the given distance of the cube center.
* @param x
* @param y
* @param z
* @param dist
* @return
*/
public final boolean inRange(final int x, final int y, final int z, final int dist){
return Math.abs(mX - x) < dist && Math.abs(mY - y) < dist && Math.abs(mZ - z) < dist;
}
}
| true | true | public Cube(final int x, final int y, final int z, final int size){
super(x / size, y / size, z / size);
this.size = size;
// Real coordinates for the middle of the cube:
final int sz2 = size / 2;
this.mX = x + sz2;
this.mY = y + sz2;
this.mZ = z + sz2;
}
| public Cube(final int x, final int y, final int z, final int size){
super(x / size, y / size, z / size);
this.size = size;
// Real coordinates for the middle of the cube:
final int sz2 = size / 2;
this.mX = this.x * size + sz2;
this.mY = this.y * size + sz2;
this.mZ = this.z * size + sz2;
}
|
diff --git a/TheAdventure/src/se/chalmers/kangaroo/view/GameView.java b/TheAdventure/src/se/chalmers/kangaroo/view/GameView.java
index f82af9f..193b37f 100644
--- a/TheAdventure/src/se/chalmers/kangaroo/view/GameView.java
+++ b/TheAdventure/src/se/chalmers/kangaroo/view/GameView.java
@@ -1,136 +1,137 @@
package se.chalmers.kangaroo.view;
import java.awt.Polygon;
import java.util.HashMap;
import javax.swing.ImageIcon;
import se.chalmers.kangaroo.constants.Constants;
import se.chalmers.kangaroo.model.GameModel;
import se.chalmers.kangaroo.model.creatures.BlackAndWhiteCreature;
import se.chalmers.kangaroo.model.creatures.Creature;
import se.chalmers.kangaroo.model.iobject.InteractiveObject;
import se.chalmers.kangaroo.model.item.Item;
import se.chalmers.kangaroo.model.utils.Position;
/**
*
* @author alburgh
* @modifiedby simonal
* @modifiedby arvidk
*/
public class GameView extends JPanelWithBackground {
private GameModel gm;
private HashMap<Creature, Animation> creatureAnimations;
private KangarooAnimation ka;
public GameView(String imagepath, GameModel gm) {
super(imagepath);
this.gm = gm;
creatureAnimations = new HashMap<Creature, Animation>();
AnimationFactory af = new AnimationFactory();
for(int i= 0; i < gm.getGameMap().getCreatureSize(); i++){
Creature c = gm.getGameMap().getCreatureAt(i);
creatureAnimations.put(c, af.getAnimation(c));
}
ka = new KangarooAnimation(gm.getKangaroo(),58, 64);
}
@Override
public void paintComponent(java.awt.Graphics g) {
super.paintComponent(g);
Position p = gm.getKangaroo().getPosition();
int drawFrom = getLeftX();
int fixPosition = p.getX() / Constants.TILE_SIZE < 16
|| drawFrom == gm.getGameMap().getTileWidth() - 33 ? 0 : p
.getX() % 32;
g.drawString("" + gm.getTime(), 10, 10);
g.drawString("Deaths: " + gm.getDeathCount(), 100, 10);
/* Render the tiles */
for (int y = 0; y < gm.getGameMap().getTileHeight(); y++)
for (int x = drawFrom; x < drawFrom + 33; x++) {
ImageIcon i = new ImageIcon("../gfx/tiles/tile_"
+ gm.getGameMap().getTile(x, y).getId() + ".png");
i.paintIcon(null, g, (x - drawFrom) * 32 - fixPosition,
(y - 2) * 32);
}
/* Render the items */
for (int i = 0; i < gm.getGameMap().amountOfItems(); i++) {
Item item = gm.getGameMap().getItem(i);
if (item.getPosition().getX() > drawFrom
&& item.getPosition().getX() < drawFrom + 32) {
ImageIcon img = new ImageIcon("../gfx/tiles/tile_"
+ item.getId() + ".png");
img.paintIcon(null, g, (item.getPosition().getX() - drawFrom)
* 32 - fixPosition,
(item.getPosition().getY() - 2) * 32);
}
}
/* Render the interactive objects */
for (int i = 0; i < gm.getGameMap().getIObjectSize(); i++) {
InteractiveObject io = gm.getGameMap().getIObject(i);
if (io.getPosition().getX() > drawFrom
&& io.getPosition().getX() < drawFrom + 32) {
ImageIcon img = new ImageIcon("../gfx/tiles/tile_" + io.getId()
+ ".png");
img.paintIcon(null, g, (io.getPosition().getX() - drawFrom)
* 32 - fixPosition, (io.getPosition().getY() - 2) * 32);
}
}
/* Render the creatures */
for (int i = 0; i < gm.getGameMap().getCreatureSize(); i++) {
Creature c = gm.getGameMap().getCreatureAt(i);
if (c.getPosition().getX() > drawFrom * 32
&& c.getPosition().getX() < (drawFrom + 32) * 32) {
int xP = c.getPosition().getX();
int yP = c.getPosition().getY();
int[] xs = { xP - drawFrom * 32 - fixPosition,
xP - drawFrom * 32 + 64 - fixPosition,
xP - drawFrom * 32 + 64 - fixPosition,
xP - drawFrom * 32 - fixPosition };
int[] ys = { yP - 64, yP - 64, yP - 32, yP - 32 };
g.drawPolygon(xs, ys, 4);
+ System.out.println(creatureAnimations.get(c).toString());
if(creatureAnimations.containsKey(c))
creatureAnimations.get(c).drawSprite(g, xP, yP);
}
}
/* Draw the kangaroo based on where you are */
if (drawFrom == 0
&& gm.getKangaroo().getPosition().getX() / Constants.TILE_SIZE != 16) {
int[] xs = { p.getX(), p.getX() + 32, p.getX() + 32, p.getX() };
int[] ys = { p.getY() - 64, p.getY() - 64, p.getY() - 1,
p.getY() - 1 };
//g.drawPolygon(new Polygon(xs, ys, 4));
ka.drawSprite(g, p.getX(), p.getY());
} else if (drawFrom == gm.getGameMap().getTileWidth() - 33) {
int[] xs = { p.getX() - drawFrom * 32,
p.getX() + 32 - drawFrom * 32,
p.getX() + 32 - drawFrom * 32, p.getX() - drawFrom * 32 };
int[] ys = { p.getY() - 64, p.getY() - 64, p.getY() - 1,
p.getY() - 1 };
//g.drawPolygon(new Polygon(xs, ys, 4));
ka.drawSprite(g, p.getX()-drawFrom*32-fixPosition, p.getY());
} else {
int[] xs = { 16 * 32, 17 * 32, 17 * 32, 16 * 32 };
int[] ys = { p.getY() - 64, p.getY() - 64, p.getY() - 1,
p.getY() - 1 };
//g.drawPolygon(new Polygon(xs, ys, 4));
ka.drawSprite(g, p.getX()-drawFrom*32-fixPosition, p.getY());
}
}
/* Private method for calculate the left side to render */
private int getLeftX() {
int kPos = gm.getKangaroo().getPosition().getX() / Constants.TILE_SIZE;
if (kPos < 16)
return 0;
if (gm.getGameMap().getTileWidth() - kPos < 17)
return gm.getGameMap().getTileWidth() - 33;
return kPos - 16;
}
}
| true | true | public void paintComponent(java.awt.Graphics g) {
super.paintComponent(g);
Position p = gm.getKangaroo().getPosition();
int drawFrom = getLeftX();
int fixPosition = p.getX() / Constants.TILE_SIZE < 16
|| drawFrom == gm.getGameMap().getTileWidth() - 33 ? 0 : p
.getX() % 32;
g.drawString("" + gm.getTime(), 10, 10);
g.drawString("Deaths: " + gm.getDeathCount(), 100, 10);
/* Render the tiles */
for (int y = 0; y < gm.getGameMap().getTileHeight(); y++)
for (int x = drawFrom; x < drawFrom + 33; x++) {
ImageIcon i = new ImageIcon("../gfx/tiles/tile_"
+ gm.getGameMap().getTile(x, y).getId() + ".png");
i.paintIcon(null, g, (x - drawFrom) * 32 - fixPosition,
(y - 2) * 32);
}
/* Render the items */
for (int i = 0; i < gm.getGameMap().amountOfItems(); i++) {
Item item = gm.getGameMap().getItem(i);
if (item.getPosition().getX() > drawFrom
&& item.getPosition().getX() < drawFrom + 32) {
ImageIcon img = new ImageIcon("../gfx/tiles/tile_"
+ item.getId() + ".png");
img.paintIcon(null, g, (item.getPosition().getX() - drawFrom)
* 32 - fixPosition,
(item.getPosition().getY() - 2) * 32);
}
}
/* Render the interactive objects */
for (int i = 0; i < gm.getGameMap().getIObjectSize(); i++) {
InteractiveObject io = gm.getGameMap().getIObject(i);
if (io.getPosition().getX() > drawFrom
&& io.getPosition().getX() < drawFrom + 32) {
ImageIcon img = new ImageIcon("../gfx/tiles/tile_" + io.getId()
+ ".png");
img.paintIcon(null, g, (io.getPosition().getX() - drawFrom)
* 32 - fixPosition, (io.getPosition().getY() - 2) * 32);
}
}
/* Render the creatures */
for (int i = 0; i < gm.getGameMap().getCreatureSize(); i++) {
Creature c = gm.getGameMap().getCreatureAt(i);
if (c.getPosition().getX() > drawFrom * 32
&& c.getPosition().getX() < (drawFrom + 32) * 32) {
int xP = c.getPosition().getX();
int yP = c.getPosition().getY();
int[] xs = { xP - drawFrom * 32 - fixPosition,
xP - drawFrom * 32 + 64 - fixPosition,
xP - drawFrom * 32 + 64 - fixPosition,
xP - drawFrom * 32 - fixPosition };
int[] ys = { yP - 64, yP - 64, yP - 32, yP - 32 };
g.drawPolygon(xs, ys, 4);
if(creatureAnimations.containsKey(c))
creatureAnimations.get(c).drawSprite(g, xP, yP);
}
}
/* Draw the kangaroo based on where you are */
if (drawFrom == 0
&& gm.getKangaroo().getPosition().getX() / Constants.TILE_SIZE != 16) {
int[] xs = { p.getX(), p.getX() + 32, p.getX() + 32, p.getX() };
int[] ys = { p.getY() - 64, p.getY() - 64, p.getY() - 1,
p.getY() - 1 };
//g.drawPolygon(new Polygon(xs, ys, 4));
ka.drawSprite(g, p.getX(), p.getY());
} else if (drawFrom == gm.getGameMap().getTileWidth() - 33) {
int[] xs = { p.getX() - drawFrom * 32,
p.getX() + 32 - drawFrom * 32,
p.getX() + 32 - drawFrom * 32, p.getX() - drawFrom * 32 };
int[] ys = { p.getY() - 64, p.getY() - 64, p.getY() - 1,
p.getY() - 1 };
//g.drawPolygon(new Polygon(xs, ys, 4));
ka.drawSprite(g, p.getX()-drawFrom*32-fixPosition, p.getY());
} else {
int[] xs = { 16 * 32, 17 * 32, 17 * 32, 16 * 32 };
int[] ys = { p.getY() - 64, p.getY() - 64, p.getY() - 1,
p.getY() - 1 };
//g.drawPolygon(new Polygon(xs, ys, 4));
ka.drawSprite(g, p.getX()-drawFrom*32-fixPosition, p.getY());
}
}
| public void paintComponent(java.awt.Graphics g) {
super.paintComponent(g);
Position p = gm.getKangaroo().getPosition();
int drawFrom = getLeftX();
int fixPosition = p.getX() / Constants.TILE_SIZE < 16
|| drawFrom == gm.getGameMap().getTileWidth() - 33 ? 0 : p
.getX() % 32;
g.drawString("" + gm.getTime(), 10, 10);
g.drawString("Deaths: " + gm.getDeathCount(), 100, 10);
/* Render the tiles */
for (int y = 0; y < gm.getGameMap().getTileHeight(); y++)
for (int x = drawFrom; x < drawFrom + 33; x++) {
ImageIcon i = new ImageIcon("../gfx/tiles/tile_"
+ gm.getGameMap().getTile(x, y).getId() + ".png");
i.paintIcon(null, g, (x - drawFrom) * 32 - fixPosition,
(y - 2) * 32);
}
/* Render the items */
for (int i = 0; i < gm.getGameMap().amountOfItems(); i++) {
Item item = gm.getGameMap().getItem(i);
if (item.getPosition().getX() > drawFrom
&& item.getPosition().getX() < drawFrom + 32) {
ImageIcon img = new ImageIcon("../gfx/tiles/tile_"
+ item.getId() + ".png");
img.paintIcon(null, g, (item.getPosition().getX() - drawFrom)
* 32 - fixPosition,
(item.getPosition().getY() - 2) * 32);
}
}
/* Render the interactive objects */
for (int i = 0; i < gm.getGameMap().getIObjectSize(); i++) {
InteractiveObject io = gm.getGameMap().getIObject(i);
if (io.getPosition().getX() > drawFrom
&& io.getPosition().getX() < drawFrom + 32) {
ImageIcon img = new ImageIcon("../gfx/tiles/tile_" + io.getId()
+ ".png");
img.paintIcon(null, g, (io.getPosition().getX() - drawFrom)
* 32 - fixPosition, (io.getPosition().getY() - 2) * 32);
}
}
/* Render the creatures */
for (int i = 0; i < gm.getGameMap().getCreatureSize(); i++) {
Creature c = gm.getGameMap().getCreatureAt(i);
if (c.getPosition().getX() > drawFrom * 32
&& c.getPosition().getX() < (drawFrom + 32) * 32) {
int xP = c.getPosition().getX();
int yP = c.getPosition().getY();
int[] xs = { xP - drawFrom * 32 - fixPosition,
xP - drawFrom * 32 + 64 - fixPosition,
xP - drawFrom * 32 + 64 - fixPosition,
xP - drawFrom * 32 - fixPosition };
int[] ys = { yP - 64, yP - 64, yP - 32, yP - 32 };
g.drawPolygon(xs, ys, 4);
System.out.println(creatureAnimations.get(c).toString());
if(creatureAnimations.containsKey(c))
creatureAnimations.get(c).drawSprite(g, xP, yP);
}
}
/* Draw the kangaroo based on where you are */
if (drawFrom == 0
&& gm.getKangaroo().getPosition().getX() / Constants.TILE_SIZE != 16) {
int[] xs = { p.getX(), p.getX() + 32, p.getX() + 32, p.getX() };
int[] ys = { p.getY() - 64, p.getY() - 64, p.getY() - 1,
p.getY() - 1 };
//g.drawPolygon(new Polygon(xs, ys, 4));
ka.drawSprite(g, p.getX(), p.getY());
} else if (drawFrom == gm.getGameMap().getTileWidth() - 33) {
int[] xs = { p.getX() - drawFrom * 32,
p.getX() + 32 - drawFrom * 32,
p.getX() + 32 - drawFrom * 32, p.getX() - drawFrom * 32 };
int[] ys = { p.getY() - 64, p.getY() - 64, p.getY() - 1,
p.getY() - 1 };
//g.drawPolygon(new Polygon(xs, ys, 4));
ka.drawSprite(g, p.getX()-drawFrom*32-fixPosition, p.getY());
} else {
int[] xs = { 16 * 32, 17 * 32, 17 * 32, 16 * 32 };
int[] ys = { p.getY() - 64, p.getY() - 64, p.getY() - 1,
p.getY() - 1 };
//g.drawPolygon(new Polygon(xs, ys, 4));
ka.drawSprite(g, p.getX()-drawFrom*32-fixPosition, p.getY());
}
}
|
diff --git a/lib/java/src/protocol/TProtocolUtil.java b/lib/java/src/protocol/TProtocolUtil.java
index 0b85d38..5c665ab 100644
--- a/lib/java/src/protocol/TProtocolUtil.java
+++ b/lib/java/src/protocol/TProtocolUtil.java
@@ -1,104 +1,104 @@
// Copyright (c) 2006- Facebook
// Distributed under the Thrift Software License
//
// See accompanying file LICENSE or visit the Thrift site at:
// http://developers.facebook.com/thrift/
package com.facebook.thrift.protocol;
import com.facebook.thrift.TException;
import com.facebook.thrift.transport.TTransport;
/**
* Utility class with static methods for interacting with protocol data
* streams.
*
* @author Mark Slee <[email protected]>
*/
public class TProtocolUtil {
public static void skip(TProtocol prot, byte type)
throws TException {
switch (type) {
case TType.BOOL:
{
prot.readBool();
break;
}
case TType.BYTE:
{
prot.readByte();
break;
}
case TType.I16:
{
prot.readI16();
break;
}
case TType.I32:
{
prot.readI32();
break;
}
case TType.I64:
{
prot.readI64();
break;
}
case TType.DOUBLE:
{
prot.readDouble();
break;
}
case TType.STRING:
{
- prot.readString();
+ prot.readBinary();
break;
}
case TType.STRUCT:
{
prot.readStructBegin();
while (true) {
TField field = prot.readFieldBegin();
if (field.type == TType.STOP) {
break;
}
skip(prot, field.type);
prot.readFieldEnd();
}
prot.readStructEnd();
break;
}
case TType.MAP:
{
TMap map = prot.readMapBegin();
for (int i = 0; i < map.size; i++) {
skip(prot, map.keyType);
skip(prot, map.valueType);
}
prot.readMapEnd();
break;
}
case TType.SET:
{
TSet set = prot.readSetBegin();
for (int i = 0; i < set.size; i++) {
skip(prot, set.elemType);
}
prot.readSetEnd();
break;
}
case TType.LIST:
{
TList list = prot.readListBegin();
for (int i = 0; i < list.size; i++) {
skip(prot, list.elemType);
}
prot.readListEnd();
break;
}
default:
break;
}
}
}
| true | true | public static void skip(TProtocol prot, byte type)
throws TException {
switch (type) {
case TType.BOOL:
{
prot.readBool();
break;
}
case TType.BYTE:
{
prot.readByte();
break;
}
case TType.I16:
{
prot.readI16();
break;
}
case TType.I32:
{
prot.readI32();
break;
}
case TType.I64:
{
prot.readI64();
break;
}
case TType.DOUBLE:
{
prot.readDouble();
break;
}
case TType.STRING:
{
prot.readString();
break;
}
case TType.STRUCT:
{
prot.readStructBegin();
while (true) {
TField field = prot.readFieldBegin();
if (field.type == TType.STOP) {
break;
}
skip(prot, field.type);
prot.readFieldEnd();
}
prot.readStructEnd();
break;
}
case TType.MAP:
{
TMap map = prot.readMapBegin();
for (int i = 0; i < map.size; i++) {
skip(prot, map.keyType);
skip(prot, map.valueType);
}
prot.readMapEnd();
break;
}
case TType.SET:
{
TSet set = prot.readSetBegin();
for (int i = 0; i < set.size; i++) {
skip(prot, set.elemType);
}
prot.readSetEnd();
break;
}
case TType.LIST:
{
TList list = prot.readListBegin();
for (int i = 0; i < list.size; i++) {
skip(prot, list.elemType);
}
prot.readListEnd();
break;
}
default:
break;
}
}
| public static void skip(TProtocol prot, byte type)
throws TException {
switch (type) {
case TType.BOOL:
{
prot.readBool();
break;
}
case TType.BYTE:
{
prot.readByte();
break;
}
case TType.I16:
{
prot.readI16();
break;
}
case TType.I32:
{
prot.readI32();
break;
}
case TType.I64:
{
prot.readI64();
break;
}
case TType.DOUBLE:
{
prot.readDouble();
break;
}
case TType.STRING:
{
prot.readBinary();
break;
}
case TType.STRUCT:
{
prot.readStructBegin();
while (true) {
TField field = prot.readFieldBegin();
if (field.type == TType.STOP) {
break;
}
skip(prot, field.type);
prot.readFieldEnd();
}
prot.readStructEnd();
break;
}
case TType.MAP:
{
TMap map = prot.readMapBegin();
for (int i = 0; i < map.size; i++) {
skip(prot, map.keyType);
skip(prot, map.valueType);
}
prot.readMapEnd();
break;
}
case TType.SET:
{
TSet set = prot.readSetBegin();
for (int i = 0; i < set.size; i++) {
skip(prot, set.elemType);
}
prot.readSetEnd();
break;
}
case TType.LIST:
{
TList list = prot.readListBegin();
for (int i = 0; i < list.size; i++) {
skip(prot, list.elemType);
}
prot.readListEnd();
break;
}
default:
break;
}
}
|
diff --git a/edu/mit/wi/haploview/HaploText.java b/edu/mit/wi/haploview/HaploText.java
index 2d383e2..cc475df 100644
--- a/edu/mit/wi/haploview/HaploText.java
+++ b/edu/mit/wi/haploview/HaploText.java
@@ -1,1264 +1,1264 @@
package edu.mit.wi.haploview;
import edu.mit.wi.pedfile.MarkerResult;
import edu.mit.wi.pedfile.PedFileException;
import edu.mit.wi.pedfile.CheckData;
import edu.mit.wi.haploview.association.*;
import edu.mit.wi.haploview.tagger.TaggerController;
import edu.mit.wi.tagger.Tagger;
import edu.mit.wi.tagger.TaggerException;
import java.io.*;
import java.util.*;
import java.awt.image.BufferedImage;
import com.sun.jimi.core.Jimi;
import com.sun.jimi.core.JimiException;
public class HaploText implements Constants{
private boolean nogui = false;
private String batchFileName;
private String hapsFileName;
private String infoFileName;
private String pedFileName;
private String hapmapFileName;
private String blockFileName;
private String trackFileName;
private String customAssocTestsFileName;
private boolean skipCheck = false;
private Vector excludedMarkers = new Vector();
private boolean quietMode = false;
private int blockOutputType;
private boolean outputCheck;
private boolean individualCheck;
private boolean mendel;
private boolean outputDprime;
private boolean outputPNG;
private boolean outputCompressedPNG;
private boolean doPermutationTest;
private boolean findTags;
private boolean randomizeAffection = false;
private int permutationCount;
private int tagging;
private int maxNumTags;
private double tagRSquaredCutOff = -1;
private Vector forceIncludeTags;
private String forceIncludeFileName;
private Vector forceExcludeTags;
private String forceExcludeFileName;
private Vector argHandlerMessages;
private String chromosomeArg;
public boolean isNogui() {
return nogui;
}
public String getBatchMode() {
return batchFileName;
}
public String getHapsFileName() {
return hapsFileName;
}
public String getPedFileName() {
return pedFileName;
}
public String getInfoFileName(){
return infoFileName;
}
public String getHapmapFileName(){
return hapmapFileName;
}
public int getBlockOutputType() {
return blockOutputType;
}
private double getDoubleArg(String[] args, int valueIndex, double min, double max) {
double argument = 0;
String argName = args[valueIndex-1];
if(valueIndex>=args.length || ((args[valueIndex].charAt(0)) == '-')) {
die( argName + " requires a value between " + min + " and " + max);
}
try {
argument = Double.parseDouble(args[valueIndex]);
if(argument<min || argument>max) {
die(argName + " requires a value between " + min + " and " + max);
}
}catch(NumberFormatException nfe) {
die(argName + " requires a value between " + min + " and " + max);
}
return argument;
}
private int getIntegerArg(String[] args, int valueIndex){
int argument = 0;
String argName = args[valueIndex-1];
if(valueIndex>=args.length || ((args[valueIndex].charAt(0)) == '-')){
die(argName + " requires an integer argument");
}
else {
try {
argument = Integer.parseInt(args[valueIndex]);
if(argument<0){
die(argName + " argument must be a positive integer");
}
} catch(NumberFormatException nfe) {
die(argName + " argument must be a positive integer");
}
}
return argument;
}
public HaploText(String[] args) {
this.argHandler(args);
if(this.batchFileName != null) {
System.out.println(TITLE_STRING);
for (int i = 0; i < argHandlerMessages.size(); i++){
System.out.println(argHandlerMessages.get(i));
}
this.doBatch();
}
if(!(this.pedFileName== null) || !(this.hapsFileName== null) || !(this.hapmapFileName== null)){
if(nogui){
System.out.println(TITLE_STRING);
for (int i = 0; i < argHandlerMessages.size(); i++){
System.out.println(argHandlerMessages.get(i));
}
processTextOnly();
}
}
}
private void argHandler(String[] args){
argHandlerMessages = new Vector();
int maxDistance = -1;
//this means that user didn't specify any output type if it doesn't get changed below
blockOutputType = -1;
double hapThresh = -1;
double minimumMAF=-1;
double spacingThresh = -1;
double minimumGenoPercent = -1;
double hwCutoff = -1;
double missingCutoff = -1;
int maxMendel = -1;
boolean assocTDT = false;
boolean assocCC = false;
permutationCount = 0;
tagging = Tagger.NONE;
maxNumTags = Tagger.DEFAULT_MAXNUMTAGS;
findTags = true;
double cutHighCI = -1;
double cutLowCI = -1;
double mafThresh = -1;
double recHighCI = -1;
double informFrac = -1;
double fourGameteCutoff = -1;
double spineDP = -1;
for(int i =0; i < args.length; i++) {
if(args[i].equalsIgnoreCase("-help") || args[i].equalsIgnoreCase("-h")) {
System.out.println(HELP_OUTPUT);
System.exit(0);
}
else if(args[i].equalsIgnoreCase("-n") || args[i].equalsIgnoreCase("-nogui")) {
nogui = true;
}
else if(args[i].equalsIgnoreCase("-p") || args[i].equalsIgnoreCase("-pedfile")) {
i++;
if( i>=args.length || (args[i].charAt(0) == '-')){
die(args[i-1] + " requires a filename");
}
else{
if(pedFileName != null){
argHandlerMessages.add("multiple "+args[i-1] + " arguments found. only last pedfile listed will be used");
}
pedFileName = args[i];
}
}
else if (args[i].equalsIgnoreCase("-pcloadletter")){
die("PC LOADLETTER?! What the fuck does that mean?!");
}
else if (args[i].equalsIgnoreCase("-skipcheck") || args[i].equalsIgnoreCase("--skipcheck")){
skipCheck = true;
}
else if (args[i].equalsIgnoreCase("-excludeMarkers")){
i++;
if(i>=args.length || (args[i].charAt(0) == '-')){
die("-excludeMarkers requires a list of markers");
}
else {
StringTokenizer str = new StringTokenizer(args[i],",");
try {
StringBuffer sb = new StringBuffer();
if (!quietMode) sb.append("Excluding markers: ");
while(str.hasMoreTokens()) {
String token = str.nextToken();
if(token.indexOf("..") != -1) {
int lastIndex = token.indexOf("..");
int rangeStart = Integer.parseInt(token.substring(0,lastIndex));
int rangeEnd = Integer.parseInt(token.substring(lastIndex+2,token.length()));
for(int j=rangeStart;j<=rangeEnd;j++) {
if (!quietMode) sb.append(j+" ");
excludedMarkers.add(new Integer(j));
}
} else {
if (!quietMode) sb.append(token+" ");
excludedMarkers.add(new Integer(token));
}
}
if (!quietMode) argHandlerMessages.add(sb.toString());
} catch(NumberFormatException nfe) {
die("-excludeMarkers argument should be of the format: 1,3,5..8,12");
}
}
}
else if(args[i].equalsIgnoreCase("-ha") || args[i].equalsIgnoreCase("-l") || args[i].equalsIgnoreCase("-haps")) {
i++;
if(i>=args.length || ((args[i].charAt(0)) == '-')){
die(args[i-1] + " requires a filename");
}
else{
if(hapsFileName != null){
argHandlerMessages.add("multiple "+args[i-1] + " arguments found. only last haps file listed will be used");
}
hapsFileName = args[i];
}
}
else if(args[i].equalsIgnoreCase("-i") || args[i].equalsIgnoreCase("-info")) {
i++;
if(i>=args.length || ((args[i].charAt(0)) == '-')){
die(args[i-1] + " requires a filename");
}
else{
if(infoFileName != null){
argHandlerMessages.add("multiple "+args[i-1] + " arguments found. only last info file listed will be used");
}
infoFileName = args[i];
}
} else if (args[i].equalsIgnoreCase("-a") || args[i].equalsIgnoreCase("-hapmap")){
i++;
if(i>=args.length || ((args[i].charAt(0)) == '-')){
die(args[i-1] + " requires a filename");
}
else{
if(hapmapFileName != null){
argHandlerMessages.add("multiple "+args[i-1] + " arguments found. only last hapmap file listed will be used");
}
hapmapFileName = args[i];
}
}
else if(args[i].equalsIgnoreCase("-k") || args[i].equalsIgnoreCase("-blocks")) {
i++;
if (!(i>=args.length) && !((args[i].charAt(0)) == '-')){
blockFileName = args[i];
blockOutputType = BLOX_CUSTOM;
}else{
die(args[i-1] + " requires a filename");
}
}
else if (args[i].equalsIgnoreCase("-png")){
outputPNG = true;
}
else if (args[i].equalsIgnoreCase("-smallpng") || args[i].equalsIgnoreCase("-compressedPNG")){
outputCompressedPNG = true;
}
else if (args[i].equalsIgnoreCase("-track")){
i++;
if (!(i>=args.length) && !((args[i].charAt(0)) == '-')){
trackFileName = args[i];
}else{
die("-track requires a filename");
}
}
else if(args[i].equalsIgnoreCase("-o") || args[i].equalsIgnoreCase("-output") || args[i].equalsIgnoreCase("-blockoutput")) {
i++;
if(!(i>=args.length) && !((args[i].charAt(0)) == '-')){
if(blockOutputType != -1){
die("Only one block output type argument is allowed.");
}
if(args[i].equalsIgnoreCase("SFS") || args[i].equalsIgnoreCase("GAB")){
blockOutputType = BLOX_GABRIEL;
}
else if(args[i].equalsIgnoreCase("GAM")){
blockOutputType = BLOX_4GAM;
}
else if(args[i].equalsIgnoreCase("MJD") || args[i].equalsIgnoreCase("SPI")){
blockOutputType = BLOX_SPINE;
}
else if(args[i].equalsIgnoreCase("ALL")) {
blockOutputType = BLOX_ALL;
}
}
else {
//defaults to SFS output
blockOutputType = BLOX_GABRIEL;
i--;
}
}
else if(args[i].equalsIgnoreCase("-d") || args[i].equalsIgnoreCase("--dprime") || args[i].equalsIgnoreCase("-dprime")) {
outputDprime = true;
}
else if (args[i].equalsIgnoreCase("-c") || args[i].equalsIgnoreCase("-check")){
outputCheck = true;
}
else if (args[i].equalsIgnoreCase("-indcheck")){
individualCheck = true;
}
else if (args[i].equalsIgnoreCase("-mendel")){
mendel = true;
}
else if(args[i].equalsIgnoreCase("-m") || args[i].equalsIgnoreCase("-maxdistance")) {
i++;
maxDistance = getIntegerArg(args,i);
}
else if(args[i].equalsIgnoreCase("-b") || args[i].equalsIgnoreCase("-batch")) {
//batch mode
i++;
if(i>=args.length || ((args[i].charAt(0)) == '-')){
die(args[i-1] + " requires a filename");
}
else{
if(batchFileName != null){
argHandlerMessages.add("multiple " + args[i-1] + " arguments found. only last batch file listed will be used");
}
batchFileName = args[i];
}
}
else if(args[i].equalsIgnoreCase("-hapthresh")) {
i++;
hapThresh = getDoubleArg(args,i,0,1);
}
else if(args[i].equalsIgnoreCase("-spacing")) {
i++;
spacingThresh = getDoubleArg(args,i,0,1);
}
else if(args[i].equalsIgnoreCase("-minMAF")) {
i++;
minimumMAF = getDoubleArg(args,i,0,0.5);
}
else if(args[i].equalsIgnoreCase("-minGeno") || args[i].equalsIgnoreCase("-minGenoPercent")) {
i++;
minimumGenoPercent = getDoubleArg(args,i,0,1);
}
else if(args[i].equalsIgnoreCase("-hwcutoff")) {
i++;
hwCutoff = getDoubleArg(args,i,0,1);
}
else if(args[i].equalsIgnoreCase("-maxMendel") ) {
i++;
maxMendel = getIntegerArg(args,i);
}
else if(args[i].equalsIgnoreCase("-missingcutoff")) {
i++;
missingCutoff = getDoubleArg(args,i,0,1);
}
else if(args[i].equalsIgnoreCase("-assoctdt")) {
assocTDT = true;
}
else if(args[i].equalsIgnoreCase("-assoccc")) {
assocCC = true;
}
else if(args[i].equalsIgnoreCase("-randomcc")){
assocCC = true;
randomizeAffection = true;
}
else if(args[i].equalsIgnoreCase("-ldcolorscheme")) {
i++;
if(!(i>=args.length) && !((args[i].charAt(0)) == '-')){
if(args[i].equalsIgnoreCase("default")){
Options.setLDColorScheme(STD_SCHEME);
}
else if(args[i].equalsIgnoreCase("RSQ")){
Options.setLDColorScheme(RSQ_SCHEME);
}
else if(args[i].equalsIgnoreCase("DPALT") ){
Options.setLDColorScheme(WMF_SCHEME);
}
else if(args[i].equalsIgnoreCase("GAB")) {
Options.setLDColorScheme(GAB_SCHEME);
}
else if(args[i].equalsIgnoreCase("GAM")) {
Options.setLDColorScheme(GAM_SCHEME);
}
else if(args[i].equalsIgnoreCase("GOLD")) {
Options.setLDColorScheme(GOLD_SCHEME);
}
}
else {
//defaults to STD color scheme
Options.setLDColorScheme(STD_SCHEME);
i--;
}
}
else if(args[i].equalsIgnoreCase("-blockCutHighCI")) {
i++;
cutHighCI = getDoubleArg(args,i,0,1);
}
else if(args[i].equalsIgnoreCase("-blockCutLowCI")) {
i++;
cutLowCI = getDoubleArg(args,i,0,1);
}
else if(args[i].equalsIgnoreCase("-blockMafThresh")) {
i++;
mafThresh = getDoubleArg(args,i,0,1);
}
else if(args[i].equalsIgnoreCase("-blockRecHighCI")) {
i++;
recHighCI = getDoubleArg(args,i,0,1);
}
else if(args[i].equalsIgnoreCase("-blockInformFrac")) {
i++;
informFrac = getDoubleArg(args,i,0,1);
}
else if(args[i].equalsIgnoreCase("-block4GamCut")) {
i++;
fourGameteCutoff = getDoubleArg(args,i,0,1);
}
else if(args[i].equalsIgnoreCase("-blockSpineDP")) {
i++;
spineDP = getDoubleArg(args,i,0,1);
}
else if(args[i].equalsIgnoreCase("-permtests")) {
i++;
doPermutationTest = true;
permutationCount = getIntegerArg(args,i);
}
else if(args[i].equalsIgnoreCase("-customassoc")) {
i++;
if (!(i>=args.length) && !((args[i].charAt(0)) == '-')){
customAssocTestsFileName = args[i];
}else{
die(args[i-1] + " requires a filename");
}
}
else if(args[i].equalsIgnoreCase("-aggressiveTagging")) {
tagging = Tagger.AGGRESSIVE_TRIPLE;
}
else if (args[i].equalsIgnoreCase("-pairwiseTagging")){
tagging = Tagger.PAIRWISE_ONLY;
}
else if (args[i].equalsIgnoreCase("-printalltags")){
Options.setPrintAllTags(true);
}
else if(args[i].equalsIgnoreCase("-maxNumTags")){
i++;
maxNumTags = getIntegerArg(args,i);
}
else if(args[i].equalsIgnoreCase("-tagrSqCutoff")) {
i++;
tagRSquaredCutOff = getDoubleArg(args,i,0,1);
}
else if (args[i].equalsIgnoreCase("-dontaddtags")){
findTags = false;
}
else if(args[i].equalsIgnoreCase("-tagLODCutoff")) {
i++;
Options.setTaggerLODCutoff(getDoubleArg(args,i,0,100000));
}
else if(args[i].equalsIgnoreCase("-includeTags")) {
i++;
if(i>=args.length || args[i].charAt(0) == '-') {
die(args[i-1] + " requires a list of marker names.");
}
StringTokenizer str = new StringTokenizer(args[i],",");
forceIncludeTags = new Vector();
while(str.hasMoreTokens()) {
forceIncludeTags.add(str.nextToken());
}
}
else if (args[i].equalsIgnoreCase("-includeTagsFile")) {
i++;
if(!(i>=args.length) && !(args[i].charAt(0) == '-')) {
forceIncludeFileName =args[i];
}else {
die(args[i-1] + " requires a filename");
}
}
else if(args[i].equalsIgnoreCase("-excludeTags")) {
i++;
if(i>=args.length || args[i].charAt(0) == '-') {
die("-excludeTags requires a list of marker names.");
}
StringTokenizer str = new StringTokenizer(args[i],",");
forceExcludeTags = new Vector();
while(str.hasMoreTokens()) {
forceExcludeTags.add(str.nextToken());
}
}
else if (args[i].equalsIgnoreCase("-excludeTagsFile")) {
i++;
if(!(i>=args.length) && !(args[i].charAt(0) == '-')) {
forceExcludeFileName =args[i];
}else {
die(args[i-1] + " requires a filename");
}
}
else if(args[i].equalsIgnoreCase("-chromosome") || args[i].equalsIgnoreCase("-chr")) {
i++;
if(!(i>=args.length) && !(args[i].charAt(0) == '-')) {
chromosomeArg =args[i];
}else {
die(args[i-1] + " requires a chromosome name");
}
}
else if(args[i].equalsIgnoreCase("-q") || args[i].equalsIgnoreCase("-quiet")) {
quietMode = true;
}
else {
die("invalid parameter specified: " + args[i]);
}
}
int countOptions = 0;
if(pedFileName != null) {
countOptions++;
}
if(hapsFileName != null) {
countOptions++;
}
if(hapmapFileName != null) {
countOptions++;
}
if(batchFileName != null) {
countOptions++;
}
if(countOptions > 1) {
die("Only one genotype input file may be specified on the command line.");
}
else if(countOptions == 0 && nogui) {
die("You must specify a genotype input file.");
}
//mess with vars, set defaults, etc
if(skipCheck && !quietMode) {
argHandlerMessages.add("Skipping genotype file check");
}
if(maxDistance == -1){
maxDistance = MAXDIST_DEFAULT;
}else{
if (!quietMode) argHandlerMessages.add("Max LD comparison distance = " +maxDistance);
}
Options.setMaxDistance(maxDistance);
if(hapThresh != -1) {
Options.setHaplotypeDisplayThreshold(hapThresh);
if (!quietMode) argHandlerMessages.add("Haplotype display threshold = " + hapThresh);
}
if(minimumMAF != -1) {
CheckData.mafCut = minimumMAF;
if (!quietMode) argHandlerMessages.add("Minimum MAF = " + minimumMAF);
}
if(minimumGenoPercent != -1) {
CheckData.failedGenoCut = (int)(minimumGenoPercent*100);
if (!quietMode) argHandlerMessages.add("Minimum SNP genotype % = " + minimumGenoPercent);
}
if(hwCutoff != -1) {
CheckData.hwCut = hwCutoff;
if (!quietMode) argHandlerMessages.add("Hardy Weinberg equilibrium p-value cutoff = " + hwCutoff);
}
if(maxMendel != -1) {
CheckData.numMendErrCut = maxMendel;
if (!quietMode) argHandlerMessages.add("Maximum number of Mendel errors = "+maxMendel);
}
if(spacingThresh != -1) {
Options.setSpacingThreshold(spacingThresh);
if (!quietMode) argHandlerMessages.add("LD display spacing value = "+spacingThresh);
}
if(missingCutoff != -1) {
Options.setMissingThreshold(missingCutoff);
if (!quietMode) argHandlerMessages.add("Maximum amount of missing data allowed per individual = "+missingCutoff);
}
if(cutHighCI != -1) {
FindBlocks.cutHighCI = cutHighCI;
}
if(cutLowCI != -1) {
FindBlocks.cutLowCI = cutLowCI;
}
if(mafThresh != -1) {
FindBlocks.mafThresh = mafThresh;
}
if(recHighCI != -1) {
FindBlocks.recHighCI = recHighCI;
}
if(informFrac != -1) {
FindBlocks.informFrac = informFrac;
}
if(fourGameteCutoff != -1) {
FindBlocks.fourGameteCutoff = fourGameteCutoff;
}
if(spineDP != -1) {
FindBlocks.spineDP = spineDP;
}
if(assocTDT) {
Options.setAssocTest(ASSOC_TRIO);
}else if(assocCC) {
Options.setAssocTest(ASSOC_CC);
}
if (Options.getAssocTest() != ASSOC_NONE && infoFileName == null && hapmapFileName == null) {
die("A marker info file must be specified when performing association tests.");
}
if(doPermutationTest) {
if(!assocCC && !assocTDT) {
die("An association test type must be specified for permutation tests to be performed.");
}
}
if(customAssocTestsFileName != null) {
if(!assocCC && !assocTDT) {
die("An association test type must be specified when using a custom association test file.");
}
if(infoFileName == null) {
die("A marker info file must be specified when using a custom association test file.");
}
}
if(tagging != Tagger.NONE) {
- if(infoFileName == null && hapmapFileName == null) {
- die("A marker info file must be specified when using -doTagging");
+ if(infoFileName == null && hapmapFileName == null && batchFileName == null) {
+ die("A marker info file must be specified when tagging.");
}
if(forceExcludeTags == null) {
forceExcludeTags = new Vector();
} else if (forceExcludeFileName != null) {
die("-excludeTags and -excludeTagsFile cannot both be used");
}
if(forceExcludeFileName != null) {
File excludeFile = new File(forceExcludeFileName);
forceExcludeTags = new Vector();
try {
BufferedReader br = new BufferedReader(new FileReader(excludeFile));
String line;
while((line = br.readLine()) != null) {
if(line.length() > 0 && line.charAt(0) != '#'){
forceExcludeTags.add(line);
}
}
}catch(IOException ioe) {
die("An error occured while reading the file specified by -excludeTagsFile.");
}
}
if(forceIncludeTags == null ) {
forceIncludeTags = new Vector();
} else if (forceIncludeFileName != null) {
die("-includeTags and -includeTagsFile cannot both be used");
}
if(forceIncludeFileName != null) {
File includeFile = new File(forceIncludeFileName);
forceIncludeTags = new Vector();
try {
BufferedReader br = new BufferedReader(new FileReader(includeFile));
String line;
while((line = br.readLine()) != null) {
if(line.length() > 0 && line.charAt(0) != '#'){
forceIncludeTags.add(line);
}
}
}catch(IOException ioe) {
die("An error occured while reading the file specified by -includeTagsFile.");
}
}
//check that there isn't any overlap between include/exclude lists
Vector tempInclude = (Vector) forceIncludeTags.clone();
tempInclude.retainAll(forceExcludeTags);
if(tempInclude.size() > 0) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < tempInclude.size(); i++) {
String s = (String) tempInclude.elementAt(i);
sb.append(s).append(",");
}
die("The following markers appear in both the include and exclude lists: " + sb.toString());
}
if(tagRSquaredCutOff != -1) {
Options.setTaggerRsqCutoff(tagRSquaredCutOff);
}
} else if(forceExcludeTags != null || forceIncludeTags != null || tagRSquaredCutOff != -1) {
- die("-tagrSqCutoff, -excludeTags, -excludeTagsFile, -includeTags and -includeTagsFile cannot be used without -doTagging");
+ die("-tagrSqCutoff, -excludeTags, -excludeTagsFile, -includeTags and -includeTagsFile cannot be used without a tagging option");
}
if(chromosomeArg != null && hapmapFileName != null) {
argHandlerMessages.add("-chromosome flag ignored when loading hapmap file");
chromosomeArg = null;
}
if(chromosomeArg != null) {
Chromosome.setDataChrom("chr" + chromosomeArg);
}
}
private void die(String msg){
System.err.println(TITLE_STRING + " Fatal Error");
System.err.println(msg);
System.exit(1);
}
private void doBatch() {
Vector files;
File batchFile;
File dataFile;
String line;
StringTokenizer tok;
String infoMaybe =null;
files = new Vector();
if(batchFileName == null) {
return;
}
batchFile = new File(this.batchFileName);
if(!batchFile.exists()) {
System.out.println("batch file " + batchFileName + " does not exist");
System.exit(1);
}
if (!quietMode) System.out.println("Processing batch input file: " + batchFile);
try {
BufferedReader br = new BufferedReader(new FileReader(batchFile));
while( (line = br.readLine()) != null ) {
files.add(line);
}
br.close();
for(int i = 0;i<files.size();i++){
line = (String)files.get(i);
tok = new StringTokenizer(line);
infoMaybe = null;
if(tok.hasMoreTokens()){
dataFile = new File(tok.nextToken());
if(tok.hasMoreTokens()){
infoMaybe = tok.nextToken();
}
if(dataFile.exists()) {
String name = dataFile.getName();
if( name.substring(name.length()-4,name.length()).equalsIgnoreCase(".ped") ) {
processFile(name,PED_FILE,infoMaybe);
}
else if(name.substring(name.length()-5,name.length()).equalsIgnoreCase(".haps")) {
processFile(name,HAPS_FILE,infoMaybe);
}
else if(name.substring(name.length()-4,name.length()).equalsIgnoreCase(".hmp")){
processFile(name,HMP_FILE,null);
}
else{
if (!quietMode){
System.out.println("Filenames in batch file must end in .ped, .haps or .hmp\n" +
name + " is not properly formatted.");
}
}
}
else {
if(!quietMode){
System.out.println("file " + dataFile.getName() + " listed in the batch file could not be found");
}
}
}
}
}
catch(FileNotFoundException e){
System.out.println("the following error has occured:\n" + e.toString());
}
catch(IOException e){
System.out.println("the following error has occured:\n" + e.toString());
}
}
private File validateOutputFile(String fn){
File f = new File(fn);
if (f.exists() && !quietMode){
System.out.println("File " + f.getName() + " already exists and will be overwritten.");
}
if (!quietMode) System.out.println("Writing output to "+f.getName());
return f;
}
/**
* this method finds haplotypes and caclulates dprime without using any graphics
*/
private void processTextOnly(){
String fileName;
int fileType;
if(hapsFileName != null) {
fileName = hapsFileName;
fileType = HAPS_FILE;
}
else if (pedFileName != null){
fileName = pedFileName;
fileType = PED_FILE;
}else{
fileName = hapmapFileName;
fileType = HMP_FILE;
}
processFile(fileName,fileType,infoFileName);
}
/**
* this
* @param fileName name of the file to process
* @param fileType true means pedfilem false means hapsfile
* @param infoFileName
*/
private void processFile(String fileName, int fileType, String infoFileName){
try {
HaploData textData;
File outputFile;
File inputFile;
AssociationTestSet customAssocSet;
if(!quietMode && fileName != null){
System.out.println("Using data file: " + fileName);
}
inputFile = new File(fileName);
if(!inputFile.exists()){
System.out.println("input file: " + fileName + " does not exist");
System.exit(1);
}
textData = new HaploData();
//Vector result = null;
if(fileType == HAPS_FILE){
//read in haps file
textData.prepareHapsInput(inputFile);
}
else if (fileType == PED_FILE) {
//read in ped file
textData.linkageToChrom(inputFile, PED_FILE);
if(textData.getPedFile().isBogusParents()) {
System.out.println("Error: One or more individuals in the file reference non-existent parents.\nThese references have been ignored.");
}
if(textData.getPedFile().isHaploidHets()){
System.out.println("Error: One or more males in the file is heterozygous.\nThese genotypes have been ignored.");
}
}else{
//read in hapmapfile
textData.linkageToChrom(inputFile,HMP_FILE);
}
File infoFile = null;
if (infoFileName != null){
infoFile = new File(infoFileName);
}
textData.prepareMarkerInput(infoFile,textData.getPedFile().getHMInfo());
HashSet whiteListedCustomMarkers = new HashSet();
if (customAssocTestsFileName != null){
customAssocSet = new AssociationTestSet(customAssocTestsFileName);
whiteListedCustomMarkers = customAssocSet.getWhitelist();
}else{
customAssocSet = null;
}
Hashtable snpsByName = new Hashtable();
for(int i=0;i<Chromosome.getUnfilteredSize();i++) {
SNP snp = Chromosome.getUnfilteredMarker(i);
snpsByName.put(snp.getDisplayName(), snp);
}
if(forceIncludeTags != null) {
for(int i=0;i<forceIncludeTags.size();i++) {
if(snpsByName.containsKey(forceIncludeTags.get(i))) {
whiteListedCustomMarkers.add(snpsByName.get(forceIncludeTags.get(i)));
}
}
}
textData.getPedFile().setWhiteList(whiteListedCustomMarkers);
boolean[] markerResults = new boolean[Chromosome.getUnfilteredSize()];
Vector result = null;
result = textData.getPedFile().getResults();
//once check has been run we can filter the markers
for (int i = 0; i < result.size(); i++){
if (((((MarkerResult)result.get(i)).getRating() > 0 || skipCheck) &&
Chromosome.getUnfilteredMarker(i).getDupStatus() != 2)){
markerResults[i] = true;
}else{
markerResults[i] = false;
}
}
for (int i = 0; i < excludedMarkers.size(); i++){
int cur = ((Integer)excludedMarkers.elementAt(i)).intValue();
if (cur < 1 || cur > markerResults.length){
System.out.println("Excluded marker out of bounds: " + cur +
"\nMarkers must be between 1 and N, where N is the total number of markers.");
System.exit(1);
}else{
markerResults[cur-1] = false;
}
}
for(int i=0;i<Chromosome.getUnfilteredSize();i++) {
if(textData.getPedFile().isWhiteListed(Chromosome.getUnfilteredMarker(i))) {
markerResults[i] = true;
}
}
Chromosome.doFilter(markerResults);
if(!quietMode && infoFile != null){
System.out.println("Using marker information file: " + infoFile.getName());
}
if(outputCheck && result != null){
textData.getPedFile().saveCheckDataToText(validateOutputFile(fileName + ".CHECK"));
}
if(individualCheck && result != null){
IndividualDialog id = new IndividualDialog(textData);
id.printTable(validateOutputFile(fileName + ".INDCHECK"));
}
if(mendel && result != null){
MendelDialog md = new MendelDialog(textData);
md.printTable(validateOutputFile(fileName + ".MENDEL" ));
}
Vector cust = new Vector();
AssociationTestSet blockTestSet = null;
if(blockOutputType != -1){
textData.generateDPrimeTable();
Haplotype[][] haplos;
Haplotype[][] filtHaplos;
switch(blockOutputType){
case BLOX_GABRIEL:
outputFile = validateOutputFile(fileName + ".GABRIELblocks");
break;
case BLOX_4GAM:
outputFile = validateOutputFile(fileName + ".4GAMblocks");
break;
case BLOX_SPINE:
outputFile = validateOutputFile(fileName + ".SPINEblocks");
break;
case BLOX_CUSTOM:
outputFile = validateOutputFile(fileName + ".CUSTblocks");
//read in the blocks file
File blocksFile = new File(blockFileName);
if(!quietMode) {
System.out.println("Using custom blocks file " + blockFileName);
}
cust = textData.readBlocks(blocksFile);
break;
case BLOX_ALL:
//handled below, so we don't do anything here
outputFile = null;
break;
default:
outputFile = validateOutputFile(fileName + ".GABRIELblocks");
break;
}
//this handles output type ALL
if(blockOutputType == BLOX_ALL) {
outputFile = validateOutputFile(fileName + ".GABRIELblocks");
textData.guessBlocks(BLOX_GABRIEL);
haplos = textData.generateBlockHaplotypes(textData.blocks);
if (haplos != null){
filtHaplos = filterHaplos(haplos);
textData.pickTags(filtHaplos);
textData.saveHapsToText(haplos, textData.computeMultiDprime(filtHaplos), outputFile);
}else if (!quietMode){
System.out.println("Skipping block output: no valid Gabriel blocks.");
}
outputFile = validateOutputFile(fileName + ".4GAMblocks");
textData.guessBlocks(BLOX_4GAM);
haplos = textData.generateBlockHaplotypes(textData.blocks);
if (haplos != null){
filtHaplos = filterHaplos(haplos);
textData.pickTags(filtHaplos);
textData.saveHapsToText(haplos, textData.computeMultiDprime(filtHaplos), outputFile);
}else if (!quietMode){
System.out.println("Skipping block output: no valid 4 Gamete blocks.");
}
outputFile = validateOutputFile(fileName + ".SPINEblocks");
textData.guessBlocks(BLOX_SPINE);
haplos = textData.generateBlockHaplotypes(textData.blocks);
if (haplos != null){
filtHaplos = filterHaplos(haplos);
textData.pickTags(filtHaplos);
textData.saveHapsToText(haplos, textData.computeMultiDprime(filtHaplos), outputFile);
}else if (!quietMode){
System.out.println("Skipping block output: no valid LD Spine blocks.");
}
}else{
//guesses blocks based on output type determined above.
textData.guessBlocks(blockOutputType, cust);
haplos = textData.generateBlockHaplotypes(textData.blocks);
if (haplos != null){
filtHaplos = filterHaplos(haplos);
textData.pickTags(filtHaplos);
textData.saveHapsToText(haplos, textData.computeMultiDprime(filtHaplos), outputFile);
}else if (!quietMode){
System.out.println("Skipping block output: no valid blocks.");
}
}
if(Options.getAssocTest() == ASSOC_TRIO || Options.getAssocTest() == ASSOC_CC) {
if (blockOutputType == BLOX_ALL){
System.out.println("Haplotype association results cannot be used with block output \"ALL\"");
}else{
if (haplos != null){
blockTestSet = new AssociationTestSet(haplos,null);
blockTestSet.saveHapsToText(validateOutputFile(fileName + ".HAPASSOC"));
}else if (!quietMode){
System.out.println("Skipping block association output: no valid blocks.");
}
}
}
}
if(outputDprime) {
outputFile = validateOutputFile(fileName + ".LD");
if (textData.dpTable != null){
textData.saveDprimeToText(outputFile, TABLE_TYPE, 0, Chromosome.getSize());
}else{
textData.saveDprimeToText(outputFile, LIVE_TYPE, 0, Chromosome.getSize());
}
}
if (outputPNG || outputCompressedPNG){
outputFile = validateOutputFile(fileName + ".LD.PNG");
if (textData.dpTable == null){
textData.generateDPrimeTable();
textData.guessBlocks(BLOX_CUSTOM, new Vector());
}
if (trackFileName != null){
textData.readAnalysisTrack(new File(trackFileName));
if(!quietMode) {
System.out.println("Using analysis track file " + trackFileName);
}
}
DPrimeDisplay dpd = new DPrimeDisplay(textData);
BufferedImage i = dpd.export(0,Chromosome.getUnfilteredSize(),outputCompressedPNG);
try{
Jimi.putImage("image/png", i, outputFile.getAbsolutePath());
}catch(JimiException je){
System.out.println(je.getMessage());
}
}
AssociationTestSet markerTestSet =null;
if(Options.getAssocTest() == ASSOC_TRIO || Options.getAssocTest() == ASSOC_CC){
if (randomizeAffection){
Vector aff = new Vector();
int j=0, k=0;
for (int i = 0; i < textData.getPedFile().getNumIndividuals(); i++){
if (i%2 == 0){
aff.add(new Integer(1));
j++;
}else{
aff.add(new Integer(2));
k++;
}
}
Collections.shuffle(aff);
markerTestSet = new AssociationTestSet(textData.getPedFile(),aff,null,Chromosome.getAllMarkers());
}else{
markerTestSet = new AssociationTestSet(textData.getPedFile(),null,null,Chromosome.getAllMarkers());
}
markerTestSet.saveSNPsToText(validateOutputFile(fileName + ".ASSOC"));
}
if(customAssocSet != null) {
if(!quietMode) {
System.out.println("Using custom association test file " + customAssocTestsFileName);
}
try {
customAssocSet.setPermTests(doPermutationTest);
customAssocSet.runFileTests(textData,markerTestSet.getMarkerAssociationResults());
customAssocSet.saveResultsToText(validateOutputFile(fileName + ".CUSTASSOC"));
}catch(IOException ioe) {
System.out.println("An error occured writing the custom association results file.");
customAssocSet = null;
}
}
if(doPermutationTest) {
AssociationTestSet permTests = new AssociationTestSet();
permTests.cat(markerTestSet);
if(blockTestSet != null) {
permTests.cat(blockTestSet);
}
final PermutationTestSet pts = new PermutationTestSet(permutationCount,textData.getPedFile(),customAssocSet,permTests);
Thread permThread = new Thread(new Runnable() {
public void run() {
if (pts.isCustom()){
pts.doPermutations(PermutationTestSet.CUSTOM);
}else{
pts.doPermutations(PermutationTestSet.SINGLE_PLUS_BLOCKS);
}
}
});
permThread.start();
if(!quietMode) {
System.out.println("Starting " + permutationCount + " permutation tests (each . printed represents 1% of tests completed)");
}
int dotsPrinted =0;
while(pts.getPermutationCount() - pts.getPermutationsPerformed() > 0) {
while(( (double)pts.getPermutationsPerformed() / pts.getPermutationCount())*100 > dotsPrinted) {
System.out.print(".");
dotsPrinted++;
}
try{
Thread.sleep(100);
}catch(InterruptedException ie) {}
}
System.out.println();
try {
pts.writeResultsToFile(validateOutputFile(fileName + ".PERMUT"));
} catch(IOException ioe) {
System.out.println("An error occured while writing the permutation test results to file.");
}
}
if(tagging != Tagger.NONE) {
if(textData.dpTable == null) {
textData.generateDPrimeTable();
}
Vector snps = Chromosome.getAllMarkers();
HashSet names = new HashSet();
for (int i = 0; i < snps.size(); i++) {
SNP snp = (SNP) snps.elementAt(i);
names.add(snp.getDisplayName());
}
HashSet filteredNames = new HashSet();
for(int i=0;i<Chromosome.getSize();i++) {
filteredNames.add(Chromosome.getMarker(i).getDisplayName());
}
Vector sitesToCapture = new Vector();
for(int i=0;i<Chromosome.getSize();i++) {
sitesToCapture.add(Chromosome.getMarker(i));
}
for (int i = 0; i < forceIncludeTags.size(); i++) {
String s = (String) forceIncludeTags.elementAt(i);
if(!names.contains(s) && !quietMode) {
System.out.println("Warning: skipping marker " + s + " in the list of forced included tags since I don't know about it.");
}
}
for (int i = 0; i < forceExcludeTags.size(); i++) {
String s = (String) forceExcludeTags.elementAt(i);
if(!names.contains(s) && !quietMode) {
System.out.println("Warning: skipping marker " + s + " in the list of forced excluded tags since I don't know about it.");
}
}
//chuck out filtered jazz from excludes, and nonexistent markers from both
forceExcludeTags.retainAll(filteredNames);
forceIncludeTags.retainAll(names);
if(!quietMode) {
System.out.println("Starting tagging.");
}
TaggerController tc = new TaggerController(textData,forceIncludeTags,forceExcludeTags,sitesToCapture,
tagging,maxNumTags,findTags);
tc.runTagger();
while(!tc.isTaggingCompleted()) {
try {
Thread.sleep(100);
}catch(InterruptedException ie) {}
}
tc.saveResultsToFile(validateOutputFile(fileName + ".TAGS"));
tc.dumpTests(validateOutputFile(fileName + ".TESTS"));
//todo: I don't like this at the moment, removed subject to further consideration.
//tc.dumpTags(validateOutputFile(fileName + ".TAGSNPS"));
}
}
catch(IOException e){
System.err.println("An error has occured:");
System.err.println(e.getMessage());
}
catch(HaploViewException e){
System.err.println(e.getMessage());
}
catch(PedFileException pfe) {
System.err.println(pfe.getMessage());
}
catch(TaggerException te){
System.err.println(te.getMessage());
}
}
public Haplotype[][] filterHaplos(Haplotype[][] haplos) {
if (haplos == null){
return null;
}
Haplotype[][] filteredHaplos = new Haplotype[haplos.length][];
for (int i = 0; i < haplos.length; i++){
Vector tempVector = new Vector();
for (int j = 0; j < haplos[i].length; j++){
if (haplos[i][j].getPercentage() > Options.getHaplotypeDisplayThreshold()){
tempVector.add(haplos[i][j]);
}
}
filteredHaplos[i] = new Haplotype[tempVector.size()];
tempVector.copyInto(filteredHaplos[i]);
}
return filteredHaplos;
}
}
| false | true | private void argHandler(String[] args){
argHandlerMessages = new Vector();
int maxDistance = -1;
//this means that user didn't specify any output type if it doesn't get changed below
blockOutputType = -1;
double hapThresh = -1;
double minimumMAF=-1;
double spacingThresh = -1;
double minimumGenoPercent = -1;
double hwCutoff = -1;
double missingCutoff = -1;
int maxMendel = -1;
boolean assocTDT = false;
boolean assocCC = false;
permutationCount = 0;
tagging = Tagger.NONE;
maxNumTags = Tagger.DEFAULT_MAXNUMTAGS;
findTags = true;
double cutHighCI = -1;
double cutLowCI = -1;
double mafThresh = -1;
double recHighCI = -1;
double informFrac = -1;
double fourGameteCutoff = -1;
double spineDP = -1;
for(int i =0; i < args.length; i++) {
if(args[i].equalsIgnoreCase("-help") || args[i].equalsIgnoreCase("-h")) {
System.out.println(HELP_OUTPUT);
System.exit(0);
}
else if(args[i].equalsIgnoreCase("-n") || args[i].equalsIgnoreCase("-nogui")) {
nogui = true;
}
else if(args[i].equalsIgnoreCase("-p") || args[i].equalsIgnoreCase("-pedfile")) {
i++;
if( i>=args.length || (args[i].charAt(0) == '-')){
die(args[i-1] + " requires a filename");
}
else{
if(pedFileName != null){
argHandlerMessages.add("multiple "+args[i-1] + " arguments found. only last pedfile listed will be used");
}
pedFileName = args[i];
}
}
else if (args[i].equalsIgnoreCase("-pcloadletter")){
die("PC LOADLETTER?! What the fuck does that mean?!");
}
else if (args[i].equalsIgnoreCase("-skipcheck") || args[i].equalsIgnoreCase("--skipcheck")){
skipCheck = true;
}
else if (args[i].equalsIgnoreCase("-excludeMarkers")){
i++;
if(i>=args.length || (args[i].charAt(0) == '-')){
die("-excludeMarkers requires a list of markers");
}
else {
StringTokenizer str = new StringTokenizer(args[i],",");
try {
StringBuffer sb = new StringBuffer();
if (!quietMode) sb.append("Excluding markers: ");
while(str.hasMoreTokens()) {
String token = str.nextToken();
if(token.indexOf("..") != -1) {
int lastIndex = token.indexOf("..");
int rangeStart = Integer.parseInt(token.substring(0,lastIndex));
int rangeEnd = Integer.parseInt(token.substring(lastIndex+2,token.length()));
for(int j=rangeStart;j<=rangeEnd;j++) {
if (!quietMode) sb.append(j+" ");
excludedMarkers.add(new Integer(j));
}
} else {
if (!quietMode) sb.append(token+" ");
excludedMarkers.add(new Integer(token));
}
}
if (!quietMode) argHandlerMessages.add(sb.toString());
} catch(NumberFormatException nfe) {
die("-excludeMarkers argument should be of the format: 1,3,5..8,12");
}
}
}
else if(args[i].equalsIgnoreCase("-ha") || args[i].equalsIgnoreCase("-l") || args[i].equalsIgnoreCase("-haps")) {
i++;
if(i>=args.length || ((args[i].charAt(0)) == '-')){
die(args[i-1] + " requires a filename");
}
else{
if(hapsFileName != null){
argHandlerMessages.add("multiple "+args[i-1] + " arguments found. only last haps file listed will be used");
}
hapsFileName = args[i];
}
}
else if(args[i].equalsIgnoreCase("-i") || args[i].equalsIgnoreCase("-info")) {
i++;
if(i>=args.length || ((args[i].charAt(0)) == '-')){
die(args[i-1] + " requires a filename");
}
else{
if(infoFileName != null){
argHandlerMessages.add("multiple "+args[i-1] + " arguments found. only last info file listed will be used");
}
infoFileName = args[i];
}
} else if (args[i].equalsIgnoreCase("-a") || args[i].equalsIgnoreCase("-hapmap")){
i++;
if(i>=args.length || ((args[i].charAt(0)) == '-')){
die(args[i-1] + " requires a filename");
}
else{
if(hapmapFileName != null){
argHandlerMessages.add("multiple "+args[i-1] + " arguments found. only last hapmap file listed will be used");
}
hapmapFileName = args[i];
}
}
else if(args[i].equalsIgnoreCase("-k") || args[i].equalsIgnoreCase("-blocks")) {
i++;
if (!(i>=args.length) && !((args[i].charAt(0)) == '-')){
blockFileName = args[i];
blockOutputType = BLOX_CUSTOM;
}else{
die(args[i-1] + " requires a filename");
}
}
else if (args[i].equalsIgnoreCase("-png")){
outputPNG = true;
}
else if (args[i].equalsIgnoreCase("-smallpng") || args[i].equalsIgnoreCase("-compressedPNG")){
outputCompressedPNG = true;
}
else if (args[i].equalsIgnoreCase("-track")){
i++;
if (!(i>=args.length) && !((args[i].charAt(0)) == '-')){
trackFileName = args[i];
}else{
die("-track requires a filename");
}
}
else if(args[i].equalsIgnoreCase("-o") || args[i].equalsIgnoreCase("-output") || args[i].equalsIgnoreCase("-blockoutput")) {
i++;
if(!(i>=args.length) && !((args[i].charAt(0)) == '-')){
if(blockOutputType != -1){
die("Only one block output type argument is allowed.");
}
if(args[i].equalsIgnoreCase("SFS") || args[i].equalsIgnoreCase("GAB")){
blockOutputType = BLOX_GABRIEL;
}
else if(args[i].equalsIgnoreCase("GAM")){
blockOutputType = BLOX_4GAM;
}
else if(args[i].equalsIgnoreCase("MJD") || args[i].equalsIgnoreCase("SPI")){
blockOutputType = BLOX_SPINE;
}
else if(args[i].equalsIgnoreCase("ALL")) {
blockOutputType = BLOX_ALL;
}
}
else {
//defaults to SFS output
blockOutputType = BLOX_GABRIEL;
i--;
}
}
else if(args[i].equalsIgnoreCase("-d") || args[i].equalsIgnoreCase("--dprime") || args[i].equalsIgnoreCase("-dprime")) {
outputDprime = true;
}
else if (args[i].equalsIgnoreCase("-c") || args[i].equalsIgnoreCase("-check")){
outputCheck = true;
}
else if (args[i].equalsIgnoreCase("-indcheck")){
individualCheck = true;
}
else if (args[i].equalsIgnoreCase("-mendel")){
mendel = true;
}
else if(args[i].equalsIgnoreCase("-m") || args[i].equalsIgnoreCase("-maxdistance")) {
i++;
maxDistance = getIntegerArg(args,i);
}
else if(args[i].equalsIgnoreCase("-b") || args[i].equalsIgnoreCase("-batch")) {
//batch mode
i++;
if(i>=args.length || ((args[i].charAt(0)) == '-')){
die(args[i-1] + " requires a filename");
}
else{
if(batchFileName != null){
argHandlerMessages.add("multiple " + args[i-1] + " arguments found. only last batch file listed will be used");
}
batchFileName = args[i];
}
}
else if(args[i].equalsIgnoreCase("-hapthresh")) {
i++;
hapThresh = getDoubleArg(args,i,0,1);
}
else if(args[i].equalsIgnoreCase("-spacing")) {
i++;
spacingThresh = getDoubleArg(args,i,0,1);
}
else if(args[i].equalsIgnoreCase("-minMAF")) {
i++;
minimumMAF = getDoubleArg(args,i,0,0.5);
}
else if(args[i].equalsIgnoreCase("-minGeno") || args[i].equalsIgnoreCase("-minGenoPercent")) {
i++;
minimumGenoPercent = getDoubleArg(args,i,0,1);
}
else if(args[i].equalsIgnoreCase("-hwcutoff")) {
i++;
hwCutoff = getDoubleArg(args,i,0,1);
}
else if(args[i].equalsIgnoreCase("-maxMendel") ) {
i++;
maxMendel = getIntegerArg(args,i);
}
else if(args[i].equalsIgnoreCase("-missingcutoff")) {
i++;
missingCutoff = getDoubleArg(args,i,0,1);
}
else if(args[i].equalsIgnoreCase("-assoctdt")) {
assocTDT = true;
}
else if(args[i].equalsIgnoreCase("-assoccc")) {
assocCC = true;
}
else if(args[i].equalsIgnoreCase("-randomcc")){
assocCC = true;
randomizeAffection = true;
}
else if(args[i].equalsIgnoreCase("-ldcolorscheme")) {
i++;
if(!(i>=args.length) && !((args[i].charAt(0)) == '-')){
if(args[i].equalsIgnoreCase("default")){
Options.setLDColorScheme(STD_SCHEME);
}
else if(args[i].equalsIgnoreCase("RSQ")){
Options.setLDColorScheme(RSQ_SCHEME);
}
else if(args[i].equalsIgnoreCase("DPALT") ){
Options.setLDColorScheme(WMF_SCHEME);
}
else if(args[i].equalsIgnoreCase("GAB")) {
Options.setLDColorScheme(GAB_SCHEME);
}
else if(args[i].equalsIgnoreCase("GAM")) {
Options.setLDColorScheme(GAM_SCHEME);
}
else if(args[i].equalsIgnoreCase("GOLD")) {
Options.setLDColorScheme(GOLD_SCHEME);
}
}
else {
//defaults to STD color scheme
Options.setLDColorScheme(STD_SCHEME);
i--;
}
}
else if(args[i].equalsIgnoreCase("-blockCutHighCI")) {
i++;
cutHighCI = getDoubleArg(args,i,0,1);
}
else if(args[i].equalsIgnoreCase("-blockCutLowCI")) {
i++;
cutLowCI = getDoubleArg(args,i,0,1);
}
else if(args[i].equalsIgnoreCase("-blockMafThresh")) {
i++;
mafThresh = getDoubleArg(args,i,0,1);
}
else if(args[i].equalsIgnoreCase("-blockRecHighCI")) {
i++;
recHighCI = getDoubleArg(args,i,0,1);
}
else if(args[i].equalsIgnoreCase("-blockInformFrac")) {
i++;
informFrac = getDoubleArg(args,i,0,1);
}
else if(args[i].equalsIgnoreCase("-block4GamCut")) {
i++;
fourGameteCutoff = getDoubleArg(args,i,0,1);
}
else if(args[i].equalsIgnoreCase("-blockSpineDP")) {
i++;
spineDP = getDoubleArg(args,i,0,1);
}
else if(args[i].equalsIgnoreCase("-permtests")) {
i++;
doPermutationTest = true;
permutationCount = getIntegerArg(args,i);
}
else if(args[i].equalsIgnoreCase("-customassoc")) {
i++;
if (!(i>=args.length) && !((args[i].charAt(0)) == '-')){
customAssocTestsFileName = args[i];
}else{
die(args[i-1] + " requires a filename");
}
}
else if(args[i].equalsIgnoreCase("-aggressiveTagging")) {
tagging = Tagger.AGGRESSIVE_TRIPLE;
}
else if (args[i].equalsIgnoreCase("-pairwiseTagging")){
tagging = Tagger.PAIRWISE_ONLY;
}
else if (args[i].equalsIgnoreCase("-printalltags")){
Options.setPrintAllTags(true);
}
else if(args[i].equalsIgnoreCase("-maxNumTags")){
i++;
maxNumTags = getIntegerArg(args,i);
}
else if(args[i].equalsIgnoreCase("-tagrSqCutoff")) {
i++;
tagRSquaredCutOff = getDoubleArg(args,i,0,1);
}
else if (args[i].equalsIgnoreCase("-dontaddtags")){
findTags = false;
}
else if(args[i].equalsIgnoreCase("-tagLODCutoff")) {
i++;
Options.setTaggerLODCutoff(getDoubleArg(args,i,0,100000));
}
else if(args[i].equalsIgnoreCase("-includeTags")) {
i++;
if(i>=args.length || args[i].charAt(0) == '-') {
die(args[i-1] + " requires a list of marker names.");
}
StringTokenizer str = new StringTokenizer(args[i],",");
forceIncludeTags = new Vector();
while(str.hasMoreTokens()) {
forceIncludeTags.add(str.nextToken());
}
}
else if (args[i].equalsIgnoreCase("-includeTagsFile")) {
i++;
if(!(i>=args.length) && !(args[i].charAt(0) == '-')) {
forceIncludeFileName =args[i];
}else {
die(args[i-1] + " requires a filename");
}
}
else if(args[i].equalsIgnoreCase("-excludeTags")) {
i++;
if(i>=args.length || args[i].charAt(0) == '-') {
die("-excludeTags requires a list of marker names.");
}
StringTokenizer str = new StringTokenizer(args[i],",");
forceExcludeTags = new Vector();
while(str.hasMoreTokens()) {
forceExcludeTags.add(str.nextToken());
}
}
else if (args[i].equalsIgnoreCase("-excludeTagsFile")) {
i++;
if(!(i>=args.length) && !(args[i].charAt(0) == '-')) {
forceExcludeFileName =args[i];
}else {
die(args[i-1] + " requires a filename");
}
}
else if(args[i].equalsIgnoreCase("-chromosome") || args[i].equalsIgnoreCase("-chr")) {
i++;
if(!(i>=args.length) && !(args[i].charAt(0) == '-')) {
chromosomeArg =args[i];
}else {
die(args[i-1] + " requires a chromosome name");
}
}
else if(args[i].equalsIgnoreCase("-q") || args[i].equalsIgnoreCase("-quiet")) {
quietMode = true;
}
else {
die("invalid parameter specified: " + args[i]);
}
}
int countOptions = 0;
if(pedFileName != null) {
countOptions++;
}
if(hapsFileName != null) {
countOptions++;
}
if(hapmapFileName != null) {
countOptions++;
}
if(batchFileName != null) {
countOptions++;
}
if(countOptions > 1) {
die("Only one genotype input file may be specified on the command line.");
}
else if(countOptions == 0 && nogui) {
die("You must specify a genotype input file.");
}
//mess with vars, set defaults, etc
if(skipCheck && !quietMode) {
argHandlerMessages.add("Skipping genotype file check");
}
if(maxDistance == -1){
maxDistance = MAXDIST_DEFAULT;
}else{
if (!quietMode) argHandlerMessages.add("Max LD comparison distance = " +maxDistance);
}
Options.setMaxDistance(maxDistance);
if(hapThresh != -1) {
Options.setHaplotypeDisplayThreshold(hapThresh);
if (!quietMode) argHandlerMessages.add("Haplotype display threshold = " + hapThresh);
}
if(minimumMAF != -1) {
CheckData.mafCut = minimumMAF;
if (!quietMode) argHandlerMessages.add("Minimum MAF = " + minimumMAF);
}
if(minimumGenoPercent != -1) {
CheckData.failedGenoCut = (int)(minimumGenoPercent*100);
if (!quietMode) argHandlerMessages.add("Minimum SNP genotype % = " + minimumGenoPercent);
}
if(hwCutoff != -1) {
CheckData.hwCut = hwCutoff;
if (!quietMode) argHandlerMessages.add("Hardy Weinberg equilibrium p-value cutoff = " + hwCutoff);
}
if(maxMendel != -1) {
CheckData.numMendErrCut = maxMendel;
if (!quietMode) argHandlerMessages.add("Maximum number of Mendel errors = "+maxMendel);
}
if(spacingThresh != -1) {
Options.setSpacingThreshold(spacingThresh);
if (!quietMode) argHandlerMessages.add("LD display spacing value = "+spacingThresh);
}
if(missingCutoff != -1) {
Options.setMissingThreshold(missingCutoff);
if (!quietMode) argHandlerMessages.add("Maximum amount of missing data allowed per individual = "+missingCutoff);
}
if(cutHighCI != -1) {
FindBlocks.cutHighCI = cutHighCI;
}
if(cutLowCI != -1) {
FindBlocks.cutLowCI = cutLowCI;
}
if(mafThresh != -1) {
FindBlocks.mafThresh = mafThresh;
}
if(recHighCI != -1) {
FindBlocks.recHighCI = recHighCI;
}
if(informFrac != -1) {
FindBlocks.informFrac = informFrac;
}
if(fourGameteCutoff != -1) {
FindBlocks.fourGameteCutoff = fourGameteCutoff;
}
if(spineDP != -1) {
FindBlocks.spineDP = spineDP;
}
if(assocTDT) {
Options.setAssocTest(ASSOC_TRIO);
}else if(assocCC) {
Options.setAssocTest(ASSOC_CC);
}
if (Options.getAssocTest() != ASSOC_NONE && infoFileName == null && hapmapFileName == null) {
die("A marker info file must be specified when performing association tests.");
}
if(doPermutationTest) {
if(!assocCC && !assocTDT) {
die("An association test type must be specified for permutation tests to be performed.");
}
}
if(customAssocTestsFileName != null) {
if(!assocCC && !assocTDT) {
die("An association test type must be specified when using a custom association test file.");
}
if(infoFileName == null) {
die("A marker info file must be specified when using a custom association test file.");
}
}
if(tagging != Tagger.NONE) {
if(infoFileName == null && hapmapFileName == null) {
die("A marker info file must be specified when using -doTagging");
}
if(forceExcludeTags == null) {
forceExcludeTags = new Vector();
} else if (forceExcludeFileName != null) {
die("-excludeTags and -excludeTagsFile cannot both be used");
}
if(forceExcludeFileName != null) {
File excludeFile = new File(forceExcludeFileName);
forceExcludeTags = new Vector();
try {
BufferedReader br = new BufferedReader(new FileReader(excludeFile));
String line;
while((line = br.readLine()) != null) {
if(line.length() > 0 && line.charAt(0) != '#'){
forceExcludeTags.add(line);
}
}
}catch(IOException ioe) {
die("An error occured while reading the file specified by -excludeTagsFile.");
}
}
if(forceIncludeTags == null ) {
forceIncludeTags = new Vector();
} else if (forceIncludeFileName != null) {
die("-includeTags and -includeTagsFile cannot both be used");
}
if(forceIncludeFileName != null) {
File includeFile = new File(forceIncludeFileName);
forceIncludeTags = new Vector();
try {
BufferedReader br = new BufferedReader(new FileReader(includeFile));
String line;
while((line = br.readLine()) != null) {
if(line.length() > 0 && line.charAt(0) != '#'){
forceIncludeTags.add(line);
}
}
}catch(IOException ioe) {
die("An error occured while reading the file specified by -includeTagsFile.");
}
}
//check that there isn't any overlap between include/exclude lists
Vector tempInclude = (Vector) forceIncludeTags.clone();
tempInclude.retainAll(forceExcludeTags);
if(tempInclude.size() > 0) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < tempInclude.size(); i++) {
String s = (String) tempInclude.elementAt(i);
sb.append(s).append(",");
}
die("The following markers appear in both the include and exclude lists: " + sb.toString());
}
if(tagRSquaredCutOff != -1) {
Options.setTaggerRsqCutoff(tagRSquaredCutOff);
}
} else if(forceExcludeTags != null || forceIncludeTags != null || tagRSquaredCutOff != -1) {
die("-tagrSqCutoff, -excludeTags, -excludeTagsFile, -includeTags and -includeTagsFile cannot be used without -doTagging");
}
if(chromosomeArg != null && hapmapFileName != null) {
argHandlerMessages.add("-chromosome flag ignored when loading hapmap file");
chromosomeArg = null;
}
if(chromosomeArg != null) {
Chromosome.setDataChrom("chr" + chromosomeArg);
}
}
| private void argHandler(String[] args){
argHandlerMessages = new Vector();
int maxDistance = -1;
//this means that user didn't specify any output type if it doesn't get changed below
blockOutputType = -1;
double hapThresh = -1;
double minimumMAF=-1;
double spacingThresh = -1;
double minimumGenoPercent = -1;
double hwCutoff = -1;
double missingCutoff = -1;
int maxMendel = -1;
boolean assocTDT = false;
boolean assocCC = false;
permutationCount = 0;
tagging = Tagger.NONE;
maxNumTags = Tagger.DEFAULT_MAXNUMTAGS;
findTags = true;
double cutHighCI = -1;
double cutLowCI = -1;
double mafThresh = -1;
double recHighCI = -1;
double informFrac = -1;
double fourGameteCutoff = -1;
double spineDP = -1;
for(int i =0; i < args.length; i++) {
if(args[i].equalsIgnoreCase("-help") || args[i].equalsIgnoreCase("-h")) {
System.out.println(HELP_OUTPUT);
System.exit(0);
}
else if(args[i].equalsIgnoreCase("-n") || args[i].equalsIgnoreCase("-nogui")) {
nogui = true;
}
else if(args[i].equalsIgnoreCase("-p") || args[i].equalsIgnoreCase("-pedfile")) {
i++;
if( i>=args.length || (args[i].charAt(0) == '-')){
die(args[i-1] + " requires a filename");
}
else{
if(pedFileName != null){
argHandlerMessages.add("multiple "+args[i-1] + " arguments found. only last pedfile listed will be used");
}
pedFileName = args[i];
}
}
else if (args[i].equalsIgnoreCase("-pcloadletter")){
die("PC LOADLETTER?! What the fuck does that mean?!");
}
else if (args[i].equalsIgnoreCase("-skipcheck") || args[i].equalsIgnoreCase("--skipcheck")){
skipCheck = true;
}
else if (args[i].equalsIgnoreCase("-excludeMarkers")){
i++;
if(i>=args.length || (args[i].charAt(0) == '-')){
die("-excludeMarkers requires a list of markers");
}
else {
StringTokenizer str = new StringTokenizer(args[i],",");
try {
StringBuffer sb = new StringBuffer();
if (!quietMode) sb.append("Excluding markers: ");
while(str.hasMoreTokens()) {
String token = str.nextToken();
if(token.indexOf("..") != -1) {
int lastIndex = token.indexOf("..");
int rangeStart = Integer.parseInt(token.substring(0,lastIndex));
int rangeEnd = Integer.parseInt(token.substring(lastIndex+2,token.length()));
for(int j=rangeStart;j<=rangeEnd;j++) {
if (!quietMode) sb.append(j+" ");
excludedMarkers.add(new Integer(j));
}
} else {
if (!quietMode) sb.append(token+" ");
excludedMarkers.add(new Integer(token));
}
}
if (!quietMode) argHandlerMessages.add(sb.toString());
} catch(NumberFormatException nfe) {
die("-excludeMarkers argument should be of the format: 1,3,5..8,12");
}
}
}
else if(args[i].equalsIgnoreCase("-ha") || args[i].equalsIgnoreCase("-l") || args[i].equalsIgnoreCase("-haps")) {
i++;
if(i>=args.length || ((args[i].charAt(0)) == '-')){
die(args[i-1] + " requires a filename");
}
else{
if(hapsFileName != null){
argHandlerMessages.add("multiple "+args[i-1] + " arguments found. only last haps file listed will be used");
}
hapsFileName = args[i];
}
}
else if(args[i].equalsIgnoreCase("-i") || args[i].equalsIgnoreCase("-info")) {
i++;
if(i>=args.length || ((args[i].charAt(0)) == '-')){
die(args[i-1] + " requires a filename");
}
else{
if(infoFileName != null){
argHandlerMessages.add("multiple "+args[i-1] + " arguments found. only last info file listed will be used");
}
infoFileName = args[i];
}
} else if (args[i].equalsIgnoreCase("-a") || args[i].equalsIgnoreCase("-hapmap")){
i++;
if(i>=args.length || ((args[i].charAt(0)) == '-')){
die(args[i-1] + " requires a filename");
}
else{
if(hapmapFileName != null){
argHandlerMessages.add("multiple "+args[i-1] + " arguments found. only last hapmap file listed will be used");
}
hapmapFileName = args[i];
}
}
else if(args[i].equalsIgnoreCase("-k") || args[i].equalsIgnoreCase("-blocks")) {
i++;
if (!(i>=args.length) && !((args[i].charAt(0)) == '-')){
blockFileName = args[i];
blockOutputType = BLOX_CUSTOM;
}else{
die(args[i-1] + " requires a filename");
}
}
else if (args[i].equalsIgnoreCase("-png")){
outputPNG = true;
}
else if (args[i].equalsIgnoreCase("-smallpng") || args[i].equalsIgnoreCase("-compressedPNG")){
outputCompressedPNG = true;
}
else if (args[i].equalsIgnoreCase("-track")){
i++;
if (!(i>=args.length) && !((args[i].charAt(0)) == '-')){
trackFileName = args[i];
}else{
die("-track requires a filename");
}
}
else if(args[i].equalsIgnoreCase("-o") || args[i].equalsIgnoreCase("-output") || args[i].equalsIgnoreCase("-blockoutput")) {
i++;
if(!(i>=args.length) && !((args[i].charAt(0)) == '-')){
if(blockOutputType != -1){
die("Only one block output type argument is allowed.");
}
if(args[i].equalsIgnoreCase("SFS") || args[i].equalsIgnoreCase("GAB")){
blockOutputType = BLOX_GABRIEL;
}
else if(args[i].equalsIgnoreCase("GAM")){
blockOutputType = BLOX_4GAM;
}
else if(args[i].equalsIgnoreCase("MJD") || args[i].equalsIgnoreCase("SPI")){
blockOutputType = BLOX_SPINE;
}
else if(args[i].equalsIgnoreCase("ALL")) {
blockOutputType = BLOX_ALL;
}
}
else {
//defaults to SFS output
blockOutputType = BLOX_GABRIEL;
i--;
}
}
else if(args[i].equalsIgnoreCase("-d") || args[i].equalsIgnoreCase("--dprime") || args[i].equalsIgnoreCase("-dprime")) {
outputDprime = true;
}
else if (args[i].equalsIgnoreCase("-c") || args[i].equalsIgnoreCase("-check")){
outputCheck = true;
}
else if (args[i].equalsIgnoreCase("-indcheck")){
individualCheck = true;
}
else if (args[i].equalsIgnoreCase("-mendel")){
mendel = true;
}
else if(args[i].equalsIgnoreCase("-m") || args[i].equalsIgnoreCase("-maxdistance")) {
i++;
maxDistance = getIntegerArg(args,i);
}
else if(args[i].equalsIgnoreCase("-b") || args[i].equalsIgnoreCase("-batch")) {
//batch mode
i++;
if(i>=args.length || ((args[i].charAt(0)) == '-')){
die(args[i-1] + " requires a filename");
}
else{
if(batchFileName != null){
argHandlerMessages.add("multiple " + args[i-1] + " arguments found. only last batch file listed will be used");
}
batchFileName = args[i];
}
}
else if(args[i].equalsIgnoreCase("-hapthresh")) {
i++;
hapThresh = getDoubleArg(args,i,0,1);
}
else if(args[i].equalsIgnoreCase("-spacing")) {
i++;
spacingThresh = getDoubleArg(args,i,0,1);
}
else if(args[i].equalsIgnoreCase("-minMAF")) {
i++;
minimumMAF = getDoubleArg(args,i,0,0.5);
}
else if(args[i].equalsIgnoreCase("-minGeno") || args[i].equalsIgnoreCase("-minGenoPercent")) {
i++;
minimumGenoPercent = getDoubleArg(args,i,0,1);
}
else if(args[i].equalsIgnoreCase("-hwcutoff")) {
i++;
hwCutoff = getDoubleArg(args,i,0,1);
}
else if(args[i].equalsIgnoreCase("-maxMendel") ) {
i++;
maxMendel = getIntegerArg(args,i);
}
else if(args[i].equalsIgnoreCase("-missingcutoff")) {
i++;
missingCutoff = getDoubleArg(args,i,0,1);
}
else if(args[i].equalsIgnoreCase("-assoctdt")) {
assocTDT = true;
}
else if(args[i].equalsIgnoreCase("-assoccc")) {
assocCC = true;
}
else if(args[i].equalsIgnoreCase("-randomcc")){
assocCC = true;
randomizeAffection = true;
}
else if(args[i].equalsIgnoreCase("-ldcolorscheme")) {
i++;
if(!(i>=args.length) && !((args[i].charAt(0)) == '-')){
if(args[i].equalsIgnoreCase("default")){
Options.setLDColorScheme(STD_SCHEME);
}
else if(args[i].equalsIgnoreCase("RSQ")){
Options.setLDColorScheme(RSQ_SCHEME);
}
else if(args[i].equalsIgnoreCase("DPALT") ){
Options.setLDColorScheme(WMF_SCHEME);
}
else if(args[i].equalsIgnoreCase("GAB")) {
Options.setLDColorScheme(GAB_SCHEME);
}
else if(args[i].equalsIgnoreCase("GAM")) {
Options.setLDColorScheme(GAM_SCHEME);
}
else if(args[i].equalsIgnoreCase("GOLD")) {
Options.setLDColorScheme(GOLD_SCHEME);
}
}
else {
//defaults to STD color scheme
Options.setLDColorScheme(STD_SCHEME);
i--;
}
}
else if(args[i].equalsIgnoreCase("-blockCutHighCI")) {
i++;
cutHighCI = getDoubleArg(args,i,0,1);
}
else if(args[i].equalsIgnoreCase("-blockCutLowCI")) {
i++;
cutLowCI = getDoubleArg(args,i,0,1);
}
else if(args[i].equalsIgnoreCase("-blockMafThresh")) {
i++;
mafThresh = getDoubleArg(args,i,0,1);
}
else if(args[i].equalsIgnoreCase("-blockRecHighCI")) {
i++;
recHighCI = getDoubleArg(args,i,0,1);
}
else if(args[i].equalsIgnoreCase("-blockInformFrac")) {
i++;
informFrac = getDoubleArg(args,i,0,1);
}
else if(args[i].equalsIgnoreCase("-block4GamCut")) {
i++;
fourGameteCutoff = getDoubleArg(args,i,0,1);
}
else if(args[i].equalsIgnoreCase("-blockSpineDP")) {
i++;
spineDP = getDoubleArg(args,i,0,1);
}
else if(args[i].equalsIgnoreCase("-permtests")) {
i++;
doPermutationTest = true;
permutationCount = getIntegerArg(args,i);
}
else if(args[i].equalsIgnoreCase("-customassoc")) {
i++;
if (!(i>=args.length) && !((args[i].charAt(0)) == '-')){
customAssocTestsFileName = args[i];
}else{
die(args[i-1] + " requires a filename");
}
}
else if(args[i].equalsIgnoreCase("-aggressiveTagging")) {
tagging = Tagger.AGGRESSIVE_TRIPLE;
}
else if (args[i].equalsIgnoreCase("-pairwiseTagging")){
tagging = Tagger.PAIRWISE_ONLY;
}
else if (args[i].equalsIgnoreCase("-printalltags")){
Options.setPrintAllTags(true);
}
else if(args[i].equalsIgnoreCase("-maxNumTags")){
i++;
maxNumTags = getIntegerArg(args,i);
}
else if(args[i].equalsIgnoreCase("-tagrSqCutoff")) {
i++;
tagRSquaredCutOff = getDoubleArg(args,i,0,1);
}
else if (args[i].equalsIgnoreCase("-dontaddtags")){
findTags = false;
}
else if(args[i].equalsIgnoreCase("-tagLODCutoff")) {
i++;
Options.setTaggerLODCutoff(getDoubleArg(args,i,0,100000));
}
else if(args[i].equalsIgnoreCase("-includeTags")) {
i++;
if(i>=args.length || args[i].charAt(0) == '-') {
die(args[i-1] + " requires a list of marker names.");
}
StringTokenizer str = new StringTokenizer(args[i],",");
forceIncludeTags = new Vector();
while(str.hasMoreTokens()) {
forceIncludeTags.add(str.nextToken());
}
}
else if (args[i].equalsIgnoreCase("-includeTagsFile")) {
i++;
if(!(i>=args.length) && !(args[i].charAt(0) == '-')) {
forceIncludeFileName =args[i];
}else {
die(args[i-1] + " requires a filename");
}
}
else if(args[i].equalsIgnoreCase("-excludeTags")) {
i++;
if(i>=args.length || args[i].charAt(0) == '-') {
die("-excludeTags requires a list of marker names.");
}
StringTokenizer str = new StringTokenizer(args[i],",");
forceExcludeTags = new Vector();
while(str.hasMoreTokens()) {
forceExcludeTags.add(str.nextToken());
}
}
else if (args[i].equalsIgnoreCase("-excludeTagsFile")) {
i++;
if(!(i>=args.length) && !(args[i].charAt(0) == '-')) {
forceExcludeFileName =args[i];
}else {
die(args[i-1] + " requires a filename");
}
}
else if(args[i].equalsIgnoreCase("-chromosome") || args[i].equalsIgnoreCase("-chr")) {
i++;
if(!(i>=args.length) && !(args[i].charAt(0) == '-')) {
chromosomeArg =args[i];
}else {
die(args[i-1] + " requires a chromosome name");
}
}
else if(args[i].equalsIgnoreCase("-q") || args[i].equalsIgnoreCase("-quiet")) {
quietMode = true;
}
else {
die("invalid parameter specified: " + args[i]);
}
}
int countOptions = 0;
if(pedFileName != null) {
countOptions++;
}
if(hapsFileName != null) {
countOptions++;
}
if(hapmapFileName != null) {
countOptions++;
}
if(batchFileName != null) {
countOptions++;
}
if(countOptions > 1) {
die("Only one genotype input file may be specified on the command line.");
}
else if(countOptions == 0 && nogui) {
die("You must specify a genotype input file.");
}
//mess with vars, set defaults, etc
if(skipCheck && !quietMode) {
argHandlerMessages.add("Skipping genotype file check");
}
if(maxDistance == -1){
maxDistance = MAXDIST_DEFAULT;
}else{
if (!quietMode) argHandlerMessages.add("Max LD comparison distance = " +maxDistance);
}
Options.setMaxDistance(maxDistance);
if(hapThresh != -1) {
Options.setHaplotypeDisplayThreshold(hapThresh);
if (!quietMode) argHandlerMessages.add("Haplotype display threshold = " + hapThresh);
}
if(minimumMAF != -1) {
CheckData.mafCut = minimumMAF;
if (!quietMode) argHandlerMessages.add("Minimum MAF = " + minimumMAF);
}
if(minimumGenoPercent != -1) {
CheckData.failedGenoCut = (int)(minimumGenoPercent*100);
if (!quietMode) argHandlerMessages.add("Minimum SNP genotype % = " + minimumGenoPercent);
}
if(hwCutoff != -1) {
CheckData.hwCut = hwCutoff;
if (!quietMode) argHandlerMessages.add("Hardy Weinberg equilibrium p-value cutoff = " + hwCutoff);
}
if(maxMendel != -1) {
CheckData.numMendErrCut = maxMendel;
if (!quietMode) argHandlerMessages.add("Maximum number of Mendel errors = "+maxMendel);
}
if(spacingThresh != -1) {
Options.setSpacingThreshold(spacingThresh);
if (!quietMode) argHandlerMessages.add("LD display spacing value = "+spacingThresh);
}
if(missingCutoff != -1) {
Options.setMissingThreshold(missingCutoff);
if (!quietMode) argHandlerMessages.add("Maximum amount of missing data allowed per individual = "+missingCutoff);
}
if(cutHighCI != -1) {
FindBlocks.cutHighCI = cutHighCI;
}
if(cutLowCI != -1) {
FindBlocks.cutLowCI = cutLowCI;
}
if(mafThresh != -1) {
FindBlocks.mafThresh = mafThresh;
}
if(recHighCI != -1) {
FindBlocks.recHighCI = recHighCI;
}
if(informFrac != -1) {
FindBlocks.informFrac = informFrac;
}
if(fourGameteCutoff != -1) {
FindBlocks.fourGameteCutoff = fourGameteCutoff;
}
if(spineDP != -1) {
FindBlocks.spineDP = spineDP;
}
if(assocTDT) {
Options.setAssocTest(ASSOC_TRIO);
}else if(assocCC) {
Options.setAssocTest(ASSOC_CC);
}
if (Options.getAssocTest() != ASSOC_NONE && infoFileName == null && hapmapFileName == null) {
die("A marker info file must be specified when performing association tests.");
}
if(doPermutationTest) {
if(!assocCC && !assocTDT) {
die("An association test type must be specified for permutation tests to be performed.");
}
}
if(customAssocTestsFileName != null) {
if(!assocCC && !assocTDT) {
die("An association test type must be specified when using a custom association test file.");
}
if(infoFileName == null) {
die("A marker info file must be specified when using a custom association test file.");
}
}
if(tagging != Tagger.NONE) {
if(infoFileName == null && hapmapFileName == null && batchFileName == null) {
die("A marker info file must be specified when tagging.");
}
if(forceExcludeTags == null) {
forceExcludeTags = new Vector();
} else if (forceExcludeFileName != null) {
die("-excludeTags and -excludeTagsFile cannot both be used");
}
if(forceExcludeFileName != null) {
File excludeFile = new File(forceExcludeFileName);
forceExcludeTags = new Vector();
try {
BufferedReader br = new BufferedReader(new FileReader(excludeFile));
String line;
while((line = br.readLine()) != null) {
if(line.length() > 0 && line.charAt(0) != '#'){
forceExcludeTags.add(line);
}
}
}catch(IOException ioe) {
die("An error occured while reading the file specified by -excludeTagsFile.");
}
}
if(forceIncludeTags == null ) {
forceIncludeTags = new Vector();
} else if (forceIncludeFileName != null) {
die("-includeTags and -includeTagsFile cannot both be used");
}
if(forceIncludeFileName != null) {
File includeFile = new File(forceIncludeFileName);
forceIncludeTags = new Vector();
try {
BufferedReader br = new BufferedReader(new FileReader(includeFile));
String line;
while((line = br.readLine()) != null) {
if(line.length() > 0 && line.charAt(0) != '#'){
forceIncludeTags.add(line);
}
}
}catch(IOException ioe) {
die("An error occured while reading the file specified by -includeTagsFile.");
}
}
//check that there isn't any overlap between include/exclude lists
Vector tempInclude = (Vector) forceIncludeTags.clone();
tempInclude.retainAll(forceExcludeTags);
if(tempInclude.size() > 0) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i < tempInclude.size(); i++) {
String s = (String) tempInclude.elementAt(i);
sb.append(s).append(",");
}
die("The following markers appear in both the include and exclude lists: " + sb.toString());
}
if(tagRSquaredCutOff != -1) {
Options.setTaggerRsqCutoff(tagRSquaredCutOff);
}
} else if(forceExcludeTags != null || forceIncludeTags != null || tagRSquaredCutOff != -1) {
die("-tagrSqCutoff, -excludeTags, -excludeTagsFile, -includeTags and -includeTagsFile cannot be used without a tagging option");
}
if(chromosomeArg != null && hapmapFileName != null) {
argHandlerMessages.add("-chromosome flag ignored when loading hapmap file");
chromosomeArg = null;
}
if(chromosomeArg != null) {
Chromosome.setDataChrom("chr" + chromosomeArg);
}
}
|
diff --git a/CMPUT301Project/src/com/cmput301w13t09/cmput301project/activities/QueryRecipeOfflineView.java b/CMPUT301Project/src/com/cmput301w13t09/cmput301project/activities/QueryRecipeOfflineView.java
index fa2b4bb..1ba3815 100644
--- a/CMPUT301Project/src/com/cmput301w13t09/cmput301project/activities/QueryRecipeOfflineView.java
+++ b/CMPUT301Project/src/com/cmput301w13t09/cmput301project/activities/QueryRecipeOfflineView.java
@@ -1,110 +1,110 @@
package com.cmput301w13t09.cmput301project.activities;
import com.cmput301w13t09.cmput301project.R;
import com.cmput301w13t09.cmput301project.controllers.IngredientController;
import com.cmput301w13t09.cmput301project.controllers.RecipeController;
import com.cmput301w13t09.cmput301project.models.RecipeListModel;
import com.cmput301w13t09.cmput301project.models.RecipeModel;
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListAdapter;
import android.widget.ListView;
import android.widget.AdapterView.OnItemClickListener;
public class QueryRecipeOfflineView extends Activity {
private ListAdapter recipeListAdapter;
private ListView recipeListView;
private IngredientController ingredController;
private int dialogNumber;
private RecipeListModel QuertRecipeList;
private RecipeController recipeController;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_query_recipe_offline_view);
recipeController = new RecipeController(this);
ingredController = new IngredientController(this);
QuertRecipeList = recipeController.getQueryRecipeList(ingredController);
recipeListView = (ListView) findViewById(R.id.queryRecipeOfflinelistView);
recipeListAdapter = new ArrayAdapter<RecipeModel>(this,
android.R.layout.simple_list_item_1, QuertRecipeList);
recipeListView.setAdapter(recipeListAdapter);
recipeListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
dialogNumber = position;
AlertDialog.Builder builder = new AlertDialog.Builder(
QueryRecipeOfflineView.this);
String title = QuertRecipeList.get(position).getRecipeName();
String message = QuertRecipeList.get(position).getRecipeDesc();
builder.setMessage(message);
builder.setTitle(title);
builder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();
}
});
builder.setNeutralButton("View",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
try {
Intent viewRecipe = new Intent(
- "activities.RecipeOnlineView");
+ "activities.ViewRecipe");
viewRecipe.putExtra("Recipe",
QuertRecipeList.get(dialogNumber));
startActivity(viewRecipe);
} catch (Throwable throwable) {
throwable.printStackTrace();
}
dialog.dismiss();
}
});
builder.setPositiveButton("Delete",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
recipeController.remove(recipeController
.findRecipe(QuertRecipeList.get(
dialogNumber).getRecipeName()));
recipeController.saveToFile();
dialog.dismiss();
updateList();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
});
}
protected void updateList() {
recipeController.loadFromFile();
QuertRecipeList = recipeController.getQueryRecipeList(ingredController);
recipeListAdapter = new ArrayAdapter<RecipeModel>(this,
android.R.layout.simple_list_item_1, QuertRecipeList);
recipeListView.setAdapter(recipeListAdapter);
}
}
| true | true | protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_query_recipe_offline_view);
recipeController = new RecipeController(this);
ingredController = new IngredientController(this);
QuertRecipeList = recipeController.getQueryRecipeList(ingredController);
recipeListView = (ListView) findViewById(R.id.queryRecipeOfflinelistView);
recipeListAdapter = new ArrayAdapter<RecipeModel>(this,
android.R.layout.simple_list_item_1, QuertRecipeList);
recipeListView.setAdapter(recipeListAdapter);
recipeListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
dialogNumber = position;
AlertDialog.Builder builder = new AlertDialog.Builder(
QueryRecipeOfflineView.this);
String title = QuertRecipeList.get(position).getRecipeName();
String message = QuertRecipeList.get(position).getRecipeDesc();
builder.setMessage(message);
builder.setTitle(title);
builder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();
}
});
builder.setNeutralButton("View",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
try {
Intent viewRecipe = new Intent(
"activities.RecipeOnlineView");
viewRecipe.putExtra("Recipe",
QuertRecipeList.get(dialogNumber));
startActivity(viewRecipe);
} catch (Throwable throwable) {
throwable.printStackTrace();
}
dialog.dismiss();
}
});
builder.setPositiveButton("Delete",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
recipeController.remove(recipeController
.findRecipe(QuertRecipeList.get(
dialogNumber).getRecipeName()));
recipeController.saveToFile();
dialog.dismiss();
updateList();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
});
}
| protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_query_recipe_offline_view);
recipeController = new RecipeController(this);
ingredController = new IngredientController(this);
QuertRecipeList = recipeController.getQueryRecipeList(ingredController);
recipeListView = (ListView) findViewById(R.id.queryRecipeOfflinelistView);
recipeListAdapter = new ArrayAdapter<RecipeModel>(this,
android.R.layout.simple_list_item_1, QuertRecipeList);
recipeListView.setAdapter(recipeListAdapter);
recipeListView.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
dialogNumber = position;
AlertDialog.Builder builder = new AlertDialog.Builder(
QueryRecipeOfflineView.this);
String title = QuertRecipeList.get(position).getRecipeName();
String message = QuertRecipeList.get(position).getRecipeDesc();
builder.setMessage(message);
builder.setTitle(title);
builder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
dialog.dismiss();
}
});
builder.setNeutralButton("View",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
try {
Intent viewRecipe = new Intent(
"activities.ViewRecipe");
viewRecipe.putExtra("Recipe",
QuertRecipeList.get(dialogNumber));
startActivity(viewRecipe);
} catch (Throwable throwable) {
throwable.printStackTrace();
}
dialog.dismiss();
}
});
builder.setPositiveButton("Delete",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int which) {
recipeController.remove(recipeController
.findRecipe(QuertRecipeList.get(
dialogNumber).getRecipeName()));
recipeController.saveToFile();
dialog.dismiss();
updateList();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
});
}
|
diff --git a/src/com/android/shakemusic/Guitar.java b/src/com/android/shakemusic/Guitar.java
index d49210f..f1c6d1b 100644
--- a/src/com/android/shakemusic/Guitar.java
+++ b/src/com/android/shakemusic/Guitar.java
@@ -1,39 +1,46 @@
package com.android.shakemusic;
public class Guitar implements Instrument{
private int nHarm;
private int bpm;
private double duration;
private double pluck_location;
Guitar(int nHarm, int bpm, double duration, double pluck_location) {
this.nHarm = nHarm;
this.bpm = bpm;
this.duration = duration;
this.pluck_location = pluck_location;
}
- public short[] Note(int freq) {
+ public byte[] Note(int freq) {
int Nt, jh, jhsqr;
double T, An, dfn;
T = duration / bpm;
Nt = (int) (fs * T);
- short sj[] = new short[Nt];
+ double sj[] = new double[Nt];
+ byte generatedSnd[];
// Make Note
int i, j;
for (i = 0; i < Nt; i++) {
sj[i] = 0;
for (j = 0; j < nHarm; j++) {
jh = j + 1;
jhsqr = jh * jh;
An = 2 / ((pisqr) * jhsqr * pluck_location * (1 - pluck_location))
* Math.sin(jh * pi * pluck_location);
dfn = Math.sqrt(1 + jhsqr * inharmonity * inharmonity);
- sj[i] = (short) (An * Math.exp(-gam * jh * i / fs) * Math.sin(2
+ sj[i] = (An * Math.exp(-gam * jh * i / fs) * Math.sin(2
* pi * i * freq * dfn * jh / fs));
}
}
- return sj;
+ int idx = 0;
+ for (double dVal : sj) {
+ short val = (short) (dVal * 32767);
+ generatedSnd[idx++] = (byte) (val & 0x00ff);
+ generatedSnd[idx++] = (byte) ((val & 0xff00) >>> 8);
+ }
+ return generatedSnd;
}
}
| false | true | public short[] Note(int freq) {
int Nt, jh, jhsqr;
double T, An, dfn;
T = duration / bpm;
Nt = (int) (fs * T);
short sj[] = new short[Nt];
// Make Note
int i, j;
for (i = 0; i < Nt; i++) {
sj[i] = 0;
for (j = 0; j < nHarm; j++) {
jh = j + 1;
jhsqr = jh * jh;
An = 2 / ((pisqr) * jhsqr * pluck_location * (1 - pluck_location))
* Math.sin(jh * pi * pluck_location);
dfn = Math.sqrt(1 + jhsqr * inharmonity * inharmonity);
sj[i] = (short) (An * Math.exp(-gam * jh * i / fs) * Math.sin(2
* pi * i * freq * dfn * jh / fs));
}
}
return sj;
}
| public byte[] Note(int freq) {
int Nt, jh, jhsqr;
double T, An, dfn;
T = duration / bpm;
Nt = (int) (fs * T);
double sj[] = new double[Nt];
byte generatedSnd[];
// Make Note
int i, j;
for (i = 0; i < Nt; i++) {
sj[i] = 0;
for (j = 0; j < nHarm; j++) {
jh = j + 1;
jhsqr = jh * jh;
An = 2 / ((pisqr) * jhsqr * pluck_location * (1 - pluck_location))
* Math.sin(jh * pi * pluck_location);
dfn = Math.sqrt(1 + jhsqr * inharmonity * inharmonity);
sj[i] = (An * Math.exp(-gam * jh * i / fs) * Math.sin(2
* pi * i * freq * dfn * jh / fs));
}
}
int idx = 0;
for (double dVal : sj) {
short val = (short) (dVal * 32767);
generatedSnd[idx++] = (byte) (val & 0x00ff);
generatedSnd[idx++] = (byte) ((val & 0xff00) >>> 8);
}
return generatedSnd;
}
|
diff --git a/IndaProject/src/components/PlayerMovementComponent.java b/IndaProject/src/components/PlayerMovementComponent.java
index 776a926..4e62da6 100644
--- a/IndaProject/src/components/PlayerMovementComponent.java
+++ b/IndaProject/src/components/PlayerMovementComponent.java
@@ -1,75 +1,73 @@
package components;
import game.Controller;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Input;
import org.newdawn.slick.geom.Vector2f;
import org.newdawn.slick.state.StateBasedGame;
public class PlayerMovementComponent extends Component {
private float direction;
private float speed;
public PlayerMovementComponent(String id) {
this.id = id;
}
public float getSpeed() {
return speed;
}
public float getDirection() {
return direction;
}
@Override
public void update(GameContainer gc, StateBasedGame sb, int delta) {
float rotation = owner.getRotation();
float scale = owner.getScale();
Vector2f position = owner.getPosition();
Input input = gc.getInput();
if (Controller.isP1ButtonPressed("Left", input)
|| Controller.isP1ButtonPressed("LeftAlt", input)) {
- rotation += -0.2f * delta;
+ position.x += -0.2f * delta;
}
if (Controller.isP1ButtonPressed("Right", input)
|| Controller.isP1ButtonPressed("RightAlt", input)) {
rotation += 0.2f * delta;
}
- if (Controller.isP1ButtonPressed("Up", input)
- || Controller.isP1ButtonPressed("UpAlt", input))
+ if (Controller.isP1ButtonPressed("Up", input) || Controller.isP1ButtonPressed("UpAlt", input))
{
float hip = 0.4f * delta;
position.x += hip
* java.lang.Math.sin(java.lang.Math.toRadians(rotation));
position.y -= hip
* java.lang.Math.cos(java.lang.Math.toRadians(rotation));
}
- if (Controller.isP1ButtonPressed("Down", input)
- || Controller.isP1ButtonPressed("DownAlt", input))
+ if (Controller.isP1ButtonPressed("Down", input) || Controller.isP1ButtonPressed("DownAlt", input))
{
float hip = -0.4f * delta;
position.x += hip
* java.lang.Math.sin(java.lang.Math.toRadians(rotation));
position.y -= hip
* java.lang.Math.cos(java.lang.Math.toRadians(rotation));
}
owner.setPosition(position);
owner.setRotation(rotation);
owner.setScale(scale);
}
}
| false | true | public void update(GameContainer gc, StateBasedGame sb, int delta) {
float rotation = owner.getRotation();
float scale = owner.getScale();
Vector2f position = owner.getPosition();
Input input = gc.getInput();
if (Controller.isP1ButtonPressed("Left", input)
|| Controller.isP1ButtonPressed("LeftAlt", input)) {
rotation += -0.2f * delta;
}
if (Controller.isP1ButtonPressed("Right", input)
|| Controller.isP1ButtonPressed("RightAlt", input)) {
rotation += 0.2f * delta;
}
if (Controller.isP1ButtonPressed("Up", input)
|| Controller.isP1ButtonPressed("UpAlt", input))
{
float hip = 0.4f * delta;
position.x += hip
* java.lang.Math.sin(java.lang.Math.toRadians(rotation));
position.y -= hip
* java.lang.Math.cos(java.lang.Math.toRadians(rotation));
}
if (Controller.isP1ButtonPressed("Down", input)
|| Controller.isP1ButtonPressed("DownAlt", input))
{
float hip = -0.4f * delta;
position.x += hip
* java.lang.Math.sin(java.lang.Math.toRadians(rotation));
position.y -= hip
* java.lang.Math.cos(java.lang.Math.toRadians(rotation));
}
owner.setPosition(position);
owner.setRotation(rotation);
owner.setScale(scale);
}
| public void update(GameContainer gc, StateBasedGame sb, int delta) {
float rotation = owner.getRotation();
float scale = owner.getScale();
Vector2f position = owner.getPosition();
Input input = gc.getInput();
if (Controller.isP1ButtonPressed("Left", input)
|| Controller.isP1ButtonPressed("LeftAlt", input)) {
position.x += -0.2f * delta;
}
if (Controller.isP1ButtonPressed("Right", input)
|| Controller.isP1ButtonPressed("RightAlt", input)) {
rotation += 0.2f * delta;
}
if (Controller.isP1ButtonPressed("Up", input) || Controller.isP1ButtonPressed("UpAlt", input))
{
float hip = 0.4f * delta;
position.x += hip
* java.lang.Math.sin(java.lang.Math.toRadians(rotation));
position.y -= hip
* java.lang.Math.cos(java.lang.Math.toRadians(rotation));
}
if (Controller.isP1ButtonPressed("Down", input) || Controller.isP1ButtonPressed("DownAlt", input))
{
float hip = -0.4f * delta;
position.x += hip
* java.lang.Math.sin(java.lang.Math.toRadians(rotation));
position.y -= hip
* java.lang.Math.cos(java.lang.Math.toRadians(rotation));
}
owner.setPosition(position);
owner.setRotation(rotation);
owner.setScale(scale);
}
|
diff --git a/src/main/java/org/dynmap/servlet/SendMessageServlet.java b/src/main/java/org/dynmap/servlet/SendMessageServlet.java
index b5a7a04c..ade31d71 100644
--- a/src/main/java/org/dynmap/servlet/SendMessageServlet.java
+++ b/src/main/java/org/dynmap/servlet/SendMessageServlet.java
@@ -1,197 +1,200 @@
package org.dynmap.servlet;
import static org.dynmap.JSONUtils.s;
import org.dynmap.DynmapCore;
import org.dynmap.Event;
import org.dynmap.Log;
import org.dynmap.web.HttpField;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.InputStreamReader;
import java.nio.charset.Charset;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Logger;
@SuppressWarnings("serial")
public class SendMessageServlet extends HttpServlet {
protected static final Logger log = Logger.getLogger("Minecraft");
private static final JSONParser parser = new JSONParser();
public Event<Message> onMessageReceived = new Event<Message>();
private Charset cs_utf8 = Charset.forName("UTF-8");
public int maximumMessageInterval = 1000;
public boolean hideip = false;
public boolean trustclientname = false;
public String spamMessage = "\"You may only chat once every %interval% seconds.\"";
private HashMap<String, WebUser> disallowedUsers = new HashMap<String, WebUser>();
private LinkedList<WebUser> disallowedUserQueue = new LinkedList<WebUser>();
private Object disallowedUsersLock = new Object();
private HashMap<String,String> useralias = new HashMap<String,String>();
private int aliasindex = 1;
public boolean use_player_login_ip = false;
public boolean require_player_login_ip = false;
public boolean check_user_ban = false;
public boolean require_login = false;
public boolean chat_perms = false;
public int lengthlimit = 256;
public DynmapCore core;
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
byte[] bytes;
String error = "none";
HttpSession sess = request.getSession(true);
String userID = (String) sess.getAttribute(LoginServlet.USERID_ATTRIB);
if(userID == null) userID = LoginServlet.USERID_GUEST;
boolean chat_requires_login = core.getLoginRequired() || require_login;
if(chat_requires_login && userID.equals(LoginServlet.USERID_GUEST)) {
error = "login-required";
}
else if(chat_requires_login && (!userID.equals(LoginServlet.USERID_GUEST)) && chat_perms &&
(!core.checkPermission(userID, "webchat"))) {
Log.info("Rejected web chat by " + userID + ": not permitted");
error = "not-permitted";
}
else {
boolean ok = true;
InputStreamReader reader = new InputStreamReader(request.getInputStream(), cs_utf8);
JSONObject o = null;
try {
o = (JSONObject)parser.parse(reader);
} catch (ParseException e) {
error = "bad-format";
ok = false;
}
final Message message = new Message();
- if(userID.equals(LoginServlet.USERID_GUEST)) {
+ if (userID.equals(LoginServlet.USERID_GUEST)) {
message.name = "";
- if(trustclientname) {
+ if (trustclientname) {
message.name = String.valueOf(o.get("name"));
}
boolean isip = true;
- if((message.name == null) || message.name.equals("")) {
- /* If proxied client address, get original */
- if(request.getHeader("X-Forwarded-For") != null)
- message.name = request.getHeader("X-Forwarded-For");
+ if ((message.name == null) || message.name.equals("")) {
/* If from loopback, we're probably getting from proxy - need to trust client */
- else if(request.getRemoteAddr() == "127.0.0.1")
- message.name = String.valueOf(o.get("name"));
+ if (request.getRemoteAddr().equals("127.0.0.1")) {
+ /* If proxied client address, get original IP */
+ if (request.getHeader("X-Forwarded-For") != null) {
+ message.name = request.getHeader("X-Forwarded-For");
+ } else {
+ message.name = String.valueOf(o.get("name"));
+ }
+ }
else
message.name = request.getRemoteAddr();
}
if (use_player_login_ip) {
List<String> ids = core.getIDsForIP(message.name);
if (ids != null) {
String id = ids.get(0);
if (check_user_ban) {
if (core.getServer().isPlayerBanned(id)) {
Log.info("Ignore message from '" + message.name + "' - banned player (" + id + ")");
error = "not-allowed";
ok = false;
}
}
if (chat_perms && !core.getServer().checkPlayerPermission(id, "webchat")) {
Log.info("Rejected web chat from '" + message.name + "': not permitted (" + id + ")");
error = "not-allowed";
ok = false;
}
message.name = id;
isip = false;
} else if (require_player_login_ip) {
Log.info("Ignore message from '" + message.name + "' - no matching player login recorded");
error = "not-allowed";
ok = false;
}
}
if (hideip && isip) { /* If hiding IP, find or assign alias */
synchronized (disallowedUsersLock) {
String n = useralias.get(message.name);
if (n == null) { /* Make ID */
n = String.format("web-%03d", aliasindex);
aliasindex++;
useralias.put(message.name, n);
}
message.name = n;
}
}
}
else {
message.name = userID;
}
message.message = String.valueOf(o.get("message"));
if((lengthlimit > 0) && (message.message.length() > lengthlimit)) {
message.message = message.message.substring(0, lengthlimit);
}
final long now = System.currentTimeMillis();
synchronized (disallowedUsersLock) {
// Allow users that user that are now allowed to send messages.
while (!disallowedUserQueue.isEmpty()) {
WebUser wu = disallowedUserQueue.getFirst();
if (now >= wu.nextMessageTime) {
disallowedUserQueue.remove();
disallowedUsers.remove(wu.name);
} else {
break;
}
}
WebUser user = disallowedUsers.get(message.name);
if (user == null) {
user = new WebUser() {
{
name = message.name;
nextMessageTime = now + maximumMessageInterval;
}
};
disallowedUsers.put(user.name, user);
disallowedUserQueue.add(user);
} else {
error = "not-allowed";
ok = false;
}
}
if(ok)
onMessageReceived.trigger(message);
}
JSONObject json = new JSONObject();
s(json, "error", error);
bytes = json.toJSONString().getBytes(cs_utf8);
String dateStr = new Date().toString();
response.addHeader(HttpField.Date, dateStr);
response.addHeader(HttpField.ContentType, "text/plain; charset=utf-8");
response.addHeader(HttpField.Expires, "Thu, 01 Dec 1994 16:00:00 GMT");
response.addHeader(HttpField.LastModified, dateStr);
response.addHeader(HttpField.ContentLength, Integer.toString(bytes.length));
response.getOutputStream().write(bytes);
}
public static class Message {
public String name;
public String message;
}
public static class WebUser {
public long nextMessageTime;
public String name;
}
}
| false | true | protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
byte[] bytes;
String error = "none";
HttpSession sess = request.getSession(true);
String userID = (String) sess.getAttribute(LoginServlet.USERID_ATTRIB);
if(userID == null) userID = LoginServlet.USERID_GUEST;
boolean chat_requires_login = core.getLoginRequired() || require_login;
if(chat_requires_login && userID.equals(LoginServlet.USERID_GUEST)) {
error = "login-required";
}
else if(chat_requires_login && (!userID.equals(LoginServlet.USERID_GUEST)) && chat_perms &&
(!core.checkPermission(userID, "webchat"))) {
Log.info("Rejected web chat by " + userID + ": not permitted");
error = "not-permitted";
}
else {
boolean ok = true;
InputStreamReader reader = new InputStreamReader(request.getInputStream(), cs_utf8);
JSONObject o = null;
try {
o = (JSONObject)parser.parse(reader);
} catch (ParseException e) {
error = "bad-format";
ok = false;
}
final Message message = new Message();
if(userID.equals(LoginServlet.USERID_GUEST)) {
message.name = "";
if(trustclientname) {
message.name = String.valueOf(o.get("name"));
}
boolean isip = true;
if((message.name == null) || message.name.equals("")) {
/* If proxied client address, get original */
if(request.getHeader("X-Forwarded-For") != null)
message.name = request.getHeader("X-Forwarded-For");
/* If from loopback, we're probably getting from proxy - need to trust client */
else if(request.getRemoteAddr() == "127.0.0.1")
message.name = String.valueOf(o.get("name"));
else
message.name = request.getRemoteAddr();
}
if (use_player_login_ip) {
List<String> ids = core.getIDsForIP(message.name);
if (ids != null) {
String id = ids.get(0);
if (check_user_ban) {
if (core.getServer().isPlayerBanned(id)) {
Log.info("Ignore message from '" + message.name + "' - banned player (" + id + ")");
error = "not-allowed";
ok = false;
}
}
if (chat_perms && !core.getServer().checkPlayerPermission(id, "webchat")) {
Log.info("Rejected web chat from '" + message.name + "': not permitted (" + id + ")");
error = "not-allowed";
ok = false;
}
message.name = id;
isip = false;
} else if (require_player_login_ip) {
Log.info("Ignore message from '" + message.name + "' - no matching player login recorded");
error = "not-allowed";
ok = false;
}
}
if (hideip && isip) { /* If hiding IP, find or assign alias */
synchronized (disallowedUsersLock) {
String n = useralias.get(message.name);
if (n == null) { /* Make ID */
n = String.format("web-%03d", aliasindex);
aliasindex++;
useralias.put(message.name, n);
}
message.name = n;
}
}
}
else {
message.name = userID;
}
message.message = String.valueOf(o.get("message"));
if((lengthlimit > 0) && (message.message.length() > lengthlimit)) {
message.message = message.message.substring(0, lengthlimit);
}
final long now = System.currentTimeMillis();
synchronized (disallowedUsersLock) {
// Allow users that user that are now allowed to send messages.
while (!disallowedUserQueue.isEmpty()) {
WebUser wu = disallowedUserQueue.getFirst();
if (now >= wu.nextMessageTime) {
disallowedUserQueue.remove();
disallowedUsers.remove(wu.name);
} else {
break;
}
}
WebUser user = disallowedUsers.get(message.name);
if (user == null) {
user = new WebUser() {
{
name = message.name;
nextMessageTime = now + maximumMessageInterval;
}
};
disallowedUsers.put(user.name, user);
disallowedUserQueue.add(user);
} else {
error = "not-allowed";
ok = false;
}
}
if(ok)
onMessageReceived.trigger(message);
}
JSONObject json = new JSONObject();
s(json, "error", error);
bytes = json.toJSONString().getBytes(cs_utf8);
String dateStr = new Date().toString();
response.addHeader(HttpField.Date, dateStr);
response.addHeader(HttpField.ContentType, "text/plain; charset=utf-8");
response.addHeader(HttpField.Expires, "Thu, 01 Dec 1994 16:00:00 GMT");
response.addHeader(HttpField.LastModified, dateStr);
response.addHeader(HttpField.ContentLength, Integer.toString(bytes.length));
response.getOutputStream().write(bytes);
}
| protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
byte[] bytes;
String error = "none";
HttpSession sess = request.getSession(true);
String userID = (String) sess.getAttribute(LoginServlet.USERID_ATTRIB);
if(userID == null) userID = LoginServlet.USERID_GUEST;
boolean chat_requires_login = core.getLoginRequired() || require_login;
if(chat_requires_login && userID.equals(LoginServlet.USERID_GUEST)) {
error = "login-required";
}
else if(chat_requires_login && (!userID.equals(LoginServlet.USERID_GUEST)) && chat_perms &&
(!core.checkPermission(userID, "webchat"))) {
Log.info("Rejected web chat by " + userID + ": not permitted");
error = "not-permitted";
}
else {
boolean ok = true;
InputStreamReader reader = new InputStreamReader(request.getInputStream(), cs_utf8);
JSONObject o = null;
try {
o = (JSONObject)parser.parse(reader);
} catch (ParseException e) {
error = "bad-format";
ok = false;
}
final Message message = new Message();
if (userID.equals(LoginServlet.USERID_GUEST)) {
message.name = "";
if (trustclientname) {
message.name = String.valueOf(o.get("name"));
}
boolean isip = true;
if ((message.name == null) || message.name.equals("")) {
/* If from loopback, we're probably getting from proxy - need to trust client */
if (request.getRemoteAddr().equals("127.0.0.1")) {
/* If proxied client address, get original IP */
if (request.getHeader("X-Forwarded-For") != null) {
message.name = request.getHeader("X-Forwarded-For");
} else {
message.name = String.valueOf(o.get("name"));
}
}
else
message.name = request.getRemoteAddr();
}
if (use_player_login_ip) {
List<String> ids = core.getIDsForIP(message.name);
if (ids != null) {
String id = ids.get(0);
if (check_user_ban) {
if (core.getServer().isPlayerBanned(id)) {
Log.info("Ignore message from '" + message.name + "' - banned player (" + id + ")");
error = "not-allowed";
ok = false;
}
}
if (chat_perms && !core.getServer().checkPlayerPermission(id, "webchat")) {
Log.info("Rejected web chat from '" + message.name + "': not permitted (" + id + ")");
error = "not-allowed";
ok = false;
}
message.name = id;
isip = false;
} else if (require_player_login_ip) {
Log.info("Ignore message from '" + message.name + "' - no matching player login recorded");
error = "not-allowed";
ok = false;
}
}
if (hideip && isip) { /* If hiding IP, find or assign alias */
synchronized (disallowedUsersLock) {
String n = useralias.get(message.name);
if (n == null) { /* Make ID */
n = String.format("web-%03d", aliasindex);
aliasindex++;
useralias.put(message.name, n);
}
message.name = n;
}
}
}
else {
message.name = userID;
}
message.message = String.valueOf(o.get("message"));
if((lengthlimit > 0) && (message.message.length() > lengthlimit)) {
message.message = message.message.substring(0, lengthlimit);
}
final long now = System.currentTimeMillis();
synchronized (disallowedUsersLock) {
// Allow users that user that are now allowed to send messages.
while (!disallowedUserQueue.isEmpty()) {
WebUser wu = disallowedUserQueue.getFirst();
if (now >= wu.nextMessageTime) {
disallowedUserQueue.remove();
disallowedUsers.remove(wu.name);
} else {
break;
}
}
WebUser user = disallowedUsers.get(message.name);
if (user == null) {
user = new WebUser() {
{
name = message.name;
nextMessageTime = now + maximumMessageInterval;
}
};
disallowedUsers.put(user.name, user);
disallowedUserQueue.add(user);
} else {
error = "not-allowed";
ok = false;
}
}
if(ok)
onMessageReceived.trigger(message);
}
JSONObject json = new JSONObject();
s(json, "error", error);
bytes = json.toJSONString().getBytes(cs_utf8);
String dateStr = new Date().toString();
response.addHeader(HttpField.Date, dateStr);
response.addHeader(HttpField.ContentType, "text/plain; charset=utf-8");
response.addHeader(HttpField.Expires, "Thu, 01 Dec 1994 16:00:00 GMT");
response.addHeader(HttpField.LastModified, dateStr);
response.addHeader(HttpField.ContentLength, Integer.toString(bytes.length));
response.getOutputStream().write(bytes);
}
|
diff --git a/bundles/org.eclipse.equinox.http.jetty6/src/org/eclipse/equinox/http/jetty/internal/HttpServerManager.java b/bundles/org.eclipse.equinox.http.jetty6/src/org/eclipse/equinox/http/jetty/internal/HttpServerManager.java
index 0e43af06..a1fa6aed 100644
--- a/bundles/org.eclipse.equinox.http.jetty6/src/org/eclipse/equinox/http/jetty/internal/HttpServerManager.java
+++ b/bundles/org.eclipse.equinox.http.jetty6/src/org/eclipse/equinox/http/jetty/internal/HttpServerManager.java
@@ -1,340 +1,340 @@
/*******************************************************************************
* Copyright (c) 2007, 2008 IBM Corporation and others
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.equinox.http.jetty.internal;
import java.io.File;
import java.io.IOException;
import java.util.*;
import javax.servlet.*;
import org.eclipse.equinox.http.jetty.JettyConstants;
import org.eclipse.equinox.http.jetty.JettyCustomizer;
import org.eclipse.equinox.http.servlet.HttpServiceServlet;
import org.mortbay.jetty.Connector;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.bio.SocketConnector;
import org.mortbay.jetty.nio.SelectChannelConnector;
import org.mortbay.jetty.security.SslSocketConnector;
import org.mortbay.jetty.servlet.*;
import org.osgi.framework.Constants;
import org.osgi.service.cm.ConfigurationException;
import org.osgi.service.cm.ManagedServiceFactory;
public class HttpServerManager implements ManagedServiceFactory {
private static final String CONTEXT_TEMPDIR = "javax.servlet.context.tempdir"; //$NON-NLS-1$
private static final String DIR_PREFIX = "pid_"; //$NON-NLS-1$
private static final String INTERNAL_CONTEXT_CLASSLOADER = "org.eclipse.equinox.http.jetty.internal.ContextClassLoader"; //$NON-NLS-1$
private Map servers = new HashMap();
private File workDir;
public HttpServerManager(File workDir) {
this.workDir = workDir;
}
public synchronized void deleted(String pid) {
Server server = (Server) servers.remove(pid);
if (server != null) {
try {
server.stop();
} catch (Exception e) {
// TODO: consider logging this, but we should still continue cleaning up
e.printStackTrace();
}
File contextWorkDir = new File(workDir, DIR_PREFIX + pid.hashCode());
deleteDirectory(contextWorkDir);
}
}
public String getName() {
return this.getClass().getName();
}
public synchronized void updated(String pid, Dictionary dictionary) throws ConfigurationException {
deleted(pid);
Server server = new Server();
JettyCustomizer customizer = createJettyCustomizer(dictionary);
Connector httpConnector = createHttpConnector(dictionary);
if (null != customizer)
httpConnector = (Connector) customizer.customizeHttpConnector(httpConnector, dictionary);
if (httpConnector != null)
server.addConnector(httpConnector);
Connector httpsConnector = createHttpsConnector(dictionary);
if (null != customizer)
httpsConnector = (Connector) customizer.customizeHttpsConnector(httpsConnector, dictionary);
if (httpsConnector != null)
server.addConnector(httpsConnector);
ServletHolder holder = new ServletHolder(new InternalHttpServiceServlet());
holder.setInitOrder(0);
holder.setInitParameter(Constants.SERVICE_VENDOR, "Eclipse.org"); //$NON-NLS-1$
holder.setInitParameter(Constants.SERVICE_DESCRIPTION, "Equinox Jetty-based Http Service"); //$NON-NLS-1$
if (httpConnector != null)
holder.setInitParameter(JettyConstants.HTTP_PORT, new Integer(httpConnector.getLocalPort()).toString());
if (httpsConnector != null)
holder.setInitParameter(JettyConstants.HTTPS_PORT, new Integer(httpsConnector.getLocalPort()).toString());
String otherInfo = (String) dictionary.get(JettyConstants.OTHER_INFO);
if (otherInfo != null)
holder.setInitParameter(JettyConstants.OTHER_INFO, otherInfo);
Context httpContext = createHttpContext(dictionary);
if (null != customizer)
httpContext = (Context) customizer.customizeContext(httpContext, dictionary);
httpContext.addServlet(holder, "/*"); //$NON-NLS-1$
server.addHandler(httpContext);
try {
server.start();
} catch (Exception e) {
throw new ConfigurationException(pid, e.getMessage(), e);
}
servers.put(pid, server);
}
public synchronized void shutdown() throws Exception {
for (Iterator it = servers.values().iterator(); it.hasNext();) {
Server server = (Server) it.next();
server.stop();
}
servers.clear();
}
private Connector createHttpConnector(Dictionary dictionary) {
Boolean httpEnabled = (Boolean) dictionary.get(JettyConstants.HTTP_ENABLED);
if (httpEnabled != null && !httpEnabled.booleanValue())
return null;
Integer httpPort = (Integer) dictionary.get(JettyConstants.HTTP_PORT);
if (httpPort == null)
return null;
Boolean nioEnabled = (Boolean) dictionary.get(JettyConstants.HTTP_NIO);
if (nioEnabled == null)
nioEnabled = getDefaultNIOEnablement();
Connector connector;
if (nioEnabled.booleanValue())
connector = new SelectChannelConnector();
else
connector = new SocketConnector();
connector.setPort(httpPort.intValue());
String httpHost = (String) dictionary.get(JettyConstants.HTTP_HOST);
if (httpHost != null) {
connector.setHost(httpHost);
}
if (connector.getPort() == 0) {
try {
connector.open();
} catch (IOException e) {
// this would be unexpected since we're opening the next available port
e.printStackTrace();
}
}
return connector;
}
private Boolean getDefaultNIOEnablement() {
Properties systemProperties = System.getProperties();
String javaVendor = systemProperties.getProperty("java.vendor", ""); //$NON-NLS-1$ //$NON-NLS-2$
if (javaVendor.equals("IBM Corporation")) { //$NON-NLS-1$
String javaVersion = systemProperties.getProperty("java.version", ""); //$NON-NLS-1$ //$NON-NLS-2$
if (javaVersion.startsWith("1.4")) //$NON-NLS-1$
return Boolean.FALSE;
// Note: no problems currently logged with 1.5
if (javaVersion.equals("1.6.0")) { //$NON-NLS-1$
String jclVersion = systemProperties.getProperty("java.jcl.version", ""); //$NON-NLS-1$ //$NON-NLS-2$
if (jclVersion.startsWith("2007")) //$NON-NLS-1$
return Boolean.FALSE;
if (jclVersion.startsWith("2008") && !jclVersion.startsWith("200811") && !jclVersion.startsWith("200812")) //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
return Boolean.FALSE;
}
}
return Boolean.TRUE;
}
private Connector createHttpsConnector(Dictionary dictionary) {
Boolean httpsEnabled = (Boolean) dictionary.get(JettyConstants.HTTPS_ENABLED);
if (httpsEnabled == null || !httpsEnabled.booleanValue())
return null;
Integer httpsPort = (Integer) dictionary.get(JettyConstants.HTTPS_PORT);
if (httpsPort == null)
return null;
SslSocketConnector sslConnector = new SslSocketConnector();
sslConnector.setPort(httpsPort.intValue());
String httpsHost = (String) dictionary.get(JettyConstants.HTTPS_HOST);
if (httpsHost != null) {
sslConnector.setHost(httpsHost);
}
String keyStore = (String) dictionary.get(JettyConstants.SSL_KEYSTORE);
if (keyStore != null)
sslConnector.setKeystore(keyStore);
String password = (String) dictionary.get(JettyConstants.SSL_PASSWORD);
if (password != null)
sslConnector.setPassword(password);
String keyPassword = (String) dictionary.get(JettyConstants.SSL_KEYPASSWORD);
if (keyPassword != null)
sslConnector.setKeyPassword(keyPassword);
Object needClientAuth = dictionary.get(JettyConstants.SSL_NEEDCLIENTAUTH);
if (needClientAuth != null) {
if (needClientAuth instanceof String)
needClientAuth = Boolean.valueOf((String) needClientAuth);
sslConnector.setNeedClientAuth(((Boolean) needClientAuth).booleanValue());
}
- Object wantClientAuth = (Boolean) dictionary.get(JettyConstants.SSL_WANTCLIENTAUTH);
+ Object wantClientAuth = dictionary.get(JettyConstants.SSL_WANTCLIENTAUTH);
if (wantClientAuth != null) {
if (wantClientAuth instanceof String)
wantClientAuth = Boolean.valueOf((String) wantClientAuth);
sslConnector.setWantClientAuth(((Boolean) wantClientAuth).booleanValue());
}
String protocol = (String) dictionary.get(JettyConstants.SSL_PROTOCOL);
if (protocol != null)
sslConnector.setProtocol(protocol);
String keystoreType = (String) dictionary.get(JettyConstants.SSL_KEYSTORETYPE);
if (keystoreType != null)
sslConnector.setKeystoreType(keystoreType);
if (sslConnector.getPort() == 0) {
try {
sslConnector.open();
} catch (IOException e) {
// this would be unexpected since we're opening the next available port
e.printStackTrace();
}
}
return sslConnector;
}
private Context createHttpContext(Dictionary dictionary) {
Context httpContext = new Context();
httpContext.setAttribute(INTERNAL_CONTEXT_CLASSLOADER, Thread.currentThread().getContextClassLoader());
httpContext.setClassLoader(this.getClass().getClassLoader());
String contextPathProperty = (String) dictionary.get(JettyConstants.CONTEXT_PATH);
if (contextPathProperty == null)
contextPathProperty = "/"; //$NON-NLS-1$
httpContext.setContextPath(contextPathProperty);
File contextWorkDir = new File(workDir, DIR_PREFIX + dictionary.get(Constants.SERVICE_PID).hashCode());
contextWorkDir.mkdir();
httpContext.setAttribute(CONTEXT_TEMPDIR, contextWorkDir);
HashSessionManager sessionManager = new HashSessionManager();
Integer sessionInactiveInterval = (Integer) dictionary.get(JettyConstants.CONTEXT_SESSIONINACTIVEINTERVAL);
if (sessionInactiveInterval != null)
sessionManager.setMaxInactiveInterval(sessionInactiveInterval.intValue());
httpContext.setSessionHandler(new SessionHandler(sessionManager));
return httpContext;
}
private JettyCustomizer createJettyCustomizer(Dictionary dictionary) {
String customizerClass = (String) dictionary.get(JettyConstants.CUSTOMIZER_CLASS);
if (null == customizerClass)
return null;
try {
return (JettyCustomizer) Class.forName(customizerClass).newInstance();
} catch (Exception e) {
// TODO: consider logging this, but we should still continue
e.printStackTrace();
return null;
}
}
public static class InternalHttpServiceServlet implements Servlet {
private static final long serialVersionUID = 7477982882399972088L;
private Servlet httpServiceServlet = new HttpServiceServlet();
private ClassLoader contextLoader;
public void init(ServletConfig config) throws ServletException {
ServletContext context = config.getServletContext();
contextLoader = (ClassLoader) context.getAttribute(INTERNAL_CONTEXT_CLASSLOADER);
Thread thread = Thread.currentThread();
ClassLoader current = thread.getContextClassLoader();
thread.setContextClassLoader(contextLoader);
try {
httpServiceServlet.init(config);
} finally {
thread.setContextClassLoader(current);
}
}
public void destroy() {
Thread thread = Thread.currentThread();
ClassLoader current = thread.getContextClassLoader();
thread.setContextClassLoader(contextLoader);
try {
httpServiceServlet.destroy();
} finally {
thread.setContextClassLoader(current);
}
contextLoader = null;
}
public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
Thread thread = Thread.currentThread();
ClassLoader current = thread.getContextClassLoader();
thread.setContextClassLoader(contextLoader);
try {
httpServiceServlet.service(req, res);
} finally {
thread.setContextClassLoader(current);
}
}
public ServletConfig getServletConfig() {
return httpServiceServlet.getServletConfig();
}
public String getServletInfo() {
return httpServiceServlet.getServletInfo();
}
}
// deleteDirectory is a convenience method to recursively delete a directory
private static boolean deleteDirectory(File directory) {
if (directory.exists() && directory.isDirectory()) {
File[] files = directory.listFiles();
for (int i = 0; i < files.length; i++) {
if (files[i].isDirectory()) {
deleteDirectory(files[i]);
} else {
files[i].delete();
}
}
}
return directory.delete();
}
}
| true | true | private Connector createHttpsConnector(Dictionary dictionary) {
Boolean httpsEnabled = (Boolean) dictionary.get(JettyConstants.HTTPS_ENABLED);
if (httpsEnabled == null || !httpsEnabled.booleanValue())
return null;
Integer httpsPort = (Integer) dictionary.get(JettyConstants.HTTPS_PORT);
if (httpsPort == null)
return null;
SslSocketConnector sslConnector = new SslSocketConnector();
sslConnector.setPort(httpsPort.intValue());
String httpsHost = (String) dictionary.get(JettyConstants.HTTPS_HOST);
if (httpsHost != null) {
sslConnector.setHost(httpsHost);
}
String keyStore = (String) dictionary.get(JettyConstants.SSL_KEYSTORE);
if (keyStore != null)
sslConnector.setKeystore(keyStore);
String password = (String) dictionary.get(JettyConstants.SSL_PASSWORD);
if (password != null)
sslConnector.setPassword(password);
String keyPassword = (String) dictionary.get(JettyConstants.SSL_KEYPASSWORD);
if (keyPassword != null)
sslConnector.setKeyPassword(keyPassword);
Object needClientAuth = dictionary.get(JettyConstants.SSL_NEEDCLIENTAUTH);
if (needClientAuth != null) {
if (needClientAuth instanceof String)
needClientAuth = Boolean.valueOf((String) needClientAuth);
sslConnector.setNeedClientAuth(((Boolean) needClientAuth).booleanValue());
}
Object wantClientAuth = (Boolean) dictionary.get(JettyConstants.SSL_WANTCLIENTAUTH);
if (wantClientAuth != null) {
if (wantClientAuth instanceof String)
wantClientAuth = Boolean.valueOf((String) wantClientAuth);
sslConnector.setWantClientAuth(((Boolean) wantClientAuth).booleanValue());
}
String protocol = (String) dictionary.get(JettyConstants.SSL_PROTOCOL);
if (protocol != null)
sslConnector.setProtocol(protocol);
String keystoreType = (String) dictionary.get(JettyConstants.SSL_KEYSTORETYPE);
if (keystoreType != null)
sslConnector.setKeystoreType(keystoreType);
if (sslConnector.getPort() == 0) {
try {
sslConnector.open();
} catch (IOException e) {
// this would be unexpected since we're opening the next available port
e.printStackTrace();
}
}
return sslConnector;
}
| private Connector createHttpsConnector(Dictionary dictionary) {
Boolean httpsEnabled = (Boolean) dictionary.get(JettyConstants.HTTPS_ENABLED);
if (httpsEnabled == null || !httpsEnabled.booleanValue())
return null;
Integer httpsPort = (Integer) dictionary.get(JettyConstants.HTTPS_PORT);
if (httpsPort == null)
return null;
SslSocketConnector sslConnector = new SslSocketConnector();
sslConnector.setPort(httpsPort.intValue());
String httpsHost = (String) dictionary.get(JettyConstants.HTTPS_HOST);
if (httpsHost != null) {
sslConnector.setHost(httpsHost);
}
String keyStore = (String) dictionary.get(JettyConstants.SSL_KEYSTORE);
if (keyStore != null)
sslConnector.setKeystore(keyStore);
String password = (String) dictionary.get(JettyConstants.SSL_PASSWORD);
if (password != null)
sslConnector.setPassword(password);
String keyPassword = (String) dictionary.get(JettyConstants.SSL_KEYPASSWORD);
if (keyPassword != null)
sslConnector.setKeyPassword(keyPassword);
Object needClientAuth = dictionary.get(JettyConstants.SSL_NEEDCLIENTAUTH);
if (needClientAuth != null) {
if (needClientAuth instanceof String)
needClientAuth = Boolean.valueOf((String) needClientAuth);
sslConnector.setNeedClientAuth(((Boolean) needClientAuth).booleanValue());
}
Object wantClientAuth = dictionary.get(JettyConstants.SSL_WANTCLIENTAUTH);
if (wantClientAuth != null) {
if (wantClientAuth instanceof String)
wantClientAuth = Boolean.valueOf((String) wantClientAuth);
sslConnector.setWantClientAuth(((Boolean) wantClientAuth).booleanValue());
}
String protocol = (String) dictionary.get(JettyConstants.SSL_PROTOCOL);
if (protocol != null)
sslConnector.setProtocol(protocol);
String keystoreType = (String) dictionary.get(JettyConstants.SSL_KEYSTORETYPE);
if (keystoreType != null)
sslConnector.setKeystoreType(keystoreType);
if (sslConnector.getPort() == 0) {
try {
sslConnector.open();
} catch (IOException e) {
// this would be unexpected since we're opening the next available port
e.printStackTrace();
}
}
return sslConnector;
}
|
diff --git a/src/de/uni_koblenz/jgralab/greql2/evaluator/vertexeval/TypeIdEvaluator.java b/src/de/uni_koblenz/jgralab/greql2/evaluator/vertexeval/TypeIdEvaluator.java
index f653c801d..23ebd5ddd 100644
--- a/src/de/uni_koblenz/jgralab/greql2/evaluator/vertexeval/TypeIdEvaluator.java
+++ b/src/de/uni_koblenz/jgralab/greql2/evaluator/vertexeval/TypeIdEvaluator.java
@@ -1,133 +1,133 @@
/*
* JGraLab - The Java graph laboratory
* (c) 2006-2008 Institute for Software Technology
* University of Koblenz-Landau, Germany
*
* [email protected]
*
* Please report bugs to http://serres.uni-koblenz.de/bugzilla
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package de.uni_koblenz.jgralab.greql2.evaluator.vertexeval;
import java.util.ArrayList;
import java.util.List;
import de.uni_koblenz.jgralab.Graph;
import de.uni_koblenz.jgralab.Vertex;
import de.uni_koblenz.jgralab.greql2.evaluator.GreqlEvaluator;
import de.uni_koblenz.jgralab.greql2.evaluator.costmodel.GraphSize;
import de.uni_koblenz.jgralab.greql2.evaluator.costmodel.VertexCosts;
import de.uni_koblenz.jgralab.greql2.exception.EvaluateException;
import de.uni_koblenz.jgralab.greql2.exception.UnknownTypeException;
import de.uni_koblenz.jgralab.greql2.jvalue.JValue;
import de.uni_koblenz.jgralab.greql2.jvalue.JValueTypeCollection;
import de.uni_koblenz.jgralab.greql2.schema.TypeId;
import de.uni_koblenz.jgralab.schema.AttributedElementClass;
import de.uni_koblenz.jgralab.schema.QualifiedName;
import de.uni_koblenz.jgralab.schema.Schema;
/**
* Creates a List of types out of the TypeId-Vertex.
*
* @author [email protected]
*
*/
public class TypeIdEvaluator extends VertexEvaluator {
/**
* returns the vertex this VertexEvaluator evaluates
*/
@Override
public Vertex getVertex() {
return vertex;
}
private TypeId vertex;
public TypeIdEvaluator(TypeId vertex, GreqlEvaluator eval) {
super(eval);
this.vertex = vertex;
}
/**
* Creates a list of types from this TypeId-Vertex
*
* @param schema
* the schema of the datagraph
* @return the generated list of types
*/
protected List<AttributedElementClass> createTypeList(Schema schema)
throws EvaluateException {
ArrayList<AttributedElementClass> returnTypes = new ArrayList<AttributedElementClass>();
AttributedElementClass elemClass = (AttributedElementClass) schema
.getAttributedElementClass(new QualifiedName(vertex.getName()));
if (elemClass == null) {
elemClass = greqlEvaluator.getKnownType(vertex.getName());
if (elemClass == null)
throw new UnknownTypeException(vertex.getName(),
createPossibleSourcePositions());
else
vertex.setName(elemClass.getQualifiedName());
}
returnTypes.add(elemClass);
if (!vertex.isType()) {
- returnTypes.add(elemClass);
+ returnTypes.addAll(elemClass.getAllSubClasses());
}
return returnTypes;
}
@Override
public JValue evaluate() throws EvaluateException {
Graph datagraph = getDatagraph();
Schema schema = datagraph.getSchema();
return new JValueTypeCollection(createTypeList(schema), vertex
.isExcluded());
}
@Override
public VertexCosts calculateSubtreeEvaluationCosts(GraphSize graphSize) {
return this.greqlEvaluator.getCostModel().calculateCostsTypeId(this,
graphSize);
}
@Override
public double calculateEstimatedSelectivity(GraphSize graphSize) {
return greqlEvaluator.getCostModel().calculateSelectivityTypeId(this,
graphSize);
}
/*
* (non-Javadoc)
*
* @seede.uni_koblenz.jgralab.greql2.evaluator.vertexeval.VertexEvaluator#
* getLoggingName()
*/
@Override
public String getLoggingName() {
StringBuilder name = new StringBuilder();
name.append(vertex.getAttributedElementClass().getQualifiedName());
if (vertex.isType()) {
name.append("-type");
}
if (vertex.isExcluded()) {
name.append("-excluded");
}
return name.toString();
}
}
| true | true | protected List<AttributedElementClass> createTypeList(Schema schema)
throws EvaluateException {
ArrayList<AttributedElementClass> returnTypes = new ArrayList<AttributedElementClass>();
AttributedElementClass elemClass = (AttributedElementClass) schema
.getAttributedElementClass(new QualifiedName(vertex.getName()));
if (elemClass == null) {
elemClass = greqlEvaluator.getKnownType(vertex.getName());
if (elemClass == null)
throw new UnknownTypeException(vertex.getName(),
createPossibleSourcePositions());
else
vertex.setName(elemClass.getQualifiedName());
}
returnTypes.add(elemClass);
if (!vertex.isType()) {
returnTypes.add(elemClass);
}
return returnTypes;
}
| protected List<AttributedElementClass> createTypeList(Schema schema)
throws EvaluateException {
ArrayList<AttributedElementClass> returnTypes = new ArrayList<AttributedElementClass>();
AttributedElementClass elemClass = (AttributedElementClass) schema
.getAttributedElementClass(new QualifiedName(vertex.getName()));
if (elemClass == null) {
elemClass = greqlEvaluator.getKnownType(vertex.getName());
if (elemClass == null)
throw new UnknownTypeException(vertex.getName(),
createPossibleSourcePositions());
else
vertex.setName(elemClass.getQualifiedName());
}
returnTypes.add(elemClass);
if (!vertex.isType()) {
returnTypes.addAll(elemClass.getAllSubClasses());
}
return returnTypes;
}
|
diff --git a/mpayments-help/mpayments-help-repo-rest/src/main/java/org/infobip/mpayments/help/repo/rest/RestAPIService.java b/mpayments-help/mpayments-help-repo-rest/src/main/java/org/infobip/mpayments/help/repo/rest/RestAPIService.java
index 38c53ba..a47a3a3 100644
--- a/mpayments-help/mpayments-help-repo-rest/src/main/java/org/infobip/mpayments/help/repo/rest/RestAPIService.java
+++ b/mpayments-help/mpayments-help-repo-rest/src/main/java/org/infobip/mpayments/help/repo/rest/RestAPIService.java
@@ -1,526 +1,526 @@
package org.infobip.mpayments.help.repo.rest;
import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
import java.util.StringTokenizer;
import javax.ejb.Stateless;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.Repository;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.SimpleCredentials;
import javax.jcr.Workspace;
import javax.jcr.query.Query;
import javax.jcr.query.QueryManager;
import javax.jcr.query.QueryResult;
import javax.naming.InitialContext;
import javax.ws.rs.PathParam;
import javax.ws.rs.core.Response;
import org.infobip.mpayments.help.freemarker.FreeMarker;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
@Stateless
public class RestAPIService implements RestAPI {
static final Logger logger = LoggerFactory.getLogger(RestHelpRepoService.class);
@Override
public Response getParagraph(@PathParam("app") String app, @PathParam("topic") String topic,
@PathParam("parID") String parID) {
return getParagraph(app, topic, parID, "");
}
@Override
public Response getParagraph(@PathParam("app") String app, @PathParam("topic") String topic,
@PathParam("parID") String parID, @PathParam("fieldPars") String fieldPars) {
Session session = null;
Repository repository = null;
boolean error = false;
InputStream input = null;
OutputStream output = null;
String result = null;
StringTokenizer stringTokenizer = null;
Map<String, Object> mapParameters = new HashMap<String, Object>();
String reseller = null;
String language = null;
String noSuchID = "No such ID!";
StringBuffer returnResult = new StringBuffer();
System.out.println("POZVANA METODA getParagraph");
try {
System.out.println("field par uri " + fieldPars);
if (fieldPars == null) {
error = true;
fieldPars = "";
}
if (fieldPars.startsWith("?"))
fieldPars = fieldPars.substring(1);
InitialContext initialContext = new InitialContext();
repository = (Repository) initialContext.lookup("java:jcr/local");
session = repository.login(new SimpleCredentials("admin", "admin".toCharArray()));
if (!fieldPars.equals("")) {
stringTokenizer = new StringTokenizer(fieldPars, "?&=");
System.out.println("FIELD PARAMS " + fieldPars);
while (stringTokenizer.hasMoreTokens()) {
String first = stringTokenizer.nextToken();
String second = stringTokenizer.nextToken();
if ("reseller".equalsIgnoreCase(first)) {
reseller = second;
continue;
}
if ("language".equalsIgnoreCase(first)) {
language = second;
continue;
}
mapParameters.put(first, second);
}
}
if (language == null) {
language = "en";
}
if (reseller == null) {
reseller = "1";
}
System.out.println("ispis mape");
for (Map.Entry<String, Object> entry : mapParameters.entrySet()) {
System.out.println(entry.getKey() + " = " + entry.getValue());
}
String path = "/help/" + app + "/" + topic;
Workspace ws = session.getWorkspace();
QueryManager qm = ws.getQueryManager();
Query query = qm.createQuery("SELECT * FROM [mix:title] WHERE [my:lang] = '" + language
+ "' and [my:reseller] = '" + reseller + "' and ISCHILDNODE([" + path + "])", Query.JCR_SQL2);
QueryResult res = query.execute();
NodeIterator it = res.getNodes();
Node node = null;
while (it.hasNext()) {
node = it.nextNode();
}
System.out.println("path " + node.getPath());
Node content = node.getNode("jcr:content");
input = content.getProperty("jcr:data").getBinary().getStream();
result = RestAPIService.getStringFromInputStream(input).toString();
if (!mapParameters.isEmpty()) {
FreeMarker fm = new FreeMarker();
result = fm.process(mapParameters, result);
}
res = null;
it = null;
} catch (Exception ex) {
error = true;
ex.printStackTrace();
} finally {
if (session != null)
session.logout();
closeStreams(input, output);
}
if (!error) {
Document doc = Jsoup.parse(result);
Elements divs = doc.getElementsByTag("div");
for (Element elem : divs) {
if (elem.id().equals(parID)) {
// if (elem.className().equals(parID)) {
returnResult.append(elem.toString());
}
}
if ("".equals(returnResult.toString())) {
- return Response.status(Response.Status.NO_CONTENT).entity(noSuchID).build();
+ return Response.status(Response.Status.OK).entity(noSuchID).build();
} else {
return Response.status(Response.Status.OK).entity(returnResult.toString()).build();
}
} else {
return Response.status(Response.Status.NOT_FOUND).entity("error").build();
}
}
@Override
public Response getDocuments(@PathParam("id") String id) {
Session session = null;
Repository repository = null;
boolean error = false;
InputStream input = null;
OutputStream output = null;
String result = null;
System.out.println("POZVANA METODA getDocuments");
try {
InitialContext initialContext = new InitialContext();
repository = (Repository) initialContext.lookup("java:jcr/local");
session = repository.login(new SimpleCredentials("admin", "admin".toCharArray()));
Node en = session.getNode("/help/pp/service/1/en");
Node target = session.getNodeByIdentifier(en.getIdentifier());
printChildren(session.getNode("/"));
Node content = target.getNode("jcr:content");
input = content.getProperty("jcr:data").getBinary().getStream();
result = RestAPIService.getStringFromInputStream(input).toString();
} catch (Exception ex) {
error = true;
ex.printStackTrace();
} finally {
if (session != null)
session.logout();
closeStreams(input, output);
}
if (!error) {
return Response.status(Response.Status.OK).entity(result).build();
} else {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("error").build();
}
}
// za staro drvo
// @Override
public Response getDoc(@PathParam("rPath") String rPath) {
Session session = null;
Repository repository = null;
boolean error = false;
InputStream input = null;
OutputStream output = null;
String result = null;
System.out.println("POZVANA METODA getDoc");
try {
InitialContext initialContext = new InitialContext();
repository = (Repository) initialContext.lookup("java:jcr/local");
session = repository.login(new SimpleCredentials("admin", "admin".toCharArray()));
System.out.println("rpath " + rPath);
Node target = session.getNode("/" + rPath);
input = target.getProperty("jcr:data").getBinary().getStream();
result = RestAPIService.getStringFromInputStream(input).toString();
} catch (Exception ex) {
error = true;
ex.printStackTrace();
} finally {
if (session != null)
session.logout();
closeStreams(input, output);
}
if (!error) {
return Response.status(Response.Status.OK).entity(result).build();
} else {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("error").build();
}
}
private static StringBuilder getStringFromInputStream(InputStream is) {
BufferedReader br = null;
StringBuilder sb = new StringBuilder();
String line;
try {
br = new BufferedReader(new InputStreamReader(is));
while ((line = br.readLine()) != null) {
sb.append(line);
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (br != null) {
try {
br.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return sb;
}
private void closeStreams(InputStream input, OutputStream output) {
if (input != null)
try {
input.close();
} catch (IOException e) {
e.printStackTrace();
}
if (output != null)
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
@SuppressWarnings("unused")
private String readFile(File file) throws IOException {
StringBuilder fileContents = new StringBuilder((int) file.length());
Scanner scanner = new Scanner(file);
String lineSeparator = System.getProperty("line.separator");
try {
while (scanner.hasNextLine()) {
fileContents.append(scanner.nextLine() + lineSeparator);
}
return fileContents.toString();
} finally {
scanner.close();
}
}
private void printChildren(Node node) throws RepositoryException {
if (node.hasNodes()) {
NodeIterator it = node.getNodes();
while (it.hasNext()) {
Node child = it.nextNode();
printChildren(child);
}
}
}
@Override
public Response getDocument(@PathParam("app") String app, @PathParam("topic") String topic) {
return getDocument(app, topic, "");
}
@Override
public Response getDocument(@PathParam("app") String app, @PathParam("topic") String topic,
@PathParam("fieldPars") String fieldPars) {
Session session = null;
Repository repository = null;
boolean error = false;
InputStream input = null;
OutputStream output = null;
String result = null;
StringTokenizer stringTokenizer = null;
Map<String, Object> mapParameters = new HashMap<String, Object>();
String reseller = null;
String language = null;
System.out.println("POZVANA METODA getDocument");
try {
System.out.println("field par uri " + fieldPars);
if (fieldPars == null) {
error = true;
fieldPars = "";
}
if (fieldPars.startsWith("?"))
fieldPars = fieldPars.substring(1);
InitialContext initialContext = new InitialContext();
repository = (Repository) initialContext.lookup("java:jcr/local");
session = repository.login(new SimpleCredentials("admin", "admin".toCharArray()));
if (!fieldPars.equals("")) {
stringTokenizer = new StringTokenizer(fieldPars, "?&=");
System.out.println("FIELD PARAMS " + fieldPars);
while (stringTokenizer.hasMoreTokens()) {
String first = stringTokenizer.nextToken();
String second = stringTokenizer.nextToken();
if ("reseller".equalsIgnoreCase(first)) {
reseller = second;
continue;
}
if ("language".equalsIgnoreCase(first)) {
language = second;
continue;
}
mapParameters.put(first, second);
}
}
if (language == null) {
language = "en";
}
if (reseller == null) {
reseller = "1";
}
System.out.println("ispis mape");
for (Map.Entry<String, Object> entry : mapParameters.entrySet()) {
System.out.println(entry.getKey() + " = " + entry.getValue());
}
String path = "/help/" + app + "/" + topic;
Workspace ws = session.getWorkspace();
QueryManager qm = ws.getQueryManager();
// System.out.println("query " +
// "SELECT * FROM [mix:title] WHERE [my:lang] = '"+language+
// "' and [my:reseller] = '" +reseller+"'");
// Query query =
// qm.createQuery("SELECT * FROM [mix:title] WHERE [my:lang] = '"+language+
// "' and [my:reseller] = '" +reseller+"'", Query.JCR_SQL2);
Query query = qm.createQuery("SELECT * FROM [mix:title] WHERE [my:lang] = '" + language
+ "' and [my:reseller] = '" + reseller + "' and ISCHILDNODE([" + path + "])", Query.JCR_SQL2);
QueryResult res = query.execute();
NodeIterator it = res.getNodes();
Node node = null;
while (it.hasNext()) {
node = it.nextNode();
}
System.out.println("path " + node.getPath());
Node content = node.getNode("jcr:content");
input = content.getProperty("jcr:data").getBinary().getStream();
result = RestAPIService.getStringFromInputStream(input).toString();
if (!mapParameters.isEmpty()) {
FreeMarker fm = new FreeMarker();
result = fm.process(mapParameters, result);
}
res = null;
it = null;
} catch (Exception ex) {
error = true;
ex.printStackTrace();
} finally {
if (session != null)
session.logout();
closeStreams(input, output);
}
if (!error) {
return Response.status(Response.Status.OK).entity(result).build();
} else {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity("error").build();
}
}
@Override
public Response delDocument(@PathParam("app") String app, @PathParam("topic") String topic,
@PathParam("fieldPars") String fieldPars) {
Session session = null;
Repository repository = null;
boolean error = false;
InputStream input = null;
OutputStream output = null;
String result = null;
StringTokenizer stringTokenizer = null;
String reseller = null;
String language = null;
String path = "";
boolean notFound = false;
String errorString = "error";
System.out.println("POZVANA METODA delDocument");
try {
System.out.println("field par uri " + fieldPars);
if (fieldPars == null) {
error = true;
fieldPars = "";
}
if (fieldPars.startsWith("?"))
fieldPars = fieldPars.substring(1);
InitialContext initialContext = new InitialContext();
repository = (Repository) initialContext.lookup("java:jcr/local");
session = repository.login(new SimpleCredentials("admin", "admin".toCharArray()));
if (!fieldPars.equals("")) {
stringTokenizer = new StringTokenizer(fieldPars, "?&=");
System.out.println("FIELD PARAMS " + fieldPars);
while (stringTokenizer.hasMoreTokens()) {
String first = stringTokenizer.nextToken();
String second = stringTokenizer.nextToken();
if ("reseller".equalsIgnoreCase(first)) {
reseller = second;
continue;
}
if ("language".equalsIgnoreCase(first)) {
language = second;
continue;
}
}
}
if (language == null && reseller == null) {
language = "";
reseller = "";
}
path = "/help/" + app + "/" + topic;
Workspace ws = session.getWorkspace();
QueryManager qm = ws.getQueryManager();
Query query = qm.createQuery("SELECT * FROM [mix:title] WHERE [my:lang] = '" + language
+ "' and [my:reseller] = '" + reseller + "' and ISCHILDNODE([" + path + "])", Query.JCR_SQL2);
QueryResult res = query.execute();
NodeIterator it = res.getNodes();
Node node = null;
if (it.hasNext()) {
node = it.nextNode();
path = node.getPath();
Node parent = node.getParent();
node.remove();
if(!parent.hasNodes()){
parent.remove();
}
}else{
if(language.equals("") && reseller.equals("")){
node = session.getNode(path);
node.remove();
}else{
notFound = true;
errorString = "Not found!";
}
}
session.save();
res = null;
it = null;
} catch (Exception ex) {
error = true;
ex.printStackTrace();
} finally {
if (session != null)
session.logout();
closeStreams(input, output);
}
if(notFound){
return Response.status(Response.Status.NOT_FOUND).entity(errorString).build();
}
if (!error) {
return Response.status(Response.Status.OK).entity("Deleted node with path: "+path+" .").build();
} else {
return Response.status(Response.Status.INTERNAL_SERVER_ERROR).entity(errorString).build();
}
}
@Override
public Response delDocument(@PathParam("app") String app, @PathParam("topic") String topic) {
return delDocument(app, topic,"");
}
}
| true | true | public Response getParagraph(@PathParam("app") String app, @PathParam("topic") String topic,
@PathParam("parID") String parID, @PathParam("fieldPars") String fieldPars) {
Session session = null;
Repository repository = null;
boolean error = false;
InputStream input = null;
OutputStream output = null;
String result = null;
StringTokenizer stringTokenizer = null;
Map<String, Object> mapParameters = new HashMap<String, Object>();
String reseller = null;
String language = null;
String noSuchID = "No such ID!";
StringBuffer returnResult = new StringBuffer();
System.out.println("POZVANA METODA getParagraph");
try {
System.out.println("field par uri " + fieldPars);
if (fieldPars == null) {
error = true;
fieldPars = "";
}
if (fieldPars.startsWith("?"))
fieldPars = fieldPars.substring(1);
InitialContext initialContext = new InitialContext();
repository = (Repository) initialContext.lookup("java:jcr/local");
session = repository.login(new SimpleCredentials("admin", "admin".toCharArray()));
if (!fieldPars.equals("")) {
stringTokenizer = new StringTokenizer(fieldPars, "?&=");
System.out.println("FIELD PARAMS " + fieldPars);
while (stringTokenizer.hasMoreTokens()) {
String first = stringTokenizer.nextToken();
String second = stringTokenizer.nextToken();
if ("reseller".equalsIgnoreCase(first)) {
reseller = second;
continue;
}
if ("language".equalsIgnoreCase(first)) {
language = second;
continue;
}
mapParameters.put(first, second);
}
}
if (language == null) {
language = "en";
}
if (reseller == null) {
reseller = "1";
}
System.out.println("ispis mape");
for (Map.Entry<String, Object> entry : mapParameters.entrySet()) {
System.out.println(entry.getKey() + " = " + entry.getValue());
}
String path = "/help/" + app + "/" + topic;
Workspace ws = session.getWorkspace();
QueryManager qm = ws.getQueryManager();
Query query = qm.createQuery("SELECT * FROM [mix:title] WHERE [my:lang] = '" + language
+ "' and [my:reseller] = '" + reseller + "' and ISCHILDNODE([" + path + "])", Query.JCR_SQL2);
QueryResult res = query.execute();
NodeIterator it = res.getNodes();
Node node = null;
while (it.hasNext()) {
node = it.nextNode();
}
System.out.println("path " + node.getPath());
Node content = node.getNode("jcr:content");
input = content.getProperty("jcr:data").getBinary().getStream();
result = RestAPIService.getStringFromInputStream(input).toString();
if (!mapParameters.isEmpty()) {
FreeMarker fm = new FreeMarker();
result = fm.process(mapParameters, result);
}
res = null;
it = null;
} catch (Exception ex) {
error = true;
ex.printStackTrace();
} finally {
if (session != null)
session.logout();
closeStreams(input, output);
}
if (!error) {
Document doc = Jsoup.parse(result);
Elements divs = doc.getElementsByTag("div");
for (Element elem : divs) {
if (elem.id().equals(parID)) {
// if (elem.className().equals(parID)) {
returnResult.append(elem.toString());
}
}
if ("".equals(returnResult.toString())) {
return Response.status(Response.Status.NO_CONTENT).entity(noSuchID).build();
} else {
return Response.status(Response.Status.OK).entity(returnResult.toString()).build();
}
} else {
return Response.status(Response.Status.NOT_FOUND).entity("error").build();
}
}
| public Response getParagraph(@PathParam("app") String app, @PathParam("topic") String topic,
@PathParam("parID") String parID, @PathParam("fieldPars") String fieldPars) {
Session session = null;
Repository repository = null;
boolean error = false;
InputStream input = null;
OutputStream output = null;
String result = null;
StringTokenizer stringTokenizer = null;
Map<String, Object> mapParameters = new HashMap<String, Object>();
String reseller = null;
String language = null;
String noSuchID = "No such ID!";
StringBuffer returnResult = new StringBuffer();
System.out.println("POZVANA METODA getParagraph");
try {
System.out.println("field par uri " + fieldPars);
if (fieldPars == null) {
error = true;
fieldPars = "";
}
if (fieldPars.startsWith("?"))
fieldPars = fieldPars.substring(1);
InitialContext initialContext = new InitialContext();
repository = (Repository) initialContext.lookup("java:jcr/local");
session = repository.login(new SimpleCredentials("admin", "admin".toCharArray()));
if (!fieldPars.equals("")) {
stringTokenizer = new StringTokenizer(fieldPars, "?&=");
System.out.println("FIELD PARAMS " + fieldPars);
while (stringTokenizer.hasMoreTokens()) {
String first = stringTokenizer.nextToken();
String second = stringTokenizer.nextToken();
if ("reseller".equalsIgnoreCase(first)) {
reseller = second;
continue;
}
if ("language".equalsIgnoreCase(first)) {
language = second;
continue;
}
mapParameters.put(first, second);
}
}
if (language == null) {
language = "en";
}
if (reseller == null) {
reseller = "1";
}
System.out.println("ispis mape");
for (Map.Entry<String, Object> entry : mapParameters.entrySet()) {
System.out.println(entry.getKey() + " = " + entry.getValue());
}
String path = "/help/" + app + "/" + topic;
Workspace ws = session.getWorkspace();
QueryManager qm = ws.getQueryManager();
Query query = qm.createQuery("SELECT * FROM [mix:title] WHERE [my:lang] = '" + language
+ "' and [my:reseller] = '" + reseller + "' and ISCHILDNODE([" + path + "])", Query.JCR_SQL2);
QueryResult res = query.execute();
NodeIterator it = res.getNodes();
Node node = null;
while (it.hasNext()) {
node = it.nextNode();
}
System.out.println("path " + node.getPath());
Node content = node.getNode("jcr:content");
input = content.getProperty("jcr:data").getBinary().getStream();
result = RestAPIService.getStringFromInputStream(input).toString();
if (!mapParameters.isEmpty()) {
FreeMarker fm = new FreeMarker();
result = fm.process(mapParameters, result);
}
res = null;
it = null;
} catch (Exception ex) {
error = true;
ex.printStackTrace();
} finally {
if (session != null)
session.logout();
closeStreams(input, output);
}
if (!error) {
Document doc = Jsoup.parse(result);
Elements divs = doc.getElementsByTag("div");
for (Element elem : divs) {
if (elem.id().equals(parID)) {
// if (elem.className().equals(parID)) {
returnResult.append(elem.toString());
}
}
if ("".equals(returnResult.toString())) {
return Response.status(Response.Status.OK).entity(noSuchID).build();
} else {
return Response.status(Response.Status.OK).entity(returnResult.toString()).build();
}
} else {
return Response.status(Response.Status.NOT_FOUND).entity("error").build();
}
}
|
diff --git a/src/main/java/core/util/StringUtil.java b/src/main/java/core/util/StringUtil.java
index 5b39459..907fb92 100644
--- a/src/main/java/core/util/StringUtil.java
+++ b/src/main/java/core/util/StringUtil.java
@@ -1,41 +1,41 @@
package core.util;
import java.io.UnsupportedEncodingException;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
* Helper methods for strings.
*
* @author jani
*
*/
public class StringUtil {
/**
* Gets the SHA-256 hash code of a string.
*
* @param input
* The string to hash..
* @return the SHA-256 hash code.
*/
public static String sha256(String input) {
MessageDigest digest;
try {
digest = MessageDigest.getInstance("SHA-256");
digest.reset();
byte[] bytes = digest.digest(input.getBytes("UTF-8"));
BigInteger bigInt = new BigInteger(1, bytes);
- return bigInt.toString(16);
+ return String.format("%064x", bigInt);
} catch (NoSuchAlgorithmException e) {
assert false;
} catch (UnsupportedEncodingException e) {
assert false;
}
return null;
}
}
| true | true | public static String sha256(String input) {
MessageDigest digest;
try {
digest = MessageDigest.getInstance("SHA-256");
digest.reset();
byte[] bytes = digest.digest(input.getBytes("UTF-8"));
BigInteger bigInt = new BigInteger(1, bytes);
return bigInt.toString(16);
} catch (NoSuchAlgorithmException e) {
assert false;
} catch (UnsupportedEncodingException e) {
assert false;
}
return null;
}
| public static String sha256(String input) {
MessageDigest digest;
try {
digest = MessageDigest.getInstance("SHA-256");
digest.reset();
byte[] bytes = digest.digest(input.getBytes("UTF-8"));
BigInteger bigInt = new BigInteger(1, bytes);
return String.format("%064x", bigInt);
} catch (NoSuchAlgorithmException e) {
assert false;
} catch (UnsupportedEncodingException e) {
assert false;
}
return null;
}
|
diff --git a/luni/src/main/java/java/util/zip/ZipFile.java b/luni/src/main/java/java/util/zip/ZipFile.java
index 5d16f33c7..172141c01 100644
--- a/luni/src/main/java/java/util/zip/ZipFile.java
+++ b/luni/src/main/java/java/util/zip/ZipFile.java
@@ -1,450 +1,450 @@
/*
* 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 java.util.zip;
import dalvik.system.CloseGuard;
import java.io.BufferedInputStream;
import java.io.EOFException;
import java.io.DataInputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.RandomAccessFile;
import java.nio.ByteOrder;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.LinkedHashMap;
import libcore.io.BufferIterator;
import libcore.io.HeapBufferIterator;
import libcore.io.Streams;
/**
* This class provides random read access to a zip file. You pay more to read
* the zip file's central directory up front (from the constructor), but if you're using
* {@link #getEntry} to look up multiple files by name, you get the benefit of this index.
*
* <p>If you only want to iterate through all the files (using {@link #entries}, you should
* consider {@link ZipInputStream}, which provides stream-like read access to a zip file and
* has a lower up-front cost because you don't pay to build an in-memory index.
*
* <p>If you want to create a zip file, use {@link ZipOutputStream}. There is no API for updating
* an existing zip file.
*/
public class ZipFile implements ZipConstants {
/**
* General Purpose Bit Flags, Bit 3.
* If this bit is set, the fields crc-32, compressed
* size and uncompressed size are set to zero in the
* local header. The correct values are put in the
* data descriptor immediately following the compressed
* data. (Note: PKZIP version 2.04g for DOS only
* recognizes this bit for method 8 compression, newer
* versions of PKZIP recognize this bit for any
* compression method.)
*/
static final int GPBF_DATA_DESCRIPTOR_FLAG = 1 << 3;
/**
* General Purpose Bit Flags, Bit 11.
* Language encoding flag (EFS). If this bit is set,
* the filename and comment fields for this file
* must be encoded using UTF-8.
*/
static final int GPBF_UTF8_FLAG = 1 << 11;
/**
* Open zip file for reading.
*/
public static final int OPEN_READ = 1;
/**
* Delete zip file when closed.
*/
public static final int OPEN_DELETE = 4;
private final String filename;
private File fileToDeleteOnClose;
private RandomAccessFile raf;
private final LinkedHashMap<String, ZipEntry> entries = new LinkedHashMap<String, ZipEntry>();
private final CloseGuard guard = CloseGuard.get();
/**
* Constructs a new {@code ZipFile} allowing read access to the contents of the given file.
* @throws ZipException if a zip error occurs.
* @throws IOException if an {@code IOException} occurs.
*/
public ZipFile(File file) throws ZipException, IOException {
this(file, OPEN_READ);
}
/**
* Constructs a new {@code ZipFile} allowing read access to the contents of the given file.
* @throws IOException if an IOException occurs.
*/
public ZipFile(String name) throws IOException {
this(new File(name), OPEN_READ);
}
/**
* Constructs a new {@code ZipFile} allowing access to the given file.
* The {@code mode} must be either {@code OPEN_READ} or {@code OPEN_READ|OPEN_DELETE}.
*
* <p>If the {@code OPEN_DELETE} flag is supplied, the file will be deleted at or before the
* time that the {@code ZipFile} is closed (the contents will remain accessible until
* this {@code ZipFile} is closed); it also calls {@code File.deleteOnExit}.
*
* @throws IOException if an {@code IOException} occurs.
*/
public ZipFile(File file, int mode) throws IOException {
filename = file.getPath();
if (mode != OPEN_READ && mode != (OPEN_READ | OPEN_DELETE)) {
throw new IllegalArgumentException("Bad mode: " + mode);
}
if ((mode & OPEN_DELETE) != 0) {
fileToDeleteOnClose = file;
fileToDeleteOnClose.deleteOnExit();
} else {
fileToDeleteOnClose = null;
}
raf = new RandomAccessFile(filename, "r");
readCentralDir();
guard.open("close");
}
@Override protected void finalize() throws IOException {
try {
if (guard != null) {
guard.warnIfOpen();
}
} finally {
try {
super.finalize();
} catch (Throwable t) {
throw new AssertionError(t);
}
}
}
/**
* Closes this zip file. This method is idempotent. This method may cause I/O if the
* zip file needs to be deleted.
*
* @throws IOException
* if an IOException occurs.
*/
public void close() throws IOException {
guard.close();
RandomAccessFile localRaf = raf;
if (localRaf != null) { // Only close initialized instances
synchronized (localRaf) {
raf = null;
localRaf.close();
}
if (fileToDeleteOnClose != null) {
fileToDeleteOnClose.delete();
fileToDeleteOnClose = null;
}
}
}
private void checkNotClosed() {
if (raf == null) {
throw new IllegalStateException("Zip file closed");
}
}
/**
* Returns an enumeration of the entries. The entries are listed in the
* order in which they appear in the zip file.
*
* <p>If you only need to iterate over the entries in a zip file, and don't
* need random-access entry lookup by name, you should probably use {@link ZipInputStream}
* instead, to avoid paying to construct the in-memory index.
*
* @throws IllegalStateException if this zip file has been closed.
*/
public Enumeration<? extends ZipEntry> entries() {
checkNotClosed();
final Iterator<ZipEntry> iterator = entries.values().iterator();
return new Enumeration<ZipEntry>() {
public boolean hasMoreElements() {
checkNotClosed();
return iterator.hasNext();
}
public ZipEntry nextElement() {
checkNotClosed();
return iterator.next();
}
};
}
/**
* Returns the zip entry with the given name, or null if there is no such entry.
*
* @throws IllegalStateException if this zip file has been closed.
*/
public ZipEntry getEntry(String entryName) {
checkNotClosed();
if (entryName == null) {
throw new NullPointerException("entryName == null");
}
ZipEntry ze = entries.get(entryName);
if (ze == null) {
ze = entries.get(entryName + "/");
}
return ze;
}
/**
* Returns an input stream on the data of the specified {@code ZipEntry}.
*
* @param entry
* the ZipEntry.
* @return an input stream of the data contained in the {@code ZipEntry}.
* @throws IOException
* if an {@code IOException} occurs.
* @throws IllegalStateException if this zip file has been closed.
*/
public InputStream getInputStream(ZipEntry entry) throws IOException {
// Make sure this ZipEntry is in this Zip file. We run it through the name lookup.
entry = getEntry(entry.getName());
if (entry == null) {
return null;
}
// Create an InputStream at the right part of the file.
RandomAccessFile localRaf = raf;
synchronized (localRaf) {
// We don't know the entry data's start position. All we have is the
// position of the entry's local header. At position 28 we find the
// length of the extra data. In some cases this length differs from
// the one coming in the central header.
RAFStream rafStream = new RAFStream(localRaf, entry.localHeaderRelOffset + 28);
DataInputStream is = new DataInputStream(rafStream);
int localExtraLenOrWhatever = Short.reverseBytes(is.readShort());
is.close();
// Skip the name and this "extra" data or whatever it is:
rafStream.skip(entry.nameLength + localExtraLenOrWhatever);
rafStream.length = rafStream.offset + entry.compressedSize;
if (entry.compressionMethod == ZipEntry.DEFLATED) {
int bufSize = Math.max(1024, (int)Math.min(entry.getSize(), 65535L));
return new ZipInflaterInputStream(rafStream, new Inflater(true), bufSize, entry);
} else {
return rafStream;
}
}
}
/**
* Gets the file name of this {@code ZipFile}.
*
* @return the file name of this {@code ZipFile}.
*/
public String getName() {
return filename;
}
/**
* Returns the number of {@code ZipEntries} in this {@code ZipFile}.
*
* @return the number of entries in this file.
* @throws IllegalStateException if this zip file has been closed.
*/
public int size() {
checkNotClosed();
return entries.size();
}
/**
* Find the central directory and read the contents.
*
* <p>The central directory can be followed by a variable-length comment
* field, so we have to scan through it backwards. The comment is at
* most 64K, plus we have 18 bytes for the end-of-central-dir stuff
* itself, plus apparently sometimes people throw random junk on the end
* just for the fun of it.
*
* <p>This is all a little wobbly. If the wrong value ends up in the EOCD
* area, we're hosed. This appears to be the way that everybody handles
* it though, so we're in good company if this fails.
*/
private void readCentralDir() throws IOException {
// Scan back, looking for the End Of Central Directory field. If the zip file doesn't
// have an overall comment (unrelated to any per-entry comments), we'll hit the EOCD
// on the first try.
// No need to synchronize raf here -- we only do this when we first open the zip file.
long scanOffset = raf.length() - ENDHDR;
if (scanOffset < 0) {
throw new ZipException("File too short to be a zip file: " + raf.length());
}
long stopOffset = scanOffset - 65536;
if (stopOffset < 0) {
stopOffset = 0;
}
final int ENDHEADERMAGIC = 0x06054b50;
while (true) {
raf.seek(scanOffset);
if (Integer.reverseBytes(raf.readInt()) == ENDHEADERMAGIC) {
break;
}
scanOffset--;
if (scanOffset < stopOffset) {
throw new ZipException("EOCD not found; not a zip file?");
}
}
// Read the End Of Central Directory. We could use ENDHDR instead of the magic number 18,
// but we don't actually need all the header.
byte[] eocd = new byte[18];
raf.readFully(eocd);
// Pull out the information we need.
BufferIterator it = HeapBufferIterator.iterator(eocd, 0, eocd.length, ByteOrder.LITTLE_ENDIAN);
int diskNumber = it.readShort() & 0xffff;
int diskWithCentralDir = it.readShort() & 0xffff;
int numEntries = it.readShort() & 0xffff;
int totalNumEntries = it.readShort() & 0xffff;
it.skip(4); // Ignore centralDirSize.
long centralDirOffset = ((long) it.readInt()) & 0xffffffffL;
if (numEntries != totalNumEntries || diskNumber != 0 || diskWithCentralDir != 0) {
throw new ZipException("spanned archives not supported");
}
// Seek to the first CDE and read all entries.
// We have to do this now (from the constructor) rather than lazily because the
// public API doesn't allow us to throw IOException except from the constructor
// or from getInputStream.
RAFStream rafStream = new RAFStream(raf, centralDirOffset);
BufferedInputStream bufferedStream = new BufferedInputStream(rafStream, 4096);
byte[] hdrBuf = new byte[CENHDR]; // Reuse the same buffer for each entry.
for (int i = 0; i < numEntries; ++i) {
ZipEntry newEntry = new ZipEntry(hdrBuf, bufferedStream);
String entryName = newEntry.getName();
- if (mEntries.put(entryName, newEntry) != null) {
+ if (entries.put(entryName, newEntry) != null) {
throw new ZipException("Duplicate entry name: " + entryName);
}
}
}
/**
* Wrap a stream around a RandomAccessFile. The RandomAccessFile is shared
* among all streams returned by getInputStream(), so we have to synchronize
* access to it. (We can optimize this by adding buffering here to reduce
* collisions.)
*
* <p>We could support mark/reset, but we don't currently need them.
*/
static class RAFStream extends InputStream {
private final RandomAccessFile sharedRaf;
private long length;
private long offset;
public RAFStream(RandomAccessFile raf, long initialOffset) throws IOException {
sharedRaf = raf;
offset = initialOffset;
length = raf.length();
}
@Override public int available() throws IOException {
return (offset < length ? 1 : 0);
}
@Override public int read() throws IOException {
return Streams.readSingleByte(this);
}
@Override public int read(byte[] b, int off, int len) throws IOException {
synchronized (sharedRaf) {
sharedRaf.seek(offset);
if (len > length - offset) {
len = (int) (length - offset);
}
int count = sharedRaf.read(b, off, len);
if (count > 0) {
offset += count;
return count;
} else {
return -1;
}
}
}
@Override public long skip(long byteCount) throws IOException {
if (byteCount > length - offset) {
byteCount = length - offset;
}
offset += byteCount;
return byteCount;
}
public int fill(Inflater inflater, int nativeEndBufSize) throws IOException {
synchronized (sharedRaf) {
int len = Math.min((int) (length - offset), nativeEndBufSize);
int cnt = inflater.setFileInput(sharedRaf.getFD(), offset, nativeEndBufSize);
// setFileInput read from the file, so we need to get the OS and RAFStream back
// in sync...
skip(cnt);
return len;
}
}
}
static class ZipInflaterInputStream extends InflaterInputStream {
private final ZipEntry entry;
private long bytesRead = 0;
public ZipInflaterInputStream(InputStream is, Inflater inf, int bsize, ZipEntry entry) {
super(is, inf, bsize);
this.entry = entry;
}
@Override public int read(byte[] buffer, int off, int nbytes) throws IOException {
int i = super.read(buffer, off, nbytes);
if (i != -1) {
bytesRead += i;
}
return i;
}
@Override public int available() throws IOException {
if (closed) {
// Our superclass will throw an exception, but there's a jtreg test that
// explicitly checks that the InputStream returned from ZipFile.getInputStream
// returns 0 even when closed.
return 0;
}
return super.available() == 0 ? 0 : (int) (entry.getSize() - bytesRead);
}
}
}
| true | true | private void readCentralDir() throws IOException {
// Scan back, looking for the End Of Central Directory field. If the zip file doesn't
// have an overall comment (unrelated to any per-entry comments), we'll hit the EOCD
// on the first try.
// No need to synchronize raf here -- we only do this when we first open the zip file.
long scanOffset = raf.length() - ENDHDR;
if (scanOffset < 0) {
throw new ZipException("File too short to be a zip file: " + raf.length());
}
long stopOffset = scanOffset - 65536;
if (stopOffset < 0) {
stopOffset = 0;
}
final int ENDHEADERMAGIC = 0x06054b50;
while (true) {
raf.seek(scanOffset);
if (Integer.reverseBytes(raf.readInt()) == ENDHEADERMAGIC) {
break;
}
scanOffset--;
if (scanOffset < stopOffset) {
throw new ZipException("EOCD not found; not a zip file?");
}
}
// Read the End Of Central Directory. We could use ENDHDR instead of the magic number 18,
// but we don't actually need all the header.
byte[] eocd = new byte[18];
raf.readFully(eocd);
// Pull out the information we need.
BufferIterator it = HeapBufferIterator.iterator(eocd, 0, eocd.length, ByteOrder.LITTLE_ENDIAN);
int diskNumber = it.readShort() & 0xffff;
int diskWithCentralDir = it.readShort() & 0xffff;
int numEntries = it.readShort() & 0xffff;
int totalNumEntries = it.readShort() & 0xffff;
it.skip(4); // Ignore centralDirSize.
long centralDirOffset = ((long) it.readInt()) & 0xffffffffL;
if (numEntries != totalNumEntries || diskNumber != 0 || diskWithCentralDir != 0) {
throw new ZipException("spanned archives not supported");
}
// Seek to the first CDE and read all entries.
// We have to do this now (from the constructor) rather than lazily because the
// public API doesn't allow us to throw IOException except from the constructor
// or from getInputStream.
RAFStream rafStream = new RAFStream(raf, centralDirOffset);
BufferedInputStream bufferedStream = new BufferedInputStream(rafStream, 4096);
byte[] hdrBuf = new byte[CENHDR]; // Reuse the same buffer for each entry.
for (int i = 0; i < numEntries; ++i) {
ZipEntry newEntry = new ZipEntry(hdrBuf, bufferedStream);
String entryName = newEntry.getName();
if (mEntries.put(entryName, newEntry) != null) {
throw new ZipException("Duplicate entry name: " + entryName);
}
}
}
| private void readCentralDir() throws IOException {
// Scan back, looking for the End Of Central Directory field. If the zip file doesn't
// have an overall comment (unrelated to any per-entry comments), we'll hit the EOCD
// on the first try.
// No need to synchronize raf here -- we only do this when we first open the zip file.
long scanOffset = raf.length() - ENDHDR;
if (scanOffset < 0) {
throw new ZipException("File too short to be a zip file: " + raf.length());
}
long stopOffset = scanOffset - 65536;
if (stopOffset < 0) {
stopOffset = 0;
}
final int ENDHEADERMAGIC = 0x06054b50;
while (true) {
raf.seek(scanOffset);
if (Integer.reverseBytes(raf.readInt()) == ENDHEADERMAGIC) {
break;
}
scanOffset--;
if (scanOffset < stopOffset) {
throw new ZipException("EOCD not found; not a zip file?");
}
}
// Read the End Of Central Directory. We could use ENDHDR instead of the magic number 18,
// but we don't actually need all the header.
byte[] eocd = new byte[18];
raf.readFully(eocd);
// Pull out the information we need.
BufferIterator it = HeapBufferIterator.iterator(eocd, 0, eocd.length, ByteOrder.LITTLE_ENDIAN);
int diskNumber = it.readShort() & 0xffff;
int diskWithCentralDir = it.readShort() & 0xffff;
int numEntries = it.readShort() & 0xffff;
int totalNumEntries = it.readShort() & 0xffff;
it.skip(4); // Ignore centralDirSize.
long centralDirOffset = ((long) it.readInt()) & 0xffffffffL;
if (numEntries != totalNumEntries || diskNumber != 0 || diskWithCentralDir != 0) {
throw new ZipException("spanned archives not supported");
}
// Seek to the first CDE and read all entries.
// We have to do this now (from the constructor) rather than lazily because the
// public API doesn't allow us to throw IOException except from the constructor
// or from getInputStream.
RAFStream rafStream = new RAFStream(raf, centralDirOffset);
BufferedInputStream bufferedStream = new BufferedInputStream(rafStream, 4096);
byte[] hdrBuf = new byte[CENHDR]; // Reuse the same buffer for each entry.
for (int i = 0; i < numEntries; ++i) {
ZipEntry newEntry = new ZipEntry(hdrBuf, bufferedStream);
String entryName = newEntry.getName();
if (entries.put(entryName, newEntry) != null) {
throw new ZipException("Duplicate entry name: " + entryName);
}
}
}
|
diff --git a/crypto/src/org/bouncycastle/crypto/tls/NamedCurve.java b/crypto/src/org/bouncycastle/crypto/tls/NamedCurve.java
index fe18cee4..5f407a09 100644
--- a/crypto/src/org/bouncycastle/crypto/tls/NamedCurve.java
+++ b/crypto/src/org/bouncycastle/crypto/tls/NamedCurve.java
@@ -1,93 +1,93 @@
package org.bouncycastle.crypto.tls;
import org.bouncycastle.asn1.sec.SECNamedCurves;
import org.bouncycastle.asn1.x9.X9ECParameters;
import org.bouncycastle.crypto.params.ECDomainParameters;
/**
* RFC 4492 5.1.1
*
* The named curves defined here are those specified in SEC 2 [13]. Note that many of
* these curves are also recommended in ANSI X9.62 [7] and FIPS 186-2 [11]. Values 0xFE00
* through 0xFEFF are reserved for private use. Values 0xFF01 and 0xFF02 indicate that the
* client supports arbitrary prime and characteristic-2 curves, respectively (the curve
* parameters must be encoded explicitly in ECParameters).
*/
public class NamedCurve
{
public static final int sect163k1 = 1;
public static final int sect163r1 = 2;
public static final int sect163r2 = 3;
public static final int sect193r1 = 4;
public static final int sect193r2 = 5;
public static final int sect233k1 = 6;
public static final int sect233r1 = 7;
public static final int sect239k1 = 8;
public static final int sect283k1 = 9;
public static final int sect283r1 = 10;
public static final int sect409k1 = 11;
public static final int sect409r1 = 12;
public static final int sect571k1 = 13;
public static final int sect571r1 = 14;
public static final int secp160k1 = 15;
public static final int secp160r1 = 16;
public static final int secp160r2 = 17;
public static final int secp192k1 = 18;
public static final int secp192r1 = 19;
public static final int secp224k1 = 20;
public static final int secp224r1 = 21;
public static final int secp256k1 = 22;
public static final int secp256r1 = 23;
public static final int secp384r1 = 24;
public static final int secp521r1 = 25;
/*
* reserved (0xFE00..0xFEFF)
*/
public static final int arbitrary_explicit_prime_curves = 0xFF01;
public static final int arbitrary_explicit_char2_curves = 0xFF02;
private static final String[] curveNames = new String[] {
"sect163k1",
"sect163r1",
"sect163r2",
"sect193r1",
"sect193r2",
"sect233k1",
"sect233r1",
"sect239k1",
"sect283k1",
"sect283r1",
"sect409k1",
"sect409r1",
"sect571k1",
"sect571r1",
"secp160k1",
"secp160r1",
"secp160r2",
"secp192k1",
"secp192r1",
"secp224k1",
"secp224r1",
"secp256k1",
"secp256r1",
"secp384r1",
"secp521r1", };
static ECDomainParameters getECParameters(int namedCurve)
{
int index = namedCurve - 1;
if (index < 0 || index >= curveNames.length)
{
return null;
}
// Lazily created the first time a particular curve is accessed
- X9ECParameters ecP = SECNamedCurves.getByName(curveNames[namedCurve]);
+ X9ECParameters ecP = SECNamedCurves.getByName(curveNames[index]);
// It's a bit inefficient to do this conversion every time
return new ECDomainParameters(ecP.getCurve(), ecP.getG(), ecP.getN(), ecP.getH(),
ecP.getSeed());
}
}
| true | true | static ECDomainParameters getECParameters(int namedCurve)
{
int index = namedCurve - 1;
if (index < 0 || index >= curveNames.length)
{
return null;
}
// Lazily created the first time a particular curve is accessed
X9ECParameters ecP = SECNamedCurves.getByName(curveNames[namedCurve]);
// It's a bit inefficient to do this conversion every time
return new ECDomainParameters(ecP.getCurve(), ecP.getG(), ecP.getN(), ecP.getH(),
ecP.getSeed());
}
| static ECDomainParameters getECParameters(int namedCurve)
{
int index = namedCurve - 1;
if (index < 0 || index >= curveNames.length)
{
return null;
}
// Lazily created the first time a particular curve is accessed
X9ECParameters ecP = SECNamedCurves.getByName(curveNames[index]);
// It's a bit inefficient to do this conversion every time
return new ECDomainParameters(ecP.getCurve(), ecP.getG(), ecP.getN(), ecP.getH(),
ecP.getSeed());
}
|
diff --git a/lenskit-core/src/main/java/org/grouplens/lenskit/baseline/ItemMeanPredictor.java b/lenskit-core/src/main/java/org/grouplens/lenskit/baseline/ItemMeanPredictor.java
index 86a46a083..19aac74af 100644
--- a/lenskit-core/src/main/java/org/grouplens/lenskit/baseline/ItemMeanPredictor.java
+++ b/lenskit-core/src/main/java/org/grouplens/lenskit/baseline/ItemMeanPredictor.java
@@ -1,210 +1,214 @@
/*
* LensKit, an open source recommender systems toolkit.
* Copyright 2010-2013 Regents of the University of Minnesota and contributors
* Work on LensKit has been funded by the National Science Foundation under
* grants IIS 05-34939, 08-08692, 08-12148, and 10-17697.
*
* 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.1 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU General Public License along with
* this program; if not, write to the Free Software Foundation, Inc., 51
* Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
/**
*
*/
package org.grouplens.lenskit.baseline;
import it.unimi.dsi.fastutil.longs.*;
import org.grouplens.grapht.annotation.DefaultProvider;
import org.grouplens.lenskit.core.Shareable;
import org.grouplens.lenskit.core.Transient;
import org.grouplens.lenskit.cursors.Cursor;
import org.grouplens.lenskit.data.dao.DataAccessObject;
import org.grouplens.lenskit.data.event.Rating;
import org.grouplens.lenskit.data.pref.Preference;
import org.grouplens.lenskit.vectors.MutableSparseVector;
import org.grouplens.lenskit.vectors.VectorEntry;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.inject.Inject;
import javax.inject.Provider;
import java.io.Serializable;
import java.util.Iterator;
import static org.grouplens.lenskit.vectors.VectorEntry.State;
/**
* Rating scorer that returns the item's mean rating for all predictions.
*
* If the item has no ratings, the global mean rating is returned.
*
* This implements the baseline scorer <i>p<sub>u,i</sub> = µ + b<sub>i</sub></i>,
* where <i>b<sub>i</sub></i> is the item's average rating (less the global
* mean µ).
*
* @author <a href="http://www.grouplens.org">GroupLens Research</a>
*/
@DefaultProvider(ItemMeanPredictor.Builder.class)
@Shareable
public class ItemMeanPredictor extends AbstractBaselinePredictor {
/**
* A builder to create ItemMeanPredictors.
*
* @author <a href="http://www.grouplens.org">GroupLens Research</a>
*/
public static class Builder implements Provider<ItemMeanPredictor> {
private double damping = 0;
private DataAccessObject dao;
/**
* Construct a new provider.
*
* @param dao The DAO.
* @param damping The Bayesian mean damping term. It biases means toward the
* global mean.
*/
@Inject
public Builder(@Transient DataAccessObject dao,
@MeanDamping double damping) {
this.dao = dao;
this.damping = damping;
}
@Override
public ItemMeanPredictor get() {
Long2DoubleMap itemMeans = new Long2DoubleOpenHashMap();
Cursor<Rating> ratings = dao.getEvents(Rating.class);
double globalMean;
try {
globalMean = computeItemAverages(ratings.fast().iterator(),
damping, itemMeans);
} finally {
ratings.close();
}
return new ItemMeanPredictor(itemMeans, globalMean, damping);
}
}
private static final long serialVersionUID = 2L;
private static final Logger logger = LoggerFactory.getLogger(ItemMeanPredictor.class);
private final Long2DoubleMap itemMeans; // offsets from the global mean
protected final double globalMean;
protected final double damping;
/**
* Construct a new scorer. This assumes ownership of the provided map.
*
* @param itemMeans A map of item IDs to their mean ratings.
* @param globalMean The mean rating value for all items.
* @param damping The damping factor.
*/
public ItemMeanPredictor(Long2DoubleMap itemMeans, double globalMean, double damping) {
if (itemMeans instanceof Serializable) {
this.itemMeans = itemMeans;
} else {
this.itemMeans = new Long2DoubleOpenHashMap(itemMeans);
}
this.globalMean = globalMean;
this.damping = damping;
}
/**
* Compute item averages from a rating data source. Used in
* predictors that need this data. Note that item averages
* are actually offsets from the global mean.
*
* <p>
* This method's interface is a little weird, using an output parameter and
* returning the global mean, so that we can compute the global mean and the
* item means in a single pass through the data source.
*
* @param ratings The collection of preferences the averages are based on.
* This can be a fast iterator.
* @param itemMeansResult A map in which the means should be stored.
* @param damping The damping term.
* @return The global mean rating. The item means are stored in
* {@var itemMeans}.
*/
public static double computeItemAverages(Iterator<? extends Rating> ratings, double damping,
Long2DoubleMap itemMeansResult) {
// We iterate the loop to compute the global and per-item mean
// ratings. Subtracting the global mean from each per-item mean
// is equivalent to averaging the offsets from the global mean, so
// we can compute the means in parallel and subtract after a single
// pass through the data.
double total = 0.0;
int count = 0;
itemMeansResult.defaultReturnValue(0.0);
Long2IntMap itemCounts = new Long2IntOpenHashMap();
itemCounts.defaultReturnValue(0);
while (ratings.hasNext()) {
Preference r = ratings.next().getPreference();
if (r == null) {
continue; // skip unrates
}
long i = r.getItemId();
double v = r.getValue();
total += v;
count++;
itemMeansResult.put(i, v + itemMeansResult.get(i));
itemCounts.put(i, 1 + itemCounts.get(i));
}
final double mean = count > 0 ? total / count : 0;
logger.debug("Computed global mean {} for {} items",
mean, itemMeansResult.size());
logger.debug("Computing item means, damping={}", damping);
LongIterator items = itemCounts.keySet().iterator();
while (items.hasNext()) {
long iid = items.nextLong();
- double ct = itemCounts.get(iid) + damping;
- // add damping, subtract means to get offsets
- double t = itemMeansResult.get(iid) + (damping - itemCounts.get(iid)) * mean;
+ // the number of ratings for this item
+ final int n = itemCounts.get(iid);
+ // compute the total offset - subtract n means from total
+ final double t = itemMeansResult.get(iid) - n * mean;
+ // we pretend there are damping additional ratings with no offset
+ final double ct = n + damping;
+ // average goes to 0 if there are no ratings (shouldn't happen, b/c how did we get the item?)
double avg = 0.0;
if (ct > 0) {
avg = t / ct;
}
itemMeansResult.put(iid, avg);
}
return mean;
}
@Override
public void predict(long user, MutableSparseVector items, boolean predictSet) {
State state = predictSet ? State.EITHER : State.UNSET;
for (VectorEntry e : items.fast(state)) {
items.set(e, getItemMean(e.getKey()));
}
}
@Override
public String toString() {
String cls = getClass().getSimpleName();
return String.format("%s(µ=%.3f, γ=%.2f)", cls, globalMean, damping);
}
/**
* Get the mean for a particular item.
*
* @param id The item ID.
* @return The item's mean rating.
*/
protected double getItemMean(long id) {
return globalMean + itemMeans.get(id);
}
}
| true | true | public static double computeItemAverages(Iterator<? extends Rating> ratings, double damping,
Long2DoubleMap itemMeansResult) {
// We iterate the loop to compute the global and per-item mean
// ratings. Subtracting the global mean from each per-item mean
// is equivalent to averaging the offsets from the global mean, so
// we can compute the means in parallel and subtract after a single
// pass through the data.
double total = 0.0;
int count = 0;
itemMeansResult.defaultReturnValue(0.0);
Long2IntMap itemCounts = new Long2IntOpenHashMap();
itemCounts.defaultReturnValue(0);
while (ratings.hasNext()) {
Preference r = ratings.next().getPreference();
if (r == null) {
continue; // skip unrates
}
long i = r.getItemId();
double v = r.getValue();
total += v;
count++;
itemMeansResult.put(i, v + itemMeansResult.get(i));
itemCounts.put(i, 1 + itemCounts.get(i));
}
final double mean = count > 0 ? total / count : 0;
logger.debug("Computed global mean {} for {} items",
mean, itemMeansResult.size());
logger.debug("Computing item means, damping={}", damping);
LongIterator items = itemCounts.keySet().iterator();
while (items.hasNext()) {
long iid = items.nextLong();
double ct = itemCounts.get(iid) + damping;
// add damping, subtract means to get offsets
double t = itemMeansResult.get(iid) + (damping - itemCounts.get(iid)) * mean;
double avg = 0.0;
if (ct > 0) {
avg = t / ct;
}
itemMeansResult.put(iid, avg);
}
return mean;
}
| public static double computeItemAverages(Iterator<? extends Rating> ratings, double damping,
Long2DoubleMap itemMeansResult) {
// We iterate the loop to compute the global and per-item mean
// ratings. Subtracting the global mean from each per-item mean
// is equivalent to averaging the offsets from the global mean, so
// we can compute the means in parallel and subtract after a single
// pass through the data.
double total = 0.0;
int count = 0;
itemMeansResult.defaultReturnValue(0.0);
Long2IntMap itemCounts = new Long2IntOpenHashMap();
itemCounts.defaultReturnValue(0);
while (ratings.hasNext()) {
Preference r = ratings.next().getPreference();
if (r == null) {
continue; // skip unrates
}
long i = r.getItemId();
double v = r.getValue();
total += v;
count++;
itemMeansResult.put(i, v + itemMeansResult.get(i));
itemCounts.put(i, 1 + itemCounts.get(i));
}
final double mean = count > 0 ? total / count : 0;
logger.debug("Computed global mean {} for {} items",
mean, itemMeansResult.size());
logger.debug("Computing item means, damping={}", damping);
LongIterator items = itemCounts.keySet().iterator();
while (items.hasNext()) {
long iid = items.nextLong();
// the number of ratings for this item
final int n = itemCounts.get(iid);
// compute the total offset - subtract n means from total
final double t = itemMeansResult.get(iid) - n * mean;
// we pretend there are damping additional ratings with no offset
final double ct = n + damping;
// average goes to 0 if there are no ratings (shouldn't happen, b/c how did we get the item?)
double avg = 0.0;
if (ct > 0) {
avg = t / ct;
}
itemMeansResult.put(iid, avg);
}
return mean;
}
|
diff --git a/branches/DBCP_1_5_x_BRANCH/src/main/java/org/apache/commons/dbcp/managed/LocalXAConnectionFactory.java b/branches/DBCP_1_5_x_BRANCH/src/main/java/org/apache/commons/dbcp/managed/LocalXAConnectionFactory.java
index b8ed0e8..a68996a 100644
--- a/branches/DBCP_1_5_x_BRANCH/src/main/java/org/apache/commons/dbcp/managed/LocalXAConnectionFactory.java
+++ b/branches/DBCP_1_5_x_BRANCH/src/main/java/org/apache/commons/dbcp/managed/LocalXAConnectionFactory.java
@@ -1,298 +1,298 @@
/**
*
* 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.dbcp.managed;
import org.apache.commons.dbcp.ConnectionFactory;
import javax.transaction.TransactionManager;
import javax.transaction.xa.XAException;
import javax.transaction.xa.XAResource;
import javax.transaction.xa.Xid;
import java.sql.Connection;
import java.sql.SQLException;
/**
* An implementation of XAConnectionFactory which manages non-XA connections in XA transactions. A non-XA connection
* commits and rolls back as part of the XA transaction, but is not recoverable since the connection does not implement
* the 2-phase protocol.
*
* @author Dain Sundstrom
* @version $Revision$
*/
public class LocalXAConnectionFactory implements XAConnectionFactory {
protected TransactionRegistry transactionRegistry;
protected ConnectionFactory connectionFactory;
/**
* Creates an LocalXAConnectionFactory which uses the specified connection factory to create database
* connections. The connections are enlisted into transactions using the specified transaction manager.
*
* @param transactionManager the transaction manager in which connections will be enlisted
* @param connectionFactory the connection factory from which connections will be retrieved
*/
public LocalXAConnectionFactory(TransactionManager transactionManager, ConnectionFactory connectionFactory) {
if (transactionManager == null) throw new NullPointerException("transactionManager is null");
if (connectionFactory == null) throw new NullPointerException("connectionFactory is null");
this.transactionRegistry = new TransactionRegistry(transactionManager);
this.connectionFactory = connectionFactory;
}
public TransactionRegistry getTransactionRegistry() {
return transactionRegistry;
}
public Connection createConnection() throws SQLException {
// create a new connection
Connection connection = connectionFactory.createConnection();
// create a XAResource to manage the connection during XA transactions
XAResource xaResource = new LocalXAResource(connection);
// register the xa resource for the connection
transactionRegistry.registerConnection(connection, xaResource);
return connection;
}
/**
* LocalXAResource is a fake XAResource for non-XA connections. When a transaction is started
* the connection auto-commit is turned off. When the connection is committed or rolled back,
* the commit or rollback method is called on the connection and then the original auto-commit
* value is restored.
* </p>
* The LocalXAResource also respects the connection read-only setting. If the connection is
* read-only the commit method will not be called, and the prepare method returns the XA_RDONLY.
* </p>
* It is assumed that the wrapper around a managed connection disables the setAutoCommit(),
* commit(), rollback() and setReadOnly() methods while a transaction is in progress.
*/
protected static class LocalXAResource implements XAResource {
private final Connection connection;
private Xid currentXid;
private boolean originalAutoCommit;
public LocalXAResource(Connection localTransaction) {
this.connection = localTransaction;
}
/**
* Gets the current xid of the transaction branch associated with this XAResource.
*
* @return the current xid of the transaction branch associated with this XAResource.
*/
public synchronized Xid getXid() {
return currentXid;
}
/**
* Signals that a the connection has been enrolled in a transaction. This method saves off the
* current auto commit flag, and then disables auto commit. The original auto commit setting is
* restored when the transaction completes.
*
* @param xid the id of the transaction branch for this connection
* @param flag either XAResource.TMNOFLAGS or XAResource.TMRESUME
* @throws XAException if the connection is already enlisted in another transaction, or if auto-commit
* could not be disabled
*/
public synchronized void start(Xid xid, int flag) throws XAException {
if (flag == XAResource.TMNOFLAGS) {
// first time in this transaction
// make sure we aren't already in another tx
if (this.currentXid != null) {
throw new XAException("Already enlisted in another transaction with xid " + xid);
}
// save off the current auto commit flag so it can be restored after the transaction completes
try {
originalAutoCommit = connection.getAutoCommit();
} catch (SQLException ignored) {
// no big deal, just assume it was off
originalAutoCommit = true;
}
// update the auto commit flag
try {
connection.setAutoCommit(false);
} catch (SQLException e) {
throw (XAException) new XAException("Count not turn off auto commit for a XA transaction").initCause(e);
}
this.currentXid = xid;
} else if (flag == XAResource.TMRESUME) {
- if (xid != this.currentXid) {
+ if (!xid.equals(this.currentXid)) {
throw new XAException("Attempting to resume in different transaction: expected " + this.currentXid + ", but was " + xid);
}
} else {
throw new XAException("Unknown start flag " + flag);
}
}
/**
* This method does nothing.
*
* @param xid the id of the transaction branch for this connection
* @param flag ignored
* @throws XAException if the connection is already enlisted in another transaction
*/
public synchronized void end(Xid xid, int flag) throws XAException {
if (xid == null) throw new NullPointerException("xid is null");
if (!this.currentXid.equals(xid)) throw new XAException("Invalid Xid: expected " + this.currentXid + ", but was " + xid);
// This notification tells us that the application server is done using this
// connection for the time being. The connection is still associated with an
// open transaction, so we must still wait for the commit or rollback method
}
/**
* This method does nothing since the LocalXAConnection does not support two-phase-commit. This method
* will return XAResource.XA_RDONLY if the connection isReadOnly(). This assumes that the physical
* connection is wrapped with a proxy that prevents an application from changing the read-only flag
* while enrolled in a transaction.
*
* @param xid the id of the transaction branch for this connection
* @return XAResource.XA_RDONLY if the connection.isReadOnly(); XAResource.XA_OK otherwise
*/
public synchronized int prepare(Xid xid) {
// if the connection is read-only, then the resource is read-only
// NOTE: this assumes that the outer proxy throws an exception when application code
// attempts to set this in a transaction
try {
if (connection.isReadOnly()) {
// update the auto commit flag
connection.setAutoCommit(originalAutoCommit);
// tell the transaction manager we are read only
return XAResource.XA_RDONLY;
}
} catch (SQLException ignored) {
// no big deal
}
// this is a local (one phase) only connection, so we can't prepare
return XAResource.XA_OK;
}
/**
* Commits the transaction and restores the original auto commit setting.
*
* @param xid the id of the transaction branch for this connection
* @param flag ignored
* @throws XAException if connection.commit() throws a SQLException
*/
public synchronized void commit(Xid xid, boolean flag) throws XAException {
if (xid == null) throw new NullPointerException("xid is null");
if (!this.currentXid.equals(xid)) throw new XAException("Invalid Xid: expected " + this.currentXid + ", but was " + xid);
try {
// make sure the connection isn't already closed
if (connection.isClosed()) {
throw new XAException("Conection is closed");
}
// A read only connection should not be committed
if (!connection.isReadOnly()) {
connection.commit();
}
} catch (SQLException e) {
throw (XAException) new XAException().initCause(e);
} finally {
try {
connection.setAutoCommit(originalAutoCommit);
} catch (SQLException e) {
}
this.currentXid = null;
}
}
/**
* Rolls back the transaction and restores the original auto commit setting.
*
* @param xid the id of the transaction branch for this connection
* @throws XAException if connection.rollback() throws a SQLException
*/
public synchronized void rollback(Xid xid) throws XAException {
if (xid == null) throw new NullPointerException("xid is null");
if (!this.currentXid.equals(xid)) throw new XAException("Invalid Xid: expected " + this.currentXid + ", but was " + xid);
try {
connection.rollback();
} catch (SQLException e) {
throw (XAException) new XAException().initCause(e);
} finally {
try {
connection.setAutoCommit(originalAutoCommit);
} catch (SQLException e) {
}
this.currentXid = null;
}
}
/**
* Returns true if the specified XAResource == this XAResource.
*
* @param xaResource the XAResource to test
* @return true if the specified XAResource == this XAResource; false otherwise
*/
public boolean isSameRM(XAResource xaResource) {
return this == xaResource;
}
/**
* Clears the currently associated transaction if it is the specified xid.
*
* @param xid the id of the transaction to forget
*/
public synchronized void forget(Xid xid) {
if (xid != null && this.currentXid.equals(xid)) {
this.currentXid = null;
}
}
/**
* Always returns a zero length Xid array. The LocalXAConnectionFactory can not support recovery, so no xids will ever be found.
*
* @param flag ignored since recovery is not supported
* @return always a zero length Xid array.
*/
public Xid[] recover(int flag) {
return new Xid[0];
}
/**
* Always returns 0 since we have no way to set a transaction timeout on a JDBC connection.
*
* @return always 0
*/
public int getTransactionTimeout() {
return 0;
}
/**
* Always returns false since we have no way to set a transaction timeout on a JDBC connection.
*
* @param transactionTimeout ignored since we have no way to set a transaction timeout on a JDBC connection
* @return always false
*/
public boolean setTransactionTimeout(int transactionTimeout) {
return false;
}
}
}
| true | true | public synchronized void start(Xid xid, int flag) throws XAException {
if (flag == XAResource.TMNOFLAGS) {
// first time in this transaction
// make sure we aren't already in another tx
if (this.currentXid != null) {
throw new XAException("Already enlisted in another transaction with xid " + xid);
}
// save off the current auto commit flag so it can be restored after the transaction completes
try {
originalAutoCommit = connection.getAutoCommit();
} catch (SQLException ignored) {
// no big deal, just assume it was off
originalAutoCommit = true;
}
// update the auto commit flag
try {
connection.setAutoCommit(false);
} catch (SQLException e) {
throw (XAException) new XAException("Count not turn off auto commit for a XA transaction").initCause(e);
}
this.currentXid = xid;
} else if (flag == XAResource.TMRESUME) {
if (xid != this.currentXid) {
throw new XAException("Attempting to resume in different transaction: expected " + this.currentXid + ", but was " + xid);
}
} else {
throw new XAException("Unknown start flag " + flag);
}
}
| public synchronized void start(Xid xid, int flag) throws XAException {
if (flag == XAResource.TMNOFLAGS) {
// first time in this transaction
// make sure we aren't already in another tx
if (this.currentXid != null) {
throw new XAException("Already enlisted in another transaction with xid " + xid);
}
// save off the current auto commit flag so it can be restored after the transaction completes
try {
originalAutoCommit = connection.getAutoCommit();
} catch (SQLException ignored) {
// no big deal, just assume it was off
originalAutoCommit = true;
}
// update the auto commit flag
try {
connection.setAutoCommit(false);
} catch (SQLException e) {
throw (XAException) new XAException("Count not turn off auto commit for a XA transaction").initCause(e);
}
this.currentXid = xid;
} else if (flag == XAResource.TMRESUME) {
if (!xid.equals(this.currentXid)) {
throw new XAException("Attempting to resume in different transaction: expected " + this.currentXid + ", but was " + xid);
}
} else {
throw new XAException("Unknown start flag " + flag);
}
}
|
diff --git a/plugins/org.eclipse.birt.report.engine.emitter.config.postscript/src/org/eclipse/birt/report/engine/emitter/config/postscript/PostscriptEmitterDescriptor.java b/plugins/org.eclipse.birt.report.engine.emitter.config.postscript/src/org/eclipse/birt/report/engine/emitter/config/postscript/PostscriptEmitterDescriptor.java
index f261bff5e..5e7f4bfc5 100644
--- a/plugins/org.eclipse.birt.report.engine.emitter.config.postscript/src/org/eclipse/birt/report/engine/emitter/config/postscript/PostscriptEmitterDescriptor.java
+++ b/plugins/org.eclipse.birt.report.engine.emitter.config.postscript/src/org/eclipse/birt/report/engine/emitter/config/postscript/PostscriptEmitterDescriptor.java
@@ -1,338 +1,340 @@
/*******************************************************************************
* Copyright (c) 2008 Actuate Corporation.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.report.engine.emitter.config.postscript;
import java.util.Locale;
import org.eclipse.birt.report.engine.api.IPDFRenderOption;
import org.eclipse.birt.report.engine.api.IPostscriptRenderOption;
import org.eclipse.birt.report.engine.api.IRenderOption;
import org.eclipse.birt.report.engine.api.RenderOption;
import org.eclipse.birt.report.engine.emitter.config.AbstractConfigurableOptionObserver;
import org.eclipse.birt.report.engine.emitter.config.AbstractEmitterDescriptor;
import org.eclipse.birt.report.engine.emitter.config.ConfigurableOption;
import org.eclipse.birt.report.engine.emitter.config.IConfigurableOption;
import org.eclipse.birt.report.engine.emitter.config.IConfigurableOptionObserver;
import org.eclipse.birt.report.engine.emitter.config.IOptionValue;
import org.eclipse.birt.report.engine.emitter.config.OptionValue;
import org.eclipse.birt.report.engine.emitter.config.postscript.i18n.Messages;
import org.eclipse.birt.report.engine.emitter.postscript.PostscriptRenderOption;
/**
* This class is a descriptor of postscript emitter.
*/
public class PostscriptEmitterDescriptor extends AbstractEmitterDescriptor
{
private static final String FONT_SUBSTITUTION = "FontSubstitution";
private static final String BIDI_PROCESSING = "BIDIProcessing";
private static final String TEXT_WRAPPING = "TextWrapping";
private static final String CHART_DPI = "ChartDpi";
private IConfigurableOption[] options;
private Locale locale;
public PostscriptEmitterDescriptor( )
{
initOptions( );
}
public void setLocale( Locale locale )
{
if ( this.locale != locale )
{
this.locale = locale;
initOptions( );
}
}
private void initOptions( )
{
// Initializes the option for BIDIProcessing.
ConfigurableOption bidiProcessing = new ConfigurableOption(
BIDI_PROCESSING );
bidiProcessing
.setDisplayName( getMessage( "OptionDisplayValue.BidiProcessing" ) ); //$NON-NLS-1$
bidiProcessing.setDataType( IConfigurableOption.DataType.BOOLEAN );
bidiProcessing.setDisplayType( IConfigurableOption.DisplayType.CHECKBOX );
bidiProcessing.setDefaultValue( Boolean.TRUE );
bidiProcessing.setToolTip( null );
bidiProcessing
.setDescription( getMessage( "OptionDescription.BidiProcessing" ) ); //$NON-NLS-1$
// Initializes the option for TextWrapping.
ConfigurableOption textWrapping = new ConfigurableOption( TEXT_WRAPPING );
textWrapping
.setDisplayName( getMessage( "OptionDisplayValue.TextWrapping" ) ); //$NON-NLS-1$
textWrapping.setDataType( IConfigurableOption.DataType.BOOLEAN );
textWrapping.setDisplayType( IConfigurableOption.DisplayType.CHECKBOX );
textWrapping.setDefaultValue( Boolean.TRUE );
textWrapping.setToolTip( null );
textWrapping
.setDescription( getMessage( "OptionDescription.TextWrapping" ) ); //$NON-NLS-1$
// Initializes the option for fontSubstitution.
ConfigurableOption fontSubstitution = new ConfigurableOption(
FONT_SUBSTITUTION );
fontSubstitution
.setDisplayName( getMessage( "OptionDisplayValue.FontSubstitution" ) );
fontSubstitution.setDataType( IConfigurableOption.DataType.BOOLEAN );
fontSubstitution
.setDisplayType( IConfigurableOption.DisplayType.CHECKBOX );
fontSubstitution.setDefaultValue( Boolean.TRUE );
fontSubstitution.setToolTip( null );
fontSubstitution
.setDescription( getMessage( "OptionDescription.FontSubstitution" ) ); //$NON-NLS-1$
// Initializes the option for PageOverFlow.
ConfigurableOption pageOverFlow = new ConfigurableOption(
IPDFRenderOption.PAGE_OVERFLOW );
pageOverFlow
.setDisplayName( getMessage( "OptionDisplayValue.PageOverFlow" ) ); //$NON-NLS-1$
pageOverFlow.setDataType( IConfigurableOption.DataType.INTEGER );
pageOverFlow.setDisplayType( IConfigurableOption.DisplayType.COMBO );
pageOverFlow
.setChoices( new OptionValue[]{
new OptionValue(
IPDFRenderOption.CLIP_CONTENT,
getMessage( "OptionDisplayValue.CLIP_CONTENT" ) ), //$NON-NLS-1$
new OptionValue(
IPDFRenderOption.FIT_TO_PAGE_SIZE,
getMessage( "OptionDisplayValue.FIT_TO_PAGE_SIZE" ) ), //$NON-NLS-1$
new OptionValue(
IPDFRenderOption.OUTPUT_TO_MULTIPLE_PAGES,
getMessage( "OptionDisplayValue.OUTPUT_TO_MULTIPLE_PAGES" ) ), //$NON-NLS-1$
new OptionValue(
IPDFRenderOption.ENLARGE_PAGE_SIZE,
getMessage( "OptionDisplayValue.ENLARGE_PAGE_SIZE" ) ) //$NON-NLS-1$
} );
pageOverFlow.setDefaultValue( IPDFRenderOption.CLIP_CONTENT );
pageOverFlow.setToolTip( null );
pageOverFlow
.setDescription( getMessage( "OptionDescription.PageOverFlow" ) ); //$NON-NLS-1$
// Initializes the option for copies.
ConfigurableOption copies = new ConfigurableOption(
PostscriptRenderOption.OPTION_COPIES );
copies.setDisplayName( getMessage( "OptionDisplayValue.Copies" ) ); //$NON-NLS-1$
copies.setDataType( IConfigurableOption.DataType.INTEGER );
copies.setDisplayType( IConfigurableOption.DisplayType.TEXT );
copies.setDefaultValue( 1 );
copies.setToolTip( null );
copies.setDescription( getMessage( "OptionDescription.Copies" ) ); //$NON-NLS-1$
// Initializes the option for collate.
ConfigurableOption collate = new ConfigurableOption(
PostscriptRenderOption.OPTION_COLLATE );
collate.setDisplayName( getMessage( "OptionDisplayValue.Collate" ) ); //$NON-NLS-1$
collate.setDataType( IConfigurableOption.DataType.BOOLEAN );
collate.setDisplayType( IConfigurableOption.DisplayType.CHECKBOX );
collate.setDefaultValue( Boolean.FALSE );
collate.setToolTip( null );
collate.setDescription( getMessage( "OptionDescription.Collate" ) ); //$NON-NLS-1$
// Initializes the option for duplex.
ConfigurableOption duplex = new ConfigurableOption(
PostscriptRenderOption.OPTION_DUPLEX );
duplex.setDisplayName( getMessage( "OptionDisplayValue.Duplex" ) ); //$NON-NLS-1$
duplex.setDataType( IConfigurableOption.DataType.STRING );
duplex.setDisplayType( IConfigurableOption.DisplayType.TEXT );
duplex.setChoices( new OptionValue[]{
+ new OptionValue( IPostscriptRenderOption.DUPLEX_SIMPLEX,
+ getMessage( "OptionDisplayValue.DUPLEX_SIMPLEX" ) ), //$NON-NLS-1$
new OptionValue(
IPostscriptRenderOption.DUPLEX_FLIP_ON_SHORT_EDGE,
getMessage( "OptionDisplayValue.DUPLEX_FLIP_ON_SHORT_EDGE" ) ), //$NON-NLS-1$
new OptionValue(
IPostscriptRenderOption.DUPLEX_FLIP_ON_LONG_EDGE,
getMessage( "OptionDisplayValue.DUPLEX_FLIP_ON_LONG_EDGE" ) ) //$NON-NLS-1$
} );
duplex.setDefaultValue( IPostscriptRenderOption.DUPLEX_SIMPLEX );
duplex.setToolTip( null );
duplex.setDescription( getMessage( "OptionDescription.Duplex" ) ); //$NON-NLS-1$
// Initializes the option for paperSize.
ConfigurableOption paperSize = new ConfigurableOption(
PostscriptRenderOption.OPTION_PAPER_SIZE );
paperSize.setDisplayName( getMessage( "OptionDisplayValue.PaperSize" ) ); //$NON-NLS-1$
paperSize.setDataType( IConfigurableOption.DataType.STRING );
paperSize.setDisplayType( IConfigurableOption.DisplayType.TEXT );
paperSize.setDefaultValue( null );
paperSize.setToolTip( null );
paperSize.setDescription( getMessage( "OptionDescription.PaperSize" ) ); //$NON-NLS-1$
// Initializes the option for paperTray.
ConfigurableOption paperTray = new ConfigurableOption(
PostscriptRenderOption.OPTION_PAPER_TRAY );
paperTray.setDisplayName( getMessage( "OptionDisplayValue.PaperTray" ) ); //$NON-NLS-1$
paperTray.setDataType( IConfigurableOption.DataType.INTEGER );
paperTray.setDisplayType( IConfigurableOption.DisplayType.TEXT );
paperTray.setDefaultValue( null );
paperTray.setToolTip( null );
paperTray.setDescription( getMessage( "OptionDescription.PaperTray" ) ); //$NON-NLS-1$
ConfigurableOption scale = new ConfigurableOption(
PostscriptRenderOption.OPTION_SCALE );
scale.setDisplayName( getMessage( "OptionDisplayValue.Scale" ) ); //$NON-NLS-1$
scale.setDataType( IConfigurableOption.DataType.INTEGER );
scale.setDisplayType( IConfigurableOption.DisplayType.TEXT );
scale.setDefaultValue( 100 );
scale.setToolTip( null );
scale.setDescription( getMessage( "OptionDescription.Scale" ) ); //$NON-NLS-1$
ConfigurableOption resolution = new ConfigurableOption(
PostscriptRenderOption.OPTION_RESOLUTION );
resolution
.setDisplayName( getMessage( "OptionDisplayValue.Resolution" ) ); //$NON-NLS-1$
resolution.setDataType( IConfigurableOption.DataType.STRING );
resolution.setDisplayType( IConfigurableOption.DisplayType.TEXT );
resolution.setDefaultValue( null );
resolution.setToolTip( null );
resolution
.setDescription( getMessage( "OptionDescription.Resolution" ) ); //$NON-NLS-1$
ConfigurableOption color = new ConfigurableOption(
PostscriptRenderOption.OPTION_COLOR );
color.setDisplayName( getMessage( "OptionDisplayValue.Color" ) ); //$NON-NLS-1$
color.setDataType( IConfigurableOption.DataType.BOOLEAN );
color.setDisplayType( IConfigurableOption.DisplayType.CHECKBOX );
color.setDefaultValue( Boolean.TRUE );
color.setToolTip( null );
color.setDescription( getMessage( "OptionDescription.Color" ) ); //$NON-NLS-1$
// Initializes the option for chart DPI.
ConfigurableOption chartDpi = new ConfigurableOption( CHART_DPI );
chartDpi.setDisplayName( getMessage( "OptionDisplayValue.ChartDpi" ) ); //$NON-NLS-1$
chartDpi.setDataType( IConfigurableOption.DataType.INTEGER );
chartDpi
.setDisplayType( IConfigurableOption.DisplayType.TEXT );
chartDpi.setDefaultValue( new Integer( 192 ) );
chartDpi.setToolTip( getMessage( "Tooltip.ChartDpi" ) );
chartDpi.setDescription( getMessage( "OptionDescription.ChartDpi" ) ); //$NON-NLS-1$
// Initializes the option for paperTray.
ConfigurableOption autoPaperSizeSelection = new ConfigurableOption(
PostscriptRenderOption.OPTION_AUTO_PAPER_SIZE_SELECTION );
paperTray
.setDisplayName( getMessage( "OptionDisplayValue.AutoPaperSizeSelection" ) ); //$NON-NLS-1$
paperTray.setDataType( IConfigurableOption.DataType.BOOLEAN );
paperTray.setDisplayType( IConfigurableOption.DisplayType.CHECKBOX );
paperTray.setDefaultValue( true );
paperTray.setToolTip( null );
paperTray
.setDescription( getMessage( "OptionDescription.AutoPaperSizeSelection" ) ); //$NON-NLS-1$
options = new IConfigurableOption[]{bidiProcessing, textWrapping,
fontSubstitution, pageOverFlow, copies, collate, duplex,
paperSize, paperTray, scale, resolution, color, chartDpi,
autoPaperSizeSelection};
}
private String getMessage( String key )
{
return Messages.getString( key, locale );
}
@Override
public IConfigurableOptionObserver createOptionObserver( )
{
return new PostscriptOptionObserver( );
}
/*
* (non-Javadoc)
*
* @seeorg.eclipse.birt.report.engine.emitter.config.IEmitterDescriptor#
* getDescription()
*/
public String getDescription( )
{
return getMessage( "PostscriptEmitter.Description" ); //$NON-NLS-1$
}
/*
* (non-Javadoc)
*
* @seeorg.eclipse.birt.report.engine.emitter.config.IEmitterDescriptor#
* getDisplayName()
*/
public String getDisplayName( )
{
return getMessage( "PostscriptEmitter.DisplayName" ); //$NON-NLS-1$
}
/*
* (non-Javadoc)
*
* @see
* org.eclipse.birt.report.engine.emitter.config.IEmitterDescriptor#getID()
*/
public String getID( )
{
return "org.eclipse.birt.report.engine.emitter.postscript"; //$NON-NLS-1$
}
public String getRenderOptionName( String name )
{
assert name != null;
if ( TEXT_WRAPPING.equals( name ) )
{
return IPDFRenderOption.PDF_TEXT_WRAPPING;
}
if ( BIDI_PROCESSING.equals( name ) )
{
return IPDFRenderOption.PDF_BIDI_PROCESSING;
}
if ( FONT_SUBSTITUTION.equals( name ) )
{
return IPDFRenderOption.PDF_FONT_SUBSTITUTION;
}
if ( CHART_DPI.equals( name ) )
{
return IRenderOption.CHART_DPI;
}
return name;
}
class PostscriptOptionObserver extends AbstractConfigurableOptionObserver
{
@Override
public IConfigurableOption[] getOptions( )
{
return options;
}
@Override
public IRenderOption getPreferredRenderOption( )
{
RenderOption renderOption = new RenderOption( );
renderOption.setEmitterID( getID( ) );
renderOption.setOutputFormat( "postscript" ); //$NON-NLS-1$
if ( values != null && values.length > 0 )
{
for ( IOptionValue optionValue : values )
{
if ( optionValue != null )
{
renderOption.setOption(
getRenderOptionName( optionValue.getName( ) ),
optionValue.getValue( ) );
}
}
}
return renderOption;
}
}
}
| true | true | private void initOptions( )
{
// Initializes the option for BIDIProcessing.
ConfigurableOption bidiProcessing = new ConfigurableOption(
BIDI_PROCESSING );
bidiProcessing
.setDisplayName( getMessage( "OptionDisplayValue.BidiProcessing" ) ); //$NON-NLS-1$
bidiProcessing.setDataType( IConfigurableOption.DataType.BOOLEAN );
bidiProcessing.setDisplayType( IConfigurableOption.DisplayType.CHECKBOX );
bidiProcessing.setDefaultValue( Boolean.TRUE );
bidiProcessing.setToolTip( null );
bidiProcessing
.setDescription( getMessage( "OptionDescription.BidiProcessing" ) ); //$NON-NLS-1$
// Initializes the option for TextWrapping.
ConfigurableOption textWrapping = new ConfigurableOption( TEXT_WRAPPING );
textWrapping
.setDisplayName( getMessage( "OptionDisplayValue.TextWrapping" ) ); //$NON-NLS-1$
textWrapping.setDataType( IConfigurableOption.DataType.BOOLEAN );
textWrapping.setDisplayType( IConfigurableOption.DisplayType.CHECKBOX );
textWrapping.setDefaultValue( Boolean.TRUE );
textWrapping.setToolTip( null );
textWrapping
.setDescription( getMessage( "OptionDescription.TextWrapping" ) ); //$NON-NLS-1$
// Initializes the option for fontSubstitution.
ConfigurableOption fontSubstitution = new ConfigurableOption(
FONT_SUBSTITUTION );
fontSubstitution
.setDisplayName( getMessage( "OptionDisplayValue.FontSubstitution" ) );
fontSubstitution.setDataType( IConfigurableOption.DataType.BOOLEAN );
fontSubstitution
.setDisplayType( IConfigurableOption.DisplayType.CHECKBOX );
fontSubstitution.setDefaultValue( Boolean.TRUE );
fontSubstitution.setToolTip( null );
fontSubstitution
.setDescription( getMessage( "OptionDescription.FontSubstitution" ) ); //$NON-NLS-1$
// Initializes the option for PageOverFlow.
ConfigurableOption pageOverFlow = new ConfigurableOption(
IPDFRenderOption.PAGE_OVERFLOW );
pageOverFlow
.setDisplayName( getMessage( "OptionDisplayValue.PageOverFlow" ) ); //$NON-NLS-1$
pageOverFlow.setDataType( IConfigurableOption.DataType.INTEGER );
pageOverFlow.setDisplayType( IConfigurableOption.DisplayType.COMBO );
pageOverFlow
.setChoices( new OptionValue[]{
new OptionValue(
IPDFRenderOption.CLIP_CONTENT,
getMessage( "OptionDisplayValue.CLIP_CONTENT" ) ), //$NON-NLS-1$
new OptionValue(
IPDFRenderOption.FIT_TO_PAGE_SIZE,
getMessage( "OptionDisplayValue.FIT_TO_PAGE_SIZE" ) ), //$NON-NLS-1$
new OptionValue(
IPDFRenderOption.OUTPUT_TO_MULTIPLE_PAGES,
getMessage( "OptionDisplayValue.OUTPUT_TO_MULTIPLE_PAGES" ) ), //$NON-NLS-1$
new OptionValue(
IPDFRenderOption.ENLARGE_PAGE_SIZE,
getMessage( "OptionDisplayValue.ENLARGE_PAGE_SIZE" ) ) //$NON-NLS-1$
} );
pageOverFlow.setDefaultValue( IPDFRenderOption.CLIP_CONTENT );
pageOverFlow.setToolTip( null );
pageOverFlow
.setDescription( getMessage( "OptionDescription.PageOverFlow" ) ); //$NON-NLS-1$
// Initializes the option for copies.
ConfigurableOption copies = new ConfigurableOption(
PostscriptRenderOption.OPTION_COPIES );
copies.setDisplayName( getMessage( "OptionDisplayValue.Copies" ) ); //$NON-NLS-1$
copies.setDataType( IConfigurableOption.DataType.INTEGER );
copies.setDisplayType( IConfigurableOption.DisplayType.TEXT );
copies.setDefaultValue( 1 );
copies.setToolTip( null );
copies.setDescription( getMessage( "OptionDescription.Copies" ) ); //$NON-NLS-1$
// Initializes the option for collate.
ConfigurableOption collate = new ConfigurableOption(
PostscriptRenderOption.OPTION_COLLATE );
collate.setDisplayName( getMessage( "OptionDisplayValue.Collate" ) ); //$NON-NLS-1$
collate.setDataType( IConfigurableOption.DataType.BOOLEAN );
collate.setDisplayType( IConfigurableOption.DisplayType.CHECKBOX );
collate.setDefaultValue( Boolean.FALSE );
collate.setToolTip( null );
collate.setDescription( getMessage( "OptionDescription.Collate" ) ); //$NON-NLS-1$
// Initializes the option for duplex.
ConfigurableOption duplex = new ConfigurableOption(
PostscriptRenderOption.OPTION_DUPLEX );
duplex.setDisplayName( getMessage( "OptionDisplayValue.Duplex" ) ); //$NON-NLS-1$
duplex.setDataType( IConfigurableOption.DataType.STRING );
duplex.setDisplayType( IConfigurableOption.DisplayType.TEXT );
duplex.setChoices( new OptionValue[]{
new OptionValue(
IPostscriptRenderOption.DUPLEX_FLIP_ON_SHORT_EDGE,
getMessage( "OptionDisplayValue.DUPLEX_FLIP_ON_SHORT_EDGE" ) ), //$NON-NLS-1$
new OptionValue(
IPostscriptRenderOption.DUPLEX_FLIP_ON_LONG_EDGE,
getMessage( "OptionDisplayValue.DUPLEX_FLIP_ON_LONG_EDGE" ) ) //$NON-NLS-1$
} );
duplex.setDefaultValue( IPostscriptRenderOption.DUPLEX_SIMPLEX );
duplex.setToolTip( null );
duplex.setDescription( getMessage( "OptionDescription.Duplex" ) ); //$NON-NLS-1$
// Initializes the option for paperSize.
ConfigurableOption paperSize = new ConfigurableOption(
PostscriptRenderOption.OPTION_PAPER_SIZE );
paperSize.setDisplayName( getMessage( "OptionDisplayValue.PaperSize" ) ); //$NON-NLS-1$
paperSize.setDataType( IConfigurableOption.DataType.STRING );
paperSize.setDisplayType( IConfigurableOption.DisplayType.TEXT );
paperSize.setDefaultValue( null );
paperSize.setToolTip( null );
paperSize.setDescription( getMessage( "OptionDescription.PaperSize" ) ); //$NON-NLS-1$
// Initializes the option for paperTray.
ConfigurableOption paperTray = new ConfigurableOption(
PostscriptRenderOption.OPTION_PAPER_TRAY );
paperTray.setDisplayName( getMessage( "OptionDisplayValue.PaperTray" ) ); //$NON-NLS-1$
paperTray.setDataType( IConfigurableOption.DataType.INTEGER );
paperTray.setDisplayType( IConfigurableOption.DisplayType.TEXT );
paperTray.setDefaultValue( null );
paperTray.setToolTip( null );
paperTray.setDescription( getMessage( "OptionDescription.PaperTray" ) ); //$NON-NLS-1$
ConfigurableOption scale = new ConfigurableOption(
PostscriptRenderOption.OPTION_SCALE );
scale.setDisplayName( getMessage( "OptionDisplayValue.Scale" ) ); //$NON-NLS-1$
scale.setDataType( IConfigurableOption.DataType.INTEGER );
scale.setDisplayType( IConfigurableOption.DisplayType.TEXT );
scale.setDefaultValue( 100 );
scale.setToolTip( null );
scale.setDescription( getMessage( "OptionDescription.Scale" ) ); //$NON-NLS-1$
ConfigurableOption resolution = new ConfigurableOption(
PostscriptRenderOption.OPTION_RESOLUTION );
resolution
.setDisplayName( getMessage( "OptionDisplayValue.Resolution" ) ); //$NON-NLS-1$
resolution.setDataType( IConfigurableOption.DataType.STRING );
resolution.setDisplayType( IConfigurableOption.DisplayType.TEXT );
resolution.setDefaultValue( null );
resolution.setToolTip( null );
resolution
.setDescription( getMessage( "OptionDescription.Resolution" ) ); //$NON-NLS-1$
ConfigurableOption color = new ConfigurableOption(
PostscriptRenderOption.OPTION_COLOR );
color.setDisplayName( getMessage( "OptionDisplayValue.Color" ) ); //$NON-NLS-1$
color.setDataType( IConfigurableOption.DataType.BOOLEAN );
color.setDisplayType( IConfigurableOption.DisplayType.CHECKBOX );
color.setDefaultValue( Boolean.TRUE );
color.setToolTip( null );
color.setDescription( getMessage( "OptionDescription.Color" ) ); //$NON-NLS-1$
// Initializes the option for chart DPI.
ConfigurableOption chartDpi = new ConfigurableOption( CHART_DPI );
chartDpi.setDisplayName( getMessage( "OptionDisplayValue.ChartDpi" ) ); //$NON-NLS-1$
chartDpi.setDataType( IConfigurableOption.DataType.INTEGER );
chartDpi
.setDisplayType( IConfigurableOption.DisplayType.TEXT );
chartDpi.setDefaultValue( new Integer( 192 ) );
chartDpi.setToolTip( getMessage( "Tooltip.ChartDpi" ) );
chartDpi.setDescription( getMessage( "OptionDescription.ChartDpi" ) ); //$NON-NLS-1$
// Initializes the option for paperTray.
ConfigurableOption autoPaperSizeSelection = new ConfigurableOption(
PostscriptRenderOption.OPTION_AUTO_PAPER_SIZE_SELECTION );
paperTray
.setDisplayName( getMessage( "OptionDisplayValue.AutoPaperSizeSelection" ) ); //$NON-NLS-1$
paperTray.setDataType( IConfigurableOption.DataType.BOOLEAN );
paperTray.setDisplayType( IConfigurableOption.DisplayType.CHECKBOX );
paperTray.setDefaultValue( true );
paperTray.setToolTip( null );
paperTray
.setDescription( getMessage( "OptionDescription.AutoPaperSizeSelection" ) ); //$NON-NLS-1$
options = new IConfigurableOption[]{bidiProcessing, textWrapping,
fontSubstitution, pageOverFlow, copies, collate, duplex,
paperSize, paperTray, scale, resolution, color, chartDpi,
autoPaperSizeSelection};
}
| private void initOptions( )
{
// Initializes the option for BIDIProcessing.
ConfigurableOption bidiProcessing = new ConfigurableOption(
BIDI_PROCESSING );
bidiProcessing
.setDisplayName( getMessage( "OptionDisplayValue.BidiProcessing" ) ); //$NON-NLS-1$
bidiProcessing.setDataType( IConfigurableOption.DataType.BOOLEAN );
bidiProcessing.setDisplayType( IConfigurableOption.DisplayType.CHECKBOX );
bidiProcessing.setDefaultValue( Boolean.TRUE );
bidiProcessing.setToolTip( null );
bidiProcessing
.setDescription( getMessage( "OptionDescription.BidiProcessing" ) ); //$NON-NLS-1$
// Initializes the option for TextWrapping.
ConfigurableOption textWrapping = new ConfigurableOption( TEXT_WRAPPING );
textWrapping
.setDisplayName( getMessage( "OptionDisplayValue.TextWrapping" ) ); //$NON-NLS-1$
textWrapping.setDataType( IConfigurableOption.DataType.BOOLEAN );
textWrapping.setDisplayType( IConfigurableOption.DisplayType.CHECKBOX );
textWrapping.setDefaultValue( Boolean.TRUE );
textWrapping.setToolTip( null );
textWrapping
.setDescription( getMessage( "OptionDescription.TextWrapping" ) ); //$NON-NLS-1$
// Initializes the option for fontSubstitution.
ConfigurableOption fontSubstitution = new ConfigurableOption(
FONT_SUBSTITUTION );
fontSubstitution
.setDisplayName( getMessage( "OptionDisplayValue.FontSubstitution" ) );
fontSubstitution.setDataType( IConfigurableOption.DataType.BOOLEAN );
fontSubstitution
.setDisplayType( IConfigurableOption.DisplayType.CHECKBOX );
fontSubstitution.setDefaultValue( Boolean.TRUE );
fontSubstitution.setToolTip( null );
fontSubstitution
.setDescription( getMessage( "OptionDescription.FontSubstitution" ) ); //$NON-NLS-1$
// Initializes the option for PageOverFlow.
ConfigurableOption pageOverFlow = new ConfigurableOption(
IPDFRenderOption.PAGE_OVERFLOW );
pageOverFlow
.setDisplayName( getMessage( "OptionDisplayValue.PageOverFlow" ) ); //$NON-NLS-1$
pageOverFlow.setDataType( IConfigurableOption.DataType.INTEGER );
pageOverFlow.setDisplayType( IConfigurableOption.DisplayType.COMBO );
pageOverFlow
.setChoices( new OptionValue[]{
new OptionValue(
IPDFRenderOption.CLIP_CONTENT,
getMessage( "OptionDisplayValue.CLIP_CONTENT" ) ), //$NON-NLS-1$
new OptionValue(
IPDFRenderOption.FIT_TO_PAGE_SIZE,
getMessage( "OptionDisplayValue.FIT_TO_PAGE_SIZE" ) ), //$NON-NLS-1$
new OptionValue(
IPDFRenderOption.OUTPUT_TO_MULTIPLE_PAGES,
getMessage( "OptionDisplayValue.OUTPUT_TO_MULTIPLE_PAGES" ) ), //$NON-NLS-1$
new OptionValue(
IPDFRenderOption.ENLARGE_PAGE_SIZE,
getMessage( "OptionDisplayValue.ENLARGE_PAGE_SIZE" ) ) //$NON-NLS-1$
} );
pageOverFlow.setDefaultValue( IPDFRenderOption.CLIP_CONTENT );
pageOverFlow.setToolTip( null );
pageOverFlow
.setDescription( getMessage( "OptionDescription.PageOverFlow" ) ); //$NON-NLS-1$
// Initializes the option for copies.
ConfigurableOption copies = new ConfigurableOption(
PostscriptRenderOption.OPTION_COPIES );
copies.setDisplayName( getMessage( "OptionDisplayValue.Copies" ) ); //$NON-NLS-1$
copies.setDataType( IConfigurableOption.DataType.INTEGER );
copies.setDisplayType( IConfigurableOption.DisplayType.TEXT );
copies.setDefaultValue( 1 );
copies.setToolTip( null );
copies.setDescription( getMessage( "OptionDescription.Copies" ) ); //$NON-NLS-1$
// Initializes the option for collate.
ConfigurableOption collate = new ConfigurableOption(
PostscriptRenderOption.OPTION_COLLATE );
collate.setDisplayName( getMessage( "OptionDisplayValue.Collate" ) ); //$NON-NLS-1$
collate.setDataType( IConfigurableOption.DataType.BOOLEAN );
collate.setDisplayType( IConfigurableOption.DisplayType.CHECKBOX );
collate.setDefaultValue( Boolean.FALSE );
collate.setToolTip( null );
collate.setDescription( getMessage( "OptionDescription.Collate" ) ); //$NON-NLS-1$
// Initializes the option for duplex.
ConfigurableOption duplex = new ConfigurableOption(
PostscriptRenderOption.OPTION_DUPLEX );
duplex.setDisplayName( getMessage( "OptionDisplayValue.Duplex" ) ); //$NON-NLS-1$
duplex.setDataType( IConfigurableOption.DataType.STRING );
duplex.setDisplayType( IConfigurableOption.DisplayType.TEXT );
duplex.setChoices( new OptionValue[]{
new OptionValue( IPostscriptRenderOption.DUPLEX_SIMPLEX,
getMessage( "OptionDisplayValue.DUPLEX_SIMPLEX" ) ), //$NON-NLS-1$
new OptionValue(
IPostscriptRenderOption.DUPLEX_FLIP_ON_SHORT_EDGE,
getMessage( "OptionDisplayValue.DUPLEX_FLIP_ON_SHORT_EDGE" ) ), //$NON-NLS-1$
new OptionValue(
IPostscriptRenderOption.DUPLEX_FLIP_ON_LONG_EDGE,
getMessage( "OptionDisplayValue.DUPLEX_FLIP_ON_LONG_EDGE" ) ) //$NON-NLS-1$
} );
duplex.setDefaultValue( IPostscriptRenderOption.DUPLEX_SIMPLEX );
duplex.setToolTip( null );
duplex.setDescription( getMessage( "OptionDescription.Duplex" ) ); //$NON-NLS-1$
// Initializes the option for paperSize.
ConfigurableOption paperSize = new ConfigurableOption(
PostscriptRenderOption.OPTION_PAPER_SIZE );
paperSize.setDisplayName( getMessage( "OptionDisplayValue.PaperSize" ) ); //$NON-NLS-1$
paperSize.setDataType( IConfigurableOption.DataType.STRING );
paperSize.setDisplayType( IConfigurableOption.DisplayType.TEXT );
paperSize.setDefaultValue( null );
paperSize.setToolTip( null );
paperSize.setDescription( getMessage( "OptionDescription.PaperSize" ) ); //$NON-NLS-1$
// Initializes the option for paperTray.
ConfigurableOption paperTray = new ConfigurableOption(
PostscriptRenderOption.OPTION_PAPER_TRAY );
paperTray.setDisplayName( getMessage( "OptionDisplayValue.PaperTray" ) ); //$NON-NLS-1$
paperTray.setDataType( IConfigurableOption.DataType.INTEGER );
paperTray.setDisplayType( IConfigurableOption.DisplayType.TEXT );
paperTray.setDefaultValue( null );
paperTray.setToolTip( null );
paperTray.setDescription( getMessage( "OptionDescription.PaperTray" ) ); //$NON-NLS-1$
ConfigurableOption scale = new ConfigurableOption(
PostscriptRenderOption.OPTION_SCALE );
scale.setDisplayName( getMessage( "OptionDisplayValue.Scale" ) ); //$NON-NLS-1$
scale.setDataType( IConfigurableOption.DataType.INTEGER );
scale.setDisplayType( IConfigurableOption.DisplayType.TEXT );
scale.setDefaultValue( 100 );
scale.setToolTip( null );
scale.setDescription( getMessage( "OptionDescription.Scale" ) ); //$NON-NLS-1$
ConfigurableOption resolution = new ConfigurableOption(
PostscriptRenderOption.OPTION_RESOLUTION );
resolution
.setDisplayName( getMessage( "OptionDisplayValue.Resolution" ) ); //$NON-NLS-1$
resolution.setDataType( IConfigurableOption.DataType.STRING );
resolution.setDisplayType( IConfigurableOption.DisplayType.TEXT );
resolution.setDefaultValue( null );
resolution.setToolTip( null );
resolution
.setDescription( getMessage( "OptionDescription.Resolution" ) ); //$NON-NLS-1$
ConfigurableOption color = new ConfigurableOption(
PostscriptRenderOption.OPTION_COLOR );
color.setDisplayName( getMessage( "OptionDisplayValue.Color" ) ); //$NON-NLS-1$
color.setDataType( IConfigurableOption.DataType.BOOLEAN );
color.setDisplayType( IConfigurableOption.DisplayType.CHECKBOX );
color.setDefaultValue( Boolean.TRUE );
color.setToolTip( null );
color.setDescription( getMessage( "OptionDescription.Color" ) ); //$NON-NLS-1$
// Initializes the option for chart DPI.
ConfigurableOption chartDpi = new ConfigurableOption( CHART_DPI );
chartDpi.setDisplayName( getMessage( "OptionDisplayValue.ChartDpi" ) ); //$NON-NLS-1$
chartDpi.setDataType( IConfigurableOption.DataType.INTEGER );
chartDpi
.setDisplayType( IConfigurableOption.DisplayType.TEXT );
chartDpi.setDefaultValue( new Integer( 192 ) );
chartDpi.setToolTip( getMessage( "Tooltip.ChartDpi" ) );
chartDpi.setDescription( getMessage( "OptionDescription.ChartDpi" ) ); //$NON-NLS-1$
// Initializes the option for paperTray.
ConfigurableOption autoPaperSizeSelection = new ConfigurableOption(
PostscriptRenderOption.OPTION_AUTO_PAPER_SIZE_SELECTION );
paperTray
.setDisplayName( getMessage( "OptionDisplayValue.AutoPaperSizeSelection" ) ); //$NON-NLS-1$
paperTray.setDataType( IConfigurableOption.DataType.BOOLEAN );
paperTray.setDisplayType( IConfigurableOption.DisplayType.CHECKBOX );
paperTray.setDefaultValue( true );
paperTray.setToolTip( null );
paperTray
.setDescription( getMessage( "OptionDescription.AutoPaperSizeSelection" ) ); //$NON-NLS-1$
options = new IConfigurableOption[]{bidiProcessing, textWrapping,
fontSubstitution, pageOverFlow, copies, collate, duplex,
paperSize, paperTray, scale, resolution, color, chartDpi,
autoPaperSizeSelection};
}
|
diff --git a/src/main/java/me/limebyte/battlenight/core/commands/ArenasCommand.java b/src/main/java/me/limebyte/battlenight/core/commands/ArenasCommand.java
index e541ff5..096a701 100644
--- a/src/main/java/me/limebyte/battlenight/core/commands/ArenasCommand.java
+++ b/src/main/java/me/limebyte/battlenight/core/commands/ArenasCommand.java
@@ -1,201 +1,201 @@
package me.limebyte.battlenight.core.commands;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import me.limebyte.battlenight.api.battle.Arena;
import me.limebyte.battlenight.api.battle.Waypoint;
import me.limebyte.battlenight.api.managers.ArenaManager;
import me.limebyte.battlenight.api.util.BattleNightCommand;
import me.limebyte.battlenight.api.util.ListPage;
import me.limebyte.battlenight.core.util.Messenger;
import me.limebyte.battlenight.core.util.Messenger.Message;
import org.bukkit.ChatColor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
public class ArenasCommand extends BattleNightCommand {
public ArenasCommand() {
super("Arenas");
setLabel("arenas");
setDescription("Displays the BattleNight arenas.");
setUsage("/bn arenas <action> [arena]");
setPermission(CommandPermission.ADMIN);
}
@Override
protected boolean onPerformed(CommandSender sender, String[] args) {
ArenaManager manager = api.getArenaManager();
List<Arena> arenas = manager.getArenas();
if (args.length < 1) {
sendArenasList(sender, arenas);
return true;
}
if (args[0].equalsIgnoreCase("list")) {
sendArenasList(sender, arenas);
return true;
}
if (args[0].equalsIgnoreCase("create")) {
if (args.length < 2) {
Messenger.tell(sender, Message.SPECIFY_ARENA);
return false;
}
for (Arena arena : arenas) {
if (arena.getName().equalsIgnoreCase(args[1])) {
Messenger.tell(sender, Message.ARENA_EXISTS);
return false;
}
}
manager.register(new Arena(args[1]));
Messenger.tell(sender, Message.ARENA_CREATED, args[1]);
return false;
}
if (args[0].equalsIgnoreCase("delete")) {
if (args.length < 2) {
Messenger.tell(sender, Message.SPECIFY_ARENA);
return false;
}
Iterator<Arena> it = arenas.iterator();
while (it.hasNext()) {
Arena arena = it.next();
if (arena.getName().equalsIgnoreCase(args[1])) {
it.remove();
Messenger.tell(sender, Message.ARENA_DELETED, args[1]);
return true;
}
}
return false;
}
if (args[0].equalsIgnoreCase("addspawn")) {
if (args.length < 2) {
Messenger.tell(sender, Message.SPECIFY_ARENA);
return false;
}
Arena arena = null;
for (Arena a : arenas) {
- if (a.getName().equalsIgnoreCase(args[0])) {
+ if (a.getName().equalsIgnoreCase(args[1])) {
arena = a;
}
}
if (arena == null) {
Messenger.tell(sender, "An Arena by that name does not exist!");
return false;
}
Waypoint point = new Waypoint();
point.setLocation(((Player) sender).getLocation());
arena.addSpawnPoint(point);
Messenger.tell(sender, "Spawn point created.");
return true;
}
if (args[0].equalsIgnoreCase("enable")) {
if (args.length < 2) {
Messenger.tell(sender, Message.SPECIFY_ARENA);
return false;
}
for (Arena arena : arenas) {
if (arena.getName().equalsIgnoreCase(args[1])) {
arena.enable();
return true;
}
}
return false;
}
if (args[0].equalsIgnoreCase("disable")) {
if (args.length < 2) {
Messenger.tell(sender, Message.SPECIFY_ARENA);
return false;
}
for (Arena arena : arenas) {
if (arena.getName().equalsIgnoreCase(args[1])) {
arena.disable();
return true;
}
}
return false;
}
if (args[0].equalsIgnoreCase("name")) {
if (args.length < 3) {
Messenger.tell(sender, Message.SPECIFY_ARENA);
return false;
}
for (Arena arena : arenas) {
if (arena.getName().equalsIgnoreCase(args[1])) {
arena.setDisplayName(createString(args, 2));
return true;
}
}
return false;
}
if (args[0].equalsIgnoreCase("texturepack")) {
if (args.length < 3) {
Messenger.tell(sender, Message.SPECIFY_ARENA);
return false;
}
for (Arena arena : arenas) {
if (arena.getName().equalsIgnoreCase(args[1])) {
arena.setTexturePack(args[2]);
return true;
}
}
return false;
}
Messenger.tell(sender, Message.INVALID_COMMAND);
Messenger.tell(sender, Message.USAGE, getUsage());
return false;
}
private void sendArenasList(CommandSender sender, List<Arena> arenas) {
List<String> lines = new ArrayList<String>();
lines.add(ChatColor.WHITE + "Setup Arenas: " + numSetup(arenas));
for (Arena arena : arenas) {
lines.add(getArenaName(arena) + ChatColor.WHITE + " (" + arena.getSpawnPoints().size() + " Spawns)");
}
Messenger.tell(sender, new ListPage("BattleNight Arenas", lines));
}
private String getArenaName(Arena arena) {
ChatColor colour = arena.isEnabled() ? ChatColor.GREEN : ChatColor.RED;
return colour + arena.getDisplayName() + " (" + arena.getName() + ")";
}
private String numSetup(List<Arena> arenas) {
int num = 0;
int setup = 0;
for (Arena a : arenas) {
if (a == null) continue;
num++;
if (a.isSetup(2)) setup++;
}
return setup + "/" + num;
}
}
| true | true | protected boolean onPerformed(CommandSender sender, String[] args) {
ArenaManager manager = api.getArenaManager();
List<Arena> arenas = manager.getArenas();
if (args.length < 1) {
sendArenasList(sender, arenas);
return true;
}
if (args[0].equalsIgnoreCase("list")) {
sendArenasList(sender, arenas);
return true;
}
if (args[0].equalsIgnoreCase("create")) {
if (args.length < 2) {
Messenger.tell(sender, Message.SPECIFY_ARENA);
return false;
}
for (Arena arena : arenas) {
if (arena.getName().equalsIgnoreCase(args[1])) {
Messenger.tell(sender, Message.ARENA_EXISTS);
return false;
}
}
manager.register(new Arena(args[1]));
Messenger.tell(sender, Message.ARENA_CREATED, args[1]);
return false;
}
if (args[0].equalsIgnoreCase("delete")) {
if (args.length < 2) {
Messenger.tell(sender, Message.SPECIFY_ARENA);
return false;
}
Iterator<Arena> it = arenas.iterator();
while (it.hasNext()) {
Arena arena = it.next();
if (arena.getName().equalsIgnoreCase(args[1])) {
it.remove();
Messenger.tell(sender, Message.ARENA_DELETED, args[1]);
return true;
}
}
return false;
}
if (args[0].equalsIgnoreCase("addspawn")) {
if (args.length < 2) {
Messenger.tell(sender, Message.SPECIFY_ARENA);
return false;
}
Arena arena = null;
for (Arena a : arenas) {
if (a.getName().equalsIgnoreCase(args[0])) {
arena = a;
}
}
if (arena == null) {
Messenger.tell(sender, "An Arena by that name does not exist!");
return false;
}
Waypoint point = new Waypoint();
point.setLocation(((Player) sender).getLocation());
arena.addSpawnPoint(point);
Messenger.tell(sender, "Spawn point created.");
return true;
}
if (args[0].equalsIgnoreCase("enable")) {
if (args.length < 2) {
Messenger.tell(sender, Message.SPECIFY_ARENA);
return false;
}
for (Arena arena : arenas) {
if (arena.getName().equalsIgnoreCase(args[1])) {
arena.enable();
return true;
}
}
return false;
}
if (args[0].equalsIgnoreCase("disable")) {
if (args.length < 2) {
Messenger.tell(sender, Message.SPECIFY_ARENA);
return false;
}
for (Arena arena : arenas) {
if (arena.getName().equalsIgnoreCase(args[1])) {
arena.disable();
return true;
}
}
return false;
}
if (args[0].equalsIgnoreCase("name")) {
if (args.length < 3) {
Messenger.tell(sender, Message.SPECIFY_ARENA);
return false;
}
for (Arena arena : arenas) {
if (arena.getName().equalsIgnoreCase(args[1])) {
arena.setDisplayName(createString(args, 2));
return true;
}
}
return false;
}
if (args[0].equalsIgnoreCase("texturepack")) {
if (args.length < 3) {
Messenger.tell(sender, Message.SPECIFY_ARENA);
return false;
}
for (Arena arena : arenas) {
if (arena.getName().equalsIgnoreCase(args[1])) {
arena.setTexturePack(args[2]);
return true;
}
}
return false;
}
Messenger.tell(sender, Message.INVALID_COMMAND);
Messenger.tell(sender, Message.USAGE, getUsage());
return false;
}
| protected boolean onPerformed(CommandSender sender, String[] args) {
ArenaManager manager = api.getArenaManager();
List<Arena> arenas = manager.getArenas();
if (args.length < 1) {
sendArenasList(sender, arenas);
return true;
}
if (args[0].equalsIgnoreCase("list")) {
sendArenasList(sender, arenas);
return true;
}
if (args[0].equalsIgnoreCase("create")) {
if (args.length < 2) {
Messenger.tell(sender, Message.SPECIFY_ARENA);
return false;
}
for (Arena arena : arenas) {
if (arena.getName().equalsIgnoreCase(args[1])) {
Messenger.tell(sender, Message.ARENA_EXISTS);
return false;
}
}
manager.register(new Arena(args[1]));
Messenger.tell(sender, Message.ARENA_CREATED, args[1]);
return false;
}
if (args[0].equalsIgnoreCase("delete")) {
if (args.length < 2) {
Messenger.tell(sender, Message.SPECIFY_ARENA);
return false;
}
Iterator<Arena> it = arenas.iterator();
while (it.hasNext()) {
Arena arena = it.next();
if (arena.getName().equalsIgnoreCase(args[1])) {
it.remove();
Messenger.tell(sender, Message.ARENA_DELETED, args[1]);
return true;
}
}
return false;
}
if (args[0].equalsIgnoreCase("addspawn")) {
if (args.length < 2) {
Messenger.tell(sender, Message.SPECIFY_ARENA);
return false;
}
Arena arena = null;
for (Arena a : arenas) {
if (a.getName().equalsIgnoreCase(args[1])) {
arena = a;
}
}
if (arena == null) {
Messenger.tell(sender, "An Arena by that name does not exist!");
return false;
}
Waypoint point = new Waypoint();
point.setLocation(((Player) sender).getLocation());
arena.addSpawnPoint(point);
Messenger.tell(sender, "Spawn point created.");
return true;
}
if (args[0].equalsIgnoreCase("enable")) {
if (args.length < 2) {
Messenger.tell(sender, Message.SPECIFY_ARENA);
return false;
}
for (Arena arena : arenas) {
if (arena.getName().equalsIgnoreCase(args[1])) {
arena.enable();
return true;
}
}
return false;
}
if (args[0].equalsIgnoreCase("disable")) {
if (args.length < 2) {
Messenger.tell(sender, Message.SPECIFY_ARENA);
return false;
}
for (Arena arena : arenas) {
if (arena.getName().equalsIgnoreCase(args[1])) {
arena.disable();
return true;
}
}
return false;
}
if (args[0].equalsIgnoreCase("name")) {
if (args.length < 3) {
Messenger.tell(sender, Message.SPECIFY_ARENA);
return false;
}
for (Arena arena : arenas) {
if (arena.getName().equalsIgnoreCase(args[1])) {
arena.setDisplayName(createString(args, 2));
return true;
}
}
return false;
}
if (args[0].equalsIgnoreCase("texturepack")) {
if (args.length < 3) {
Messenger.tell(sender, Message.SPECIFY_ARENA);
return false;
}
for (Arena arena : arenas) {
if (arena.getName().equalsIgnoreCase(args[1])) {
arena.setTexturePack(args[2]);
return true;
}
}
return false;
}
Messenger.tell(sender, Message.INVALID_COMMAND);
Messenger.tell(sender, Message.USAGE, getUsage());
return false;
}
|
diff --git a/ChoreographyDeployer/src/main/java/org/ow2/choreos/chors/context/SoapContextSender.java b/ChoreographyDeployer/src/main/java/org/ow2/choreos/chors/context/SoapContextSender.java
index 49b11a70..46dbee9d 100644
--- a/ChoreographyDeployer/src/main/java/org/ow2/choreos/chors/context/SoapContextSender.java
+++ b/ChoreographyDeployer/src/main/java/org/ow2/choreos/chors/context/SoapContextSender.java
@@ -1,159 +1,159 @@
package org.ow2.choreos.chors.context;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.List;
import javax.xml.namespace.QName;
import javax.xml.soap.MessageFactory;
import javax.xml.soap.SOAPBody;
import javax.xml.soap.SOAPBodyElement;
import javax.xml.soap.SOAPConnection;
import javax.xml.soap.SOAPConnectionFactory;
import javax.xml.soap.SOAPElement;
import javax.xml.soap.SOAPEnvelope;
import javax.xml.soap.SOAPException;
import javax.xml.soap.SOAPHeader;
import javax.xml.soap.SOAPMessage;
import javax.xml.stream.XMLEventReader;
import javax.xml.stream.XMLInputFactory;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.events.StartElement;
import javax.xml.stream.events.XMLEvent;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Source;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.stream.StreamResult;
public class SoapContextSender implements ContextSender {
private String parseNamespace(final String endpoint)
throws XMLStreamException, IOException {
final String wsdl = getWsdl(endpoint);
final URL url = new URL(wsdl);
final InputStreamReader streamReader = new InputStreamReader(
url.openStream());
final BufferedReader wsdlInputStream = new BufferedReader(streamReader);
final XMLInputFactory xmlInputFactory = XMLInputFactory.newInstance();
final XMLEventReader reader = xmlInputFactory
.createXMLEventReader(wsdlInputStream);
String elementName, namespace = "";
XMLEvent event;
StartElement element;
while (reader.hasNext()) {
event = reader.nextEvent();
if (event.isStartElement()) {
element = event.asStartElement();
elementName = element.getName().getLocalPart();
if ("definitions".equals(elementName)) {
final QName qname = new QName("targetNamespace"); // NOPMD
namespace = element.getAttributeByName(qname).getValue();
break;
}
}
}
reader.close();
return namespace;
}
private String getWsdl(final String endpoint) {
String slashLess;
if (endpoint.endsWith("/")) {
slashLess = endpoint.substring(0, endpoint.length() - 1);
} else {
slashLess = endpoint;
}
return slashLess + "?wsdl";
}
@Override
public void sendContext(String serviceEndpoint, String partnerRole, String partnerName,
List<String> partnerEndpoints) throws ContextNotSentException {
try {
SOAPConnectionFactory sfc = SOAPConnectionFactory.newInstance();
SOAPConnection connection = sfc.createConnection();
MessageFactory mf = MessageFactory.newInstance();
SOAPMessage sm = mf.createMessage();
SOAPEnvelope envelope = sm.getSOAPPart().getEnvelope();
String namespace = parseNamespace(serviceEndpoint);
envelope.addNamespaceDeclaration("pre", namespace);
SOAPHeader sh = sm.getSOAPHeader();
SOAPBody sb = sm.getSOAPBody();
sh.detachNode();
QName bodyName = new QName("setInvocationAddress");
SOAPBodyElement bodyElement = sb.addBodyElement(bodyName);
bodyElement.setPrefix("pre");
QName role = new QName("arg0");
SOAPElement quotation1 = bodyElement.addChildElement(role);
quotation1.addTextNode(partnerRole);
QName name = new QName("arg1");
SOAPElement quotation2 = bodyElement.addChildElement(name);
- quotation2.addTextNode(partnerRole);
+ quotation2.addTextNode(partnerName);
for(String partnerEndpoint: partnerEndpoints) {
QName address = new QName("arg2");
SOAPElement quotation3 = bodyElement.addChildElement(address);
quotation3.addTextNode(partnerEndpoint);
}
if (serviceEndpoint.trim().endsWith("/"))
serviceEndpoint = serviceEndpoint.substring(0,
serviceEndpoint.length() - 1);
URL endpoint = new URL(serviceEndpoint);
//@SuppressWarnings("unused")
//this.printSOAPMessage(sm);
connection.call(sm, endpoint);
//this.printSOAPMessage(msg);
} catch (Exception e) {
throw new ContextNotSentException(serviceEndpoint, partnerRole, partnerName, partnerEndpoints);
}
}
@SuppressWarnings("unused")
private void printSOAPMessage(SOAPMessage sm) {
TransformerFactory transformerFactory = TransformerFactory.newInstance();
Transformer transformer;
Source sourceContent;
StreamResult result = new StreamResult(System.out);
try {
transformer = transformerFactory.newTransformer();
transformer.setOutputProperty(OutputKeys.INDENT, "yes");
transformer.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "4");
sourceContent = sm.getSOAPPart().getContent();
transformer.transform(sourceContent, result);
} catch (TransformerConfigurationException e) {
e.printStackTrace();
} catch (SOAPException e) {
e.printStackTrace();
} catch (TransformerException e) {
e.printStackTrace();
}
System.out.println();
}
}
| true | true | public void sendContext(String serviceEndpoint, String partnerRole, String partnerName,
List<String> partnerEndpoints) throws ContextNotSentException {
try {
SOAPConnectionFactory sfc = SOAPConnectionFactory.newInstance();
SOAPConnection connection = sfc.createConnection();
MessageFactory mf = MessageFactory.newInstance();
SOAPMessage sm = mf.createMessage();
SOAPEnvelope envelope = sm.getSOAPPart().getEnvelope();
String namespace = parseNamespace(serviceEndpoint);
envelope.addNamespaceDeclaration("pre", namespace);
SOAPHeader sh = sm.getSOAPHeader();
SOAPBody sb = sm.getSOAPBody();
sh.detachNode();
QName bodyName = new QName("setInvocationAddress");
SOAPBodyElement bodyElement = sb.addBodyElement(bodyName);
bodyElement.setPrefix("pre");
QName role = new QName("arg0");
SOAPElement quotation1 = bodyElement.addChildElement(role);
quotation1.addTextNode(partnerRole);
QName name = new QName("arg1");
SOAPElement quotation2 = bodyElement.addChildElement(name);
quotation2.addTextNode(partnerRole);
for(String partnerEndpoint: partnerEndpoints) {
QName address = new QName("arg2");
SOAPElement quotation3 = bodyElement.addChildElement(address);
quotation3.addTextNode(partnerEndpoint);
}
if (serviceEndpoint.trim().endsWith("/"))
serviceEndpoint = serviceEndpoint.substring(0,
serviceEndpoint.length() - 1);
URL endpoint = new URL(serviceEndpoint);
//@SuppressWarnings("unused")
//this.printSOAPMessage(sm);
connection.call(sm, endpoint);
//this.printSOAPMessage(msg);
} catch (Exception e) {
throw new ContextNotSentException(serviceEndpoint, partnerRole, partnerName, partnerEndpoints);
}
}
| public void sendContext(String serviceEndpoint, String partnerRole, String partnerName,
List<String> partnerEndpoints) throws ContextNotSentException {
try {
SOAPConnectionFactory sfc = SOAPConnectionFactory.newInstance();
SOAPConnection connection = sfc.createConnection();
MessageFactory mf = MessageFactory.newInstance();
SOAPMessage sm = mf.createMessage();
SOAPEnvelope envelope = sm.getSOAPPart().getEnvelope();
String namespace = parseNamespace(serviceEndpoint);
envelope.addNamespaceDeclaration("pre", namespace);
SOAPHeader sh = sm.getSOAPHeader();
SOAPBody sb = sm.getSOAPBody();
sh.detachNode();
QName bodyName = new QName("setInvocationAddress");
SOAPBodyElement bodyElement = sb.addBodyElement(bodyName);
bodyElement.setPrefix("pre");
QName role = new QName("arg0");
SOAPElement quotation1 = bodyElement.addChildElement(role);
quotation1.addTextNode(partnerRole);
QName name = new QName("arg1");
SOAPElement quotation2 = bodyElement.addChildElement(name);
quotation2.addTextNode(partnerName);
for(String partnerEndpoint: partnerEndpoints) {
QName address = new QName("arg2");
SOAPElement quotation3 = bodyElement.addChildElement(address);
quotation3.addTextNode(partnerEndpoint);
}
if (serviceEndpoint.trim().endsWith("/"))
serviceEndpoint = serviceEndpoint.substring(0,
serviceEndpoint.length() - 1);
URL endpoint = new URL(serviceEndpoint);
//@SuppressWarnings("unused")
//this.printSOAPMessage(sm);
connection.call(sm, endpoint);
//this.printSOAPMessage(msg);
} catch (Exception e) {
throw new ContextNotSentException(serviceEndpoint, partnerRole, partnerName, partnerEndpoints);
}
}
|
diff --git a/src/edu/uwm/ai/search/World.java b/src/edu/uwm/ai/search/World.java
index f94e5df..6875606 100644
--- a/src/edu/uwm/ai/search/World.java
+++ b/src/edu/uwm/ai/search/World.java
@@ -1,172 +1,172 @@
/*
* This file is part of the search package.
*
* Copyright (C) 2012, Eric Fritz
* Copyright (C) 2012, Reed Johnson
*
* 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 edu.uwm.ai.search;
import java.util.Random;
import edu.uwm.ai.search.util.Point;
import processing.core.PApplet;
/**
* @author Eric Fritz
* @author ReedJohnson
*/
public class World
{
private PApplet parent;
private final int w;
private final int h;
private final boolean[] obstacles;
private final Random random = new Random();
public World(PApplet parent, int w, int h)
{
this.parent = parent;
this.w = w;
this.h = h;
this.obstacles = new boolean[w * h];
for (int k = 0; k < 20; k++) {
int rw = (int) (Math.random() * 5) + 2;
int rh = (int) (Math.random() * 5) + 2;
int i = (int) (Math.random() * (w - rw / 2));
int j = (int) (Math.random() * (h - rh / 2));
for (int dw = 0; dw < rw; dw++) {
for (int dh = 0; dh < rh; dh++) {
setObstacle(i + dw, j + dh);
}
}
}
}
public Point getRandomFreePoint()
{
Point p;
do {
p = new Point((int) (random.nextDouble() * w), (int) (random.nextDouble() * h));
} while (!isValidPosition(p));
return p;
}
public int getWidth()
{
return w;
}
public int getHeight()
{
return h;
}
public boolean isValidPosition(Point p)
{
return isValidPosition(p.getX(), p.getY());
}
public boolean isValidPosition(int i, int j)
{
return i >= 0 && j >= 0 && i < w && j < h && !hasObstacle(i, j);
}
public boolean isAccessableThrough(Point dest, Point origin)
{
if (!isValidPosition(dest) || !isValidPosition(origin)) {
throw new IllegalArgumentException("Points are not valid.");
}
int xDist = Math.abs(dest.getX() - origin.getX());
int yDist = Math.abs(dest.getY() - origin.getY());
if (xDist > 1 || yDist > 1) {
throw new IllegalArgumentException("Points are not adjacent.");
}
// If points are touching there cannot be an obstacle between them.
if ((xDist == 0 && yDist == 1) || (xDist == 1 && yDist == 0)) {
return true;
}
// Otherwise ensure that the diagonal move doesn't go through a corner where two separate
// walls are joined.
boolean ob1 = isValidPosition(new Point(origin.getX() + xDist, origin.getY()));
boolean ob2 = isValidPosition(new Point(origin.getX(), origin.getY() + yDist));
- return ob1 && ob2;
+ return ob1 || ob2;
}
public boolean hasObstacle(Point p)
{
return hasObstacle(p.getX(), p.getY());
}
public boolean hasObstacle(int i, int j)
{
return obstacles[getIndex(i, j)];
}
public void setObstacle(int i, int j)
{
obstacles[getIndex(i, j)] = true;
}
public int getBlockWidth()
{
return Search.displayWidth / w;
}
public int getBlockHeight()
{
return Search.displayHeight / h;
}
public void draw()
{
parent.fill(200, 200, 200);
parent.stroke(0);
int dimW = getBlockWidth();
int dimH = getBlockHeight();
for (int i = 0; i < w; i++) {
for (int j = 0; j < h; j++) {
if (hasObstacle(i, j)) {
parent.rect(i * dimW, j * dimH, dimW, dimH);
}
}
}
}
private int getIndex(int i, int j)
{
return j * h + i;
}
}
| true | true | public boolean isAccessableThrough(Point dest, Point origin)
{
if (!isValidPosition(dest) || !isValidPosition(origin)) {
throw new IllegalArgumentException("Points are not valid.");
}
int xDist = Math.abs(dest.getX() - origin.getX());
int yDist = Math.abs(dest.getY() - origin.getY());
if (xDist > 1 || yDist > 1) {
throw new IllegalArgumentException("Points are not adjacent.");
}
// If points are touching there cannot be an obstacle between them.
if ((xDist == 0 && yDist == 1) || (xDist == 1 && yDist == 0)) {
return true;
}
// Otherwise ensure that the diagonal move doesn't go through a corner where two separate
// walls are joined.
boolean ob1 = isValidPosition(new Point(origin.getX() + xDist, origin.getY()));
boolean ob2 = isValidPosition(new Point(origin.getX(), origin.getY() + yDist));
return ob1 && ob2;
}
| public boolean isAccessableThrough(Point dest, Point origin)
{
if (!isValidPosition(dest) || !isValidPosition(origin)) {
throw new IllegalArgumentException("Points are not valid.");
}
int xDist = Math.abs(dest.getX() - origin.getX());
int yDist = Math.abs(dest.getY() - origin.getY());
if (xDist > 1 || yDist > 1) {
throw new IllegalArgumentException("Points are not adjacent.");
}
// If points are touching there cannot be an obstacle between them.
if ((xDist == 0 && yDist == 1) || (xDist == 1 && yDist == 0)) {
return true;
}
// Otherwise ensure that the diagonal move doesn't go through a corner where two separate
// walls are joined.
boolean ob1 = isValidPosition(new Point(origin.getX() + xDist, origin.getY()));
boolean ob2 = isValidPosition(new Point(origin.getX(), origin.getY() + yDist));
return ob1 || ob2;
}
|
diff --git a/src/com/pepsdev/timedlight/TimedLightView.java b/src/com/pepsdev/timedlight/TimedLightView.java
index 66b63db..df0dd37 100644
--- a/src/com/pepsdev/timedlight/TimedLightView.java
+++ b/src/com/pepsdev/timedlight/TimedLightView.java
@@ -1,326 +1,326 @@
package com.pepsdev.timedlight;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.Log;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.media.MediaPlayer;
import android.widget.Toast;
import alt.android.os.CountDownTimer;
import android.graphics.Rect;
public class TimedLightView extends SurfaceView
implements SurfaceHolder.Callback {
private static final String TAG = "com.pepsdev.timedlight";
private static final int SPT = 250; // seconds per tick
public interface OnTiretteListener {
public void tiretted();
public void unTiretted();
}
public void setOnTiretteListener(OnTiretteListener l) {
tiretteListener = l;
}
private SurfaceHolder mSurfaceHolder;
private GestureDetector gestureDetector;
private OnTiretteListener tiretteListener;
private CountDownTimer mCountDown;
public boolean mCoundDownStarted = false;
private int width;
private int height;
private float mDensity;
private boolean mSurfaceCreated = false;
private Bitmap currentLamp;
private Bitmap lamp_off;
private Bitmap lamp_on;
private Bitmap handle;
private Bitmap about;
private Rect aboutBox;
private int handleHeight;
private static final int HANDLE_DURATION = 1000 * 120; // 2 mins
/* Following constants are density dependants
* This is why they are not final
*/
//private int HANDLE_POS_STOP = 346;
private int HANDLE_POS_DEFAULT;
private int HANDLE_POS_X;
private int HANDLE_POS_MAX;
private Rect touchBox;
private int handlePos; // bottom of the handle
private boolean listeningToScroll = false;
public void draw() {
if (!mSurfaceCreated)
return;
Canvas c = null;
try {
c = mSurfaceHolder.lockCanvas();
doDraw(c);
} finally {
if (c != null) {
mSurfaceHolder.unlockCanvasAndPost(c);
}
}
}
public void tick(long ms) {
setTiretteDuration(ms);
if (handlePos <= HANDLE_POS_DEFAULT) {
unTiretted();
}
}
public void doDraw(Canvas c) {
c.drawARGB(255, 255, 255, 255);
c.drawBitmap(handle, HANDLE_POS_X, handlePos - handleHeight, null);
c.drawBitmap(currentLamp, 0, 0, null);
c.drawBitmap(about, aboutBox.left, aboutBox.top, null);
}
public long getTiretteDuration() {
long msPerPx = HANDLE_DURATION / (HANDLE_POS_MAX - HANDLE_POS_DEFAULT);
return msPerPx * (handlePos - HANDLE_POS_DEFAULT);
}
private void setTiretteDuration(long ms) {
double pxPerMs = (double)(HANDLE_POS_MAX - HANDLE_POS_DEFAULT) /
(double) HANDLE_DURATION;
handlePos = HANDLE_POS_DEFAULT + (int)(ms * pxPerMs);
draw();
}
public void lightItUp() {
playClick();
currentLamp = lamp_on;
draw();
}
public void switchOff() {
playClick();
reset();
}
public void reset() {
currentLamp = lamp_off;
setTiretteDuration(0);
}
public void toggle() {
if (currentLamp == lamp_on) {
switchOff();
} else {
lightItUp();
}
}
public TimedLightView(Context context, final float density) {
super(context);
mSurfaceHolder = getHolder();
mSurfaceHolder.addCallback(this);
lamp_off = BitmapFactory.decodeResource(getContext().getResources(),
R.drawable.lamp);
lamp_on = BitmapFactory.decodeResource(getContext().getResources(),
R.drawable.lamp_hl);
currentLamp = lamp_off;
handle = BitmapFactory.decodeResource(getContext().getResources(),
R.drawable.handle);
about = BitmapFactory.decodeResource(getContext().getResources(),
R.drawable.about);
handleHeight = handle.getHeight();
mDensity = density;
HANDLE_POS_DEFAULT = (int)(205 * mDensity);
handlePos = HANDLE_POS_DEFAULT;
HANDLE_POS_X = (int)(120 * mDensity);
HANDLE_POS_MAX = HANDLE_POS_DEFAULT + (int)(155 * mDensity);
touchBox = new Rect((int)(HANDLE_POS_X - (80 * mDensity)),
(int)(HANDLE_POS_DEFAULT - (120 * mDensity)),
(int)(HANDLE_POS_X + (80 * mDensity)),
(int)(HANDLE_POS_DEFAULT + handleHeight));
gestureDetector = new GestureDetector(
new GestureDetector.SimpleOnGestureListener () {
public boolean onScroll(MotionEvent e1, MotionEvent e2,
float distanceX, float distanceY) {
if (!listeningToScroll) return false;
if (distanceY < 0 &&
handlePos < HANDLE_POS_MAX) {
handlePos = Math.min(handlePos - (int)distanceY,
HANDLE_POS_MAX);
} else if (distanceY > 0 &&
handlePos > HANDLE_POS_DEFAULT) {
handlePos = Math.max(handlePos - (int)distanceY,
HANDLE_POS_DEFAULT);
}
draw();
return false;
}
});
setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
gestureDetector.onTouchEvent(event);
final float x = event.getX();
final float y = event.getY();
if (touchBox.contains((int)x, (int)y)) {
listeningToScroll = true;
stopCountDown();
if (event.getAction() == MotionEvent.ACTION_UP) {
Log.d("TimedLightView", "ACTIONNNNNNNN UP");
listeningToScroll = false;
}
}
if (aboutBox.contains((int)x, (int)y)) {
if (event.getAction() == MotionEvent.ACTION_UP) {
Toast.makeText(getContext(), R.string.about, Toast.LENGTH_LONG).show();
}
}
if (event.getAction() == MotionEvent.ACTION_UP) {
if (tiretteListener != null) {
if (handlePos > HANDLE_POS_DEFAULT) {
tiretted();
- } else {
+ } else if (currentLamp == lamp_on) {
unTiretted();
}
}
listeningToScroll = false;
}
return true;
}
});
}
public void tiretted() {
stopCountDown();
tiretteListener.tiretted();
startCountDown((int)getTiretteDuration());
}
public void unTiretted() {
stopCountDown();
if (tiretteListener != null) {
tiretteListener.unTiretted();
}
switchOff();
}
public void startCountDown(long timeout) {
Log.d(TAG, "start with timeout " + timeout);
final long stopAt = System.currentTimeMillis() + timeout;
mCoundDownStarted = true;
mCountDown = new CountDownTimer(timeout, SPT) {
@Override
public void onTick(long ms) {
tick(ms);
}
@Override
public void onFinish() {
}
}.start();
}
public void stopCountDown() {
mCoundDownStarted = false;
if (mCountDown != null) {
mCountDown.cancel();
}
}
public boolean isCountDownStarted(){
return mCoundDownStarted;
}
public void setCountDownStarted(boolean mCoundDownStarted) {
mCoundDownStarted = mCoundDownStarted;
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int width,
int height) {
width = width;
height = height;
refreshAboutBox();
}
@Override
public void surfaceCreated(SurfaceHolder holder) {
mSurfaceCreated = true;
width = getWidth();
height = getHeight();
refreshAboutBox();
draw();
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
mSurfaceCreated = false;
}
private void refreshAboutBox() {
final int left = width - about.getWidth() * 2;
final int top = height - about.getWidth() * 2;
final int right = width - about.getWidth();
final int bottom = height - about.getWidth();
if (aboutBox != null) {
aboutBox.left = left;
aboutBox.top = top;
aboutBox.right = right;
aboutBox.bottom = bottom;
}
aboutBox = new Rect(left, top, right, bottom);
}
private MediaPlayer mpClick = null;
private void playClick() {
if (mpClick == null) {
mpClick = MediaPlayer.create(getContext(), R.raw.click);
mpClick.start();
} else {
mpClick.stop();
try {
mpClick.prepare();
mpClick.start();
} catch(java.io.IOException e) {
Log.w("TimedLightView", "Warning player did not work");
Log.w("TimedLightView", e);
}
}
}
}
| true | true | public TimedLightView(Context context, final float density) {
super(context);
mSurfaceHolder = getHolder();
mSurfaceHolder.addCallback(this);
lamp_off = BitmapFactory.decodeResource(getContext().getResources(),
R.drawable.lamp);
lamp_on = BitmapFactory.decodeResource(getContext().getResources(),
R.drawable.lamp_hl);
currentLamp = lamp_off;
handle = BitmapFactory.decodeResource(getContext().getResources(),
R.drawable.handle);
about = BitmapFactory.decodeResource(getContext().getResources(),
R.drawable.about);
handleHeight = handle.getHeight();
mDensity = density;
HANDLE_POS_DEFAULT = (int)(205 * mDensity);
handlePos = HANDLE_POS_DEFAULT;
HANDLE_POS_X = (int)(120 * mDensity);
HANDLE_POS_MAX = HANDLE_POS_DEFAULT + (int)(155 * mDensity);
touchBox = new Rect((int)(HANDLE_POS_X - (80 * mDensity)),
(int)(HANDLE_POS_DEFAULT - (120 * mDensity)),
(int)(HANDLE_POS_X + (80 * mDensity)),
(int)(HANDLE_POS_DEFAULT + handleHeight));
gestureDetector = new GestureDetector(
new GestureDetector.SimpleOnGestureListener () {
public boolean onScroll(MotionEvent e1, MotionEvent e2,
float distanceX, float distanceY) {
if (!listeningToScroll) return false;
if (distanceY < 0 &&
handlePos < HANDLE_POS_MAX) {
handlePos = Math.min(handlePos - (int)distanceY,
HANDLE_POS_MAX);
} else if (distanceY > 0 &&
handlePos > HANDLE_POS_DEFAULT) {
handlePos = Math.max(handlePos - (int)distanceY,
HANDLE_POS_DEFAULT);
}
draw();
return false;
}
});
setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
gestureDetector.onTouchEvent(event);
final float x = event.getX();
final float y = event.getY();
if (touchBox.contains((int)x, (int)y)) {
listeningToScroll = true;
stopCountDown();
if (event.getAction() == MotionEvent.ACTION_UP) {
Log.d("TimedLightView", "ACTIONNNNNNNN UP");
listeningToScroll = false;
}
}
if (aboutBox.contains((int)x, (int)y)) {
if (event.getAction() == MotionEvent.ACTION_UP) {
Toast.makeText(getContext(), R.string.about, Toast.LENGTH_LONG).show();
}
}
if (event.getAction() == MotionEvent.ACTION_UP) {
if (tiretteListener != null) {
if (handlePos > HANDLE_POS_DEFAULT) {
tiretted();
} else {
unTiretted();
}
}
listeningToScroll = false;
}
return true;
}
});
}
| public TimedLightView(Context context, final float density) {
super(context);
mSurfaceHolder = getHolder();
mSurfaceHolder.addCallback(this);
lamp_off = BitmapFactory.decodeResource(getContext().getResources(),
R.drawable.lamp);
lamp_on = BitmapFactory.decodeResource(getContext().getResources(),
R.drawable.lamp_hl);
currentLamp = lamp_off;
handle = BitmapFactory.decodeResource(getContext().getResources(),
R.drawable.handle);
about = BitmapFactory.decodeResource(getContext().getResources(),
R.drawable.about);
handleHeight = handle.getHeight();
mDensity = density;
HANDLE_POS_DEFAULT = (int)(205 * mDensity);
handlePos = HANDLE_POS_DEFAULT;
HANDLE_POS_X = (int)(120 * mDensity);
HANDLE_POS_MAX = HANDLE_POS_DEFAULT + (int)(155 * mDensity);
touchBox = new Rect((int)(HANDLE_POS_X - (80 * mDensity)),
(int)(HANDLE_POS_DEFAULT - (120 * mDensity)),
(int)(HANDLE_POS_X + (80 * mDensity)),
(int)(HANDLE_POS_DEFAULT + handleHeight));
gestureDetector = new GestureDetector(
new GestureDetector.SimpleOnGestureListener () {
public boolean onScroll(MotionEvent e1, MotionEvent e2,
float distanceX, float distanceY) {
if (!listeningToScroll) return false;
if (distanceY < 0 &&
handlePos < HANDLE_POS_MAX) {
handlePos = Math.min(handlePos - (int)distanceY,
HANDLE_POS_MAX);
} else if (distanceY > 0 &&
handlePos > HANDLE_POS_DEFAULT) {
handlePos = Math.max(handlePos - (int)distanceY,
HANDLE_POS_DEFAULT);
}
draw();
return false;
}
});
setOnTouchListener(new View.OnTouchListener() {
public boolean onTouch(View v, MotionEvent event) {
gestureDetector.onTouchEvent(event);
final float x = event.getX();
final float y = event.getY();
if (touchBox.contains((int)x, (int)y)) {
listeningToScroll = true;
stopCountDown();
if (event.getAction() == MotionEvent.ACTION_UP) {
Log.d("TimedLightView", "ACTIONNNNNNNN UP");
listeningToScroll = false;
}
}
if (aboutBox.contains((int)x, (int)y)) {
if (event.getAction() == MotionEvent.ACTION_UP) {
Toast.makeText(getContext(), R.string.about, Toast.LENGTH_LONG).show();
}
}
if (event.getAction() == MotionEvent.ACTION_UP) {
if (tiretteListener != null) {
if (handlePos > HANDLE_POS_DEFAULT) {
tiretted();
} else if (currentLamp == lamp_on) {
unTiretted();
}
}
listeningToScroll = false;
}
return true;
}
});
}
|
diff --git a/src/com/java/phondeux/team/Team.java b/src/com/java/phondeux/team/Team.java
index 93adc68..241ecbb 100644
--- a/src/com/java/phondeux/team/Team.java
+++ b/src/com/java/phondeux/team/Team.java
@@ -1,128 +1,128 @@
package com.java.phondeux.team;
import java.sql.SQLException;
import java.util.logging.Logger;
import org.bukkit.ChatColor;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
/**
* Team for Bukkit
*
* @author Phondeux
*/
public class Team extends JavaPlugin{
protected Logger log;
protected ConnectionManager cm;
protected TeamHandler th;
public EventHandler eh;
protected StatsHandler sh;
private final TeamCommand teamCommand = new TeamCommand(this);
@Override
public void onDisable() {
System.out.println("[team] disabled");
}
@Override
public void onEnable() {
log = Logger.getLogger("Minecraft");
getCommand("team").setExecutor(teamCommand);
getCommand("tc").setExecutor(teamCommand);
PluginManager pm = getServer().getPluginManager();
final TeamPlayerListener playerListener = new TeamPlayerListener(this);
final TeamEntityListener entityListener = new TeamEntityListener(this);
pm.registerEvents(playerListener, this);
pm.registerEvents(entityListener, this);
initialize();
PluginDescriptionFile pdfFile = this.getDescription();
System.out.println( pdfFile.getName() + " version " + pdfFile.getVersion() + " is enabled!" );
}
private void initialize() {
try {
log.info("[Team] Connecting to database..");
cm = new ConnectionManager("localhost/teamdata", "teamuser", "teampass");
log.info("[Team] Initializing TeamHandler..");
th = new TeamHandler(this, cm);
log.info("[Team] Initializing EventHandler..");
eh = new EventHandler(this, cm);
log.info("[Team] Initializing StatsHandler..");
sh = new StatsHandler(this, cm);
} catch (SQLException e) {
e.printStackTrace();
log.severe("[Team] Initialization failed due to SQLException!");
getPluginLoader().disablePlugin(this);
return;
} catch (ClassNotFoundException e) {
e.printStackTrace();
log.severe("[Team] Initialization failed due to the driver not being found!");
getPluginLoader().disablePlugin(this);
return;
}
initializeEvents();
}
private void initializeEvents() {
eh.RegisterCallback(new EventHandler.EventCallback() {
public void run(int parent, int child, String data) {
getServer().broadcastMessage(ChatColor.GOLD + th.playerGetName(parent) + " created a new team, " + ChatColor.WHITE + th.teamGetName(child) + ChatColor.GOLD + "!");
}
}, EventHandler.Type.TeamCreate);
eh.RegisterCallback(new EventHandler.EventCallback() {
public void run(int parent, int child, String data) {
getServer().broadcastMessage(ChatColor.GOLD + th.playerGetName(parent) + " disbanded the team " + ChatColor.WHITE + th.teamGetName(child) + ChatColor.GOLD + "!");
th.teamSendToMembers(child, ChatColor.RED + "disbanded.");
}
}, EventHandler.Type.TeamDisband);
eh.RegisterCallback(new EventHandler.EventCallback() {
public void run(int parent, int child, String data) {
th.teamSendToMembers(child, TeamUtils.formatTeam(sh.GetTeamStats(child), data));
}
}, EventHandler.Type.TeamMotd);
eh.RegisterCallback(new EventHandler.EventCallback() {
public void run(int parent, int child, String data) {
th.teamSendToMembers(child, ChatColor.GOLD + th.playerGetName(parent) + " joined!");
}
}, EventHandler.Type.PlayerJoin);
eh.RegisterCallback(new EventHandler.EventCallback() {
public void run(int parent, int child, String data) {
th.teamSendToMembers(child, ChatColor.GOLD + th.playerGetName(parent) + " left!");
}
}, EventHandler.Type.PlayerLeave);
eh.RegisterCallback(new EventHandler.EventCallback() {
public void run(int parent, int child, String data) {
th.teamSendToMembers(child, ChatColor.GOLD + th.playerGetName(parent) + " is now invited!");
}
}, EventHandler.Type.PlayerInvite);
eh.RegisterCallback(new EventHandler.EventCallback() {
public void run(int parent, int child, String data) {
th.teamSendToMembers(child, ChatColor.GOLD + th.playerGetName(parent) + " is no longer invited!");
}
}, EventHandler.Type.PlayerDeinvite);
eh.RegisterCallback(new EventHandler.EventCallback() {
public void run(int parent, int child, String data) {
th.teamSendToMembers(child, ChatColor.GOLD + th.playerGetName(parent) + " was kicked!");
}
}, EventHandler.Type.PlayerKicked);
eh.RegisterCallback(new EventHandler.EventCallback() {
public void run(int parent, int child, String data) {
- if (th.teamChatter.contains(parent)) th.teamChatter.remove(parent);
+ if (th.teamChatter.contains(parent)) th.teamChatter.remove((Integer) parent);
}
}, EventHandler.Type.PlayerDeath);
}
}
| true | true | private void initializeEvents() {
eh.RegisterCallback(new EventHandler.EventCallback() {
public void run(int parent, int child, String data) {
getServer().broadcastMessage(ChatColor.GOLD + th.playerGetName(parent) + " created a new team, " + ChatColor.WHITE + th.teamGetName(child) + ChatColor.GOLD + "!");
}
}, EventHandler.Type.TeamCreate);
eh.RegisterCallback(new EventHandler.EventCallback() {
public void run(int parent, int child, String data) {
getServer().broadcastMessage(ChatColor.GOLD + th.playerGetName(parent) + " disbanded the team " + ChatColor.WHITE + th.teamGetName(child) + ChatColor.GOLD + "!");
th.teamSendToMembers(child, ChatColor.RED + "disbanded.");
}
}, EventHandler.Type.TeamDisband);
eh.RegisterCallback(new EventHandler.EventCallback() {
public void run(int parent, int child, String data) {
th.teamSendToMembers(child, TeamUtils.formatTeam(sh.GetTeamStats(child), data));
}
}, EventHandler.Type.TeamMotd);
eh.RegisterCallback(new EventHandler.EventCallback() {
public void run(int parent, int child, String data) {
th.teamSendToMembers(child, ChatColor.GOLD + th.playerGetName(parent) + " joined!");
}
}, EventHandler.Type.PlayerJoin);
eh.RegisterCallback(new EventHandler.EventCallback() {
public void run(int parent, int child, String data) {
th.teamSendToMembers(child, ChatColor.GOLD + th.playerGetName(parent) + " left!");
}
}, EventHandler.Type.PlayerLeave);
eh.RegisterCallback(new EventHandler.EventCallback() {
public void run(int parent, int child, String data) {
th.teamSendToMembers(child, ChatColor.GOLD + th.playerGetName(parent) + " is now invited!");
}
}, EventHandler.Type.PlayerInvite);
eh.RegisterCallback(new EventHandler.EventCallback() {
public void run(int parent, int child, String data) {
th.teamSendToMembers(child, ChatColor.GOLD + th.playerGetName(parent) + " is no longer invited!");
}
}, EventHandler.Type.PlayerDeinvite);
eh.RegisterCallback(new EventHandler.EventCallback() {
public void run(int parent, int child, String data) {
th.teamSendToMembers(child, ChatColor.GOLD + th.playerGetName(parent) + " was kicked!");
}
}, EventHandler.Type.PlayerKicked);
eh.RegisterCallback(new EventHandler.EventCallback() {
public void run(int parent, int child, String data) {
if (th.teamChatter.contains(parent)) th.teamChatter.remove(parent);
}
}, EventHandler.Type.PlayerDeath);
}
| private void initializeEvents() {
eh.RegisterCallback(new EventHandler.EventCallback() {
public void run(int parent, int child, String data) {
getServer().broadcastMessage(ChatColor.GOLD + th.playerGetName(parent) + " created a new team, " + ChatColor.WHITE + th.teamGetName(child) + ChatColor.GOLD + "!");
}
}, EventHandler.Type.TeamCreate);
eh.RegisterCallback(new EventHandler.EventCallback() {
public void run(int parent, int child, String data) {
getServer().broadcastMessage(ChatColor.GOLD + th.playerGetName(parent) + " disbanded the team " + ChatColor.WHITE + th.teamGetName(child) + ChatColor.GOLD + "!");
th.teamSendToMembers(child, ChatColor.RED + "disbanded.");
}
}, EventHandler.Type.TeamDisband);
eh.RegisterCallback(new EventHandler.EventCallback() {
public void run(int parent, int child, String data) {
th.teamSendToMembers(child, TeamUtils.formatTeam(sh.GetTeamStats(child), data));
}
}, EventHandler.Type.TeamMotd);
eh.RegisterCallback(new EventHandler.EventCallback() {
public void run(int parent, int child, String data) {
th.teamSendToMembers(child, ChatColor.GOLD + th.playerGetName(parent) + " joined!");
}
}, EventHandler.Type.PlayerJoin);
eh.RegisterCallback(new EventHandler.EventCallback() {
public void run(int parent, int child, String data) {
th.teamSendToMembers(child, ChatColor.GOLD + th.playerGetName(parent) + " left!");
}
}, EventHandler.Type.PlayerLeave);
eh.RegisterCallback(new EventHandler.EventCallback() {
public void run(int parent, int child, String data) {
th.teamSendToMembers(child, ChatColor.GOLD + th.playerGetName(parent) + " is now invited!");
}
}, EventHandler.Type.PlayerInvite);
eh.RegisterCallback(new EventHandler.EventCallback() {
public void run(int parent, int child, String data) {
th.teamSendToMembers(child, ChatColor.GOLD + th.playerGetName(parent) + " is no longer invited!");
}
}, EventHandler.Type.PlayerDeinvite);
eh.RegisterCallback(new EventHandler.EventCallback() {
public void run(int parent, int child, String data) {
th.teamSendToMembers(child, ChatColor.GOLD + th.playerGetName(parent) + " was kicked!");
}
}, EventHandler.Type.PlayerKicked);
eh.RegisterCallback(new EventHandler.EventCallback() {
public void run(int parent, int child, String data) {
if (th.teamChatter.contains(parent)) th.teamChatter.remove((Integer) parent);
}
}, EventHandler.Type.PlayerDeath);
}
|
diff --git a/workflow_plugins/europeana-uim-plugin-enrichment/src/main/java/eu/europeana/uim/enrichment/EnrichmentPlugin.java b/workflow_plugins/europeana-uim-plugin-enrichment/src/main/java/eu/europeana/uim/enrichment/EnrichmentPlugin.java
index 06969093..b3f86e84 100644
--- a/workflow_plugins/europeana-uim-plugin-enrichment/src/main/java/eu/europeana/uim/enrichment/EnrichmentPlugin.java
+++ b/workflow_plugins/europeana-uim-plugin-enrichment/src/main/java/eu/europeana/uim/enrichment/EnrichmentPlugin.java
@@ -1,1492 +1,1497 @@
/*
* Copyright 2007-2012 The Europeana Foundation
*
* Licenced under the EUPL, Version 1.1 (the "Licence") and subsequent versions as approved
* by the European Commission;
* You may not use this work except in compliance with the Licence.
*
* You may obtain a copy of the Licence at:
* http://joinup.ec.europa.eu/software/page/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.europeana.uim.enrichment;
import java.io.IOException;
import java.io.StringReader;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map.Entry;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.logging.Level;
import java.util.logging.Logger;
import java.util.regex.Pattern;
import org.apache.commons.lang.StringUtils;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.impl.HttpSolrServer;
import org.apache.solr.common.SolrInputDocument;
import org.jibx.runtime.BindingDirectory;
import org.jibx.runtime.IBindingFactory;
import org.jibx.runtime.IUnmarshallingContext;
import org.jibx.runtime.JiBXException;
import org.theeuropeanlibrary.model.common.qualifier.Status;
import com.google.code.morphia.query.Query;
import com.google.code.morphia.query.UpdateOperations;
import com.mongodb.BasicDBObject;
import com.mongodb.DBCollection;
import com.mongodb.DBObject;
import com.mongodb.WriteConcern;
import eu.annocultor.converters.europeana.Entity;
import eu.annocultor.converters.europeana.Field;
import eu.annocultor.converters.europeana.RecordCompletenessRanking;
import eu.europeana.corelib.definitions.jibx.AgentType;
import eu.europeana.corelib.definitions.jibx.AggregatedCHO;
import eu.europeana.corelib.definitions.jibx.Aggregation;
import eu.europeana.corelib.definitions.jibx.Alt;
import eu.europeana.corelib.definitions.jibx.Concept;
import eu.europeana.corelib.definitions.jibx.Country;
import eu.europeana.corelib.definitions.jibx.CountryCodes;
import eu.europeana.corelib.definitions.jibx.Creator;
import eu.europeana.corelib.definitions.jibx.EuropeanaAggregationType;
import eu.europeana.corelib.definitions.jibx.EuropeanaProxy;
import eu.europeana.corelib.definitions.jibx.HasView;
import eu.europeana.corelib.definitions.jibx.LandingPage;
import eu.europeana.corelib.definitions.jibx.Language1;
import eu.europeana.corelib.definitions.jibx.LanguageCodes;
import eu.europeana.corelib.definitions.jibx.Lat;
import eu.europeana.corelib.definitions.jibx.LiteralType;
import eu.europeana.corelib.definitions.jibx.PlaceType;
import eu.europeana.corelib.definitions.jibx.ProvidedCHOType;
import eu.europeana.corelib.definitions.jibx.ProxyFor;
import eu.europeana.corelib.definitions.jibx.ProxyIn;
import eu.europeana.corelib.definitions.jibx.ProxyType;
import eu.europeana.corelib.definitions.jibx.RDF;
import eu.europeana.corelib.definitions.jibx.ResourceOrLiteralType;
import eu.europeana.corelib.definitions.jibx.ResourceOrLiteralType.Lang;
import eu.europeana.corelib.definitions.jibx.ResourceOrLiteralType.Resource;
import eu.europeana.corelib.definitions.jibx.ResourceType;
import eu.europeana.corelib.definitions.jibx.Rights1;
import eu.europeana.corelib.definitions.jibx.TimeSpanType;
import eu.europeana.corelib.definitions.jibx.WebResourceType;
import eu.europeana.corelib.definitions.jibx.Year;
import eu.europeana.corelib.definitions.jibx._Long;
import eu.europeana.corelib.definitions.model.EdmLabel;
import eu.europeana.corelib.definitions.solr.DocType;
import eu.europeana.corelib.dereference.impl.RdfMethod;
import eu.europeana.corelib.solr.bean.impl.FullBeanImpl;
import eu.europeana.corelib.solr.entity.AgentImpl;
import eu.europeana.corelib.solr.entity.ConceptImpl;
import eu.europeana.corelib.solr.entity.PlaceImpl;
import eu.europeana.corelib.solr.entity.ProxyImpl;
import eu.europeana.corelib.solr.entity.TimespanImpl;
import eu.europeana.corelib.solr.server.EdmMongoServer;
import eu.europeana.corelib.solr.utils.EdmUtils;
import eu.europeana.corelib.solr.utils.MongoConstructor;
import eu.europeana.corelib.solr.utils.SolrConstructor;
import eu.europeana.uim.common.TKey;
import eu.europeana.uim.enrichment.enums.OriginalField;
import eu.europeana.uim.enrichment.normalizer.AgentNormalizer;
import eu.europeana.uim.enrichment.service.EnrichmentService;
import eu.europeana.uim.enrichment.utils.EuropeanaDateUtils;
import eu.europeana.uim.enrichment.utils.EuropeanaEnrichmentTagger;
import eu.europeana.uim.enrichment.utils.OsgiEdmMongoServer;
import eu.europeana.uim.enrichment.utils.PropertyReader;
import eu.europeana.uim.enrichment.utils.UimConfigurationProperty;
import eu.europeana.uim.model.europeana.EuropeanaModelRegistry;
import eu.europeana.uim.model.europeanaspecific.fieldvalues.ControlledVocabularyProxy;
import eu.europeana.uim.model.europeanaspecific.fieldvalues.EuropeanaRetrievableField;
import eu.europeana.uim.orchestration.ExecutionContext;
import eu.europeana.uim.plugin.ingestion.AbstractIngestionPlugin;
import eu.europeana.uim.plugin.ingestion.CorruptedDatasetException;
import eu.europeana.uim.plugin.ingestion.IngestionPluginFailedException;
import eu.europeana.uim.store.Collection;
import eu.europeana.uim.store.MetaDataRecord;
import eu.europeana.uim.sugar.LoginFailureException;
import eu.europeana.uim.sugar.QueryResultException;
import eu.europeana.uim.sugar.SugarCrmRecord;
import eu.europeana.uim.sugar.SugarCrmService;
/**
* Enrichment plugin implementation
*
* @author Yorgos.Mamakis@ kb.nl
*
*/
public class EnrichmentPlugin<I> extends
AbstractIngestionPlugin<MetaDataRecord<I>, I> {
private static HttpSolrServer solrServer;
private static String mongoDB;
private static String mongoHost = PropertyReader
.getProperty(UimConfigurationProperty.MONGO_HOSTURL);
private static String mongoPort = PropertyReader
.getProperty(UimConfigurationProperty.MONGO_HOSTPORT);
private static String solrUrl;
private static String solrCore;
private static int recordNumber;
private static int deleted;
private static String europeanaID = PropertyReader
.getProperty(UimConfigurationProperty.MONGO_DB_EUROPEANA_ID);
private static String repository = PropertyReader
.getProperty(UimConfigurationProperty.UIM_REPOSITORY);
private static SugarCrmService sugarCrmService;
private static EnrichmentService enrichmentService;
private static String previewsOnlyInPortal;
private static String collections = PropertyReader
.getProperty(UimConfigurationProperty.MONGO_DB_COLLECTIONS);
private final static String PORTALURL = "http://www.europeana.eu/portal/record";
private final static String SUFFIX = ".html";
private static IBindingFactory bfact;
private static OsgiEdmMongoServer mongoServer;
private static EuropeanaEnrichmentTagger tagger;
private static int processCount;
private final static String XML_LANG = "_@xml:lang";
private static final Logger log = Logger.getLogger(EnrichmentPlugin.class
.getName());
private enum EnrichmentFields {
DC_DATE("proxy_dc_date"), DC_COVERAGE("proxy_dc_coverage"), DC_TERMS_TEMPORAL(
"proxy_dcterms_temporal"), EDM_YEAR("proxy_edm_year"), DCTERMS_SPATIAL(
"proxy_dcterms_spatial"), DC_TYPE("proxy_dc_type"), DC_SUBJECT(
"proxy_dc_subject"), DC_CREATOR("proxy_dc_creator"), DC_CONTRIBUTOR(
"proxy_dc_contributor");
String value;
private EnrichmentFields(String value) {
this.value = value;
}
public String getValue() {
return this.value;
}
};
public EnrichmentPlugin(String name, String description) {
super(name, description);
}
public EnrichmentPlugin() {
super("", "");
}
static {
try {
// Should be placed in a static block for performance reasons
bfact = BindingDirectory.getFactory(RDF.class);
} catch (JiBXException e) {
log.log(Level.SEVERE, "Error creating the JibX factory");
}
}
/**
* The parameters used by this WorkflowStart
*/
private static final List<String> params = new ArrayList<String>() {
private static final long serialVersionUID = 1L;
};
/*
* (non-Javadoc)
*
* @see eu.europeana.uim.plugin.ingestion.IngestionPlugin#getInputFields()
*/
@Override
public TKey<?, ?>[] getInputFields() {
return null;
}
/*
* (non-Javadoc)
*
* @see
* eu.europeana.uim.plugin.ingestion.IngestionPlugin#getOptionalFields()
*/
@Override
public TKey<?, ?>[] getOptionalFields() {
return null;
}
/*
* (non-Javadoc)
*
* @see eu.europeana.uim.plugin.ingestion.IngestionPlugin#getOutputFields()
*/
@Override
public TKey<?, ?>[] getOutputFields() {
return null;
}
/*
* (non-Javadoc)
*
* @see eu.europeana.uim.plugin.Plugin#initialize()
*/
@Override
public void initialize() {
}
/*
* (non-Javadoc)
*
* @see eu.europeana.uim.plugin.Plugin#shutdown()
*/
@Override
public void shutdown() {
}
/*
* (non-Javadoc)
*
* @see eu.europeana.uim.plugin.Plugin#getParameters()
*/
@Override
public List<String> getParameters() {
return new ArrayList<String>();
}
/*
* (non-Javadoc)
*
* @see eu.europeana.uim.plugin.Plugin#getPreferredThreadCount()
*/
@Override
public int getPreferredThreadCount() {
return 12;
}
/*
* (non-Javadoc)
*
* @see eu.europeana.uim.plugin.Plugin#getMaximumThreadCount()
*/
@Override
public int getMaximumThreadCount() {
return 15;
}
/*
* (non-Javadoc)
*
* @see eu.europeana.uim.plugin.ExecutionPlugin#initialize(eu.europeana.uim.
* orchestration.ExecutionContext)
*/
@Override
@SuppressWarnings("rawtypes")
public void initialize(ExecutionContext<MetaDataRecord<I>, I> context)
throws IngestionPluginFailedException {
Collection collection = null;
processCount = 0;
try {
log.log(Level.INFO, "Initializing Annocultor");
if (tagger == null) {
tagger = new EuropeanaEnrichmentTagger();
tagger.init("Europeana", "localhost", "27017");
}
log.log(Level.INFO, "Annocultor Initialized");
solrServer = enrichmentService.getSolrServer();
log.log(Level.INFO, "Solr Server Acquired");
mongoDB = enrichmentService.getMongoDB();
if (mongoServer == null) {
mongoServer = enrichmentService.getEuropeanaMongoServer();
}
log.log(Level.INFO, "Mongo Initialized");
collection = (Collection) context.getExecution().getDataSet();
log.log(Level.INFO, "Collection acquired");
long start = new Date().getTime();
log.log(Level.INFO,
"Clearing collection " + collection.getMnemonic()
+ " from Mongo");
clearData(mongoServer, collection.getMnemonic());
log.log(Level.INFO,
"Clearing collection " + collection.getMnemonic()
+ " from Solr");
solrServer.deleteByQuery("europeana_collectionName:"
+ collection.getName().split("_")[0] + "*");
log.log(Level.INFO,
"Finished removing after " + (new Date().getTime() - start)
+ " ms");
} catch (Exception e) {
e.printStackTrace();
log.log(Level.SEVERE, e.getMessage());
}
String sugarCrmId = collection
.getValue(ControlledVocabularyProxy.SUGARCRMID);
log.log(Level.INFO, "SugarCrmId acquired");
try {
try {
sugarCrmService
.updateSession(
PropertyReader
.getProperty(UimConfigurationProperty.SUGARCRM_USERNAME),
PropertyReader
.getProperty(UimConfigurationProperty.SUGARCRM_PASSWORD));
} catch (LoginFailureException e) {
log.log(Level.SEVERE,
"Error updating Sugar Session id. " + e.getMessage());
} catch (Exception e) {
log.log(Level.SEVERE,
"Generic SugarCRM error. " + e.getMessage());
}
SugarCrmRecord sugarCrmRecord = sugarCrmService
.retrieveRecord(sugarCrmId);
log.log(Level.INFO, " Retrieved the SugarCRM collection");
previewsOnlyInPortal = sugarCrmRecord
.getItemValue(EuropeanaRetrievableField.PREVIEWS_ONLY_IN_PORTAL);
} catch (QueryResultException e) {
log.log(Level.SEVERE, "Error retrieving SugarCRM record");
previewsOnlyInPortal = "false";
} catch (Exception e) {
log.log(Level.SEVERE,
"Record could not be retrieved. " + e.getMessage());
}
log.log(Level.INFO, "Preview Only in portal acquired with value: "
+ previewsOnlyInPortal);
}
public static void setTagger(EuropeanaEnrichmentTagger tagger) {
EnrichmentPlugin.tagger = tagger;
}
/*
* (non-Javadoc)
*
* @see eu.europeana.uim.plugin.ExecutionPlugin#completed(eu.europeana.uim.
* orchestration.ExecutionContext)
*/
@Override
public void completed(ExecutionContext<MetaDataRecord<I>, I> context)
throws IngestionPluginFailedException {
log.log(Level.INFO, "Adding " + recordNumber + " documents");
System.out.println("Adding " + recordNumber + " documents");
System.out.println("Process called " + processCount);
try {
solrServer.commit();
log.log(Level.INFO, "Added " + recordNumber + " documents");
System.out.println("Added " + recordNumber + " documents");
log.log(Level.INFO, "Deleted are " + deleted);
System.out.println("Deleted are " + deleted);
} catch (SolrServerException e) {
log.log(Level.SEVERE, e.getMessage());
} catch (IOException e) {
log.log(Level.SEVERE, e.getMessage());
}
log.log(Level.INFO, "Committed in Solr Server");
recordNumber = 0;
processCount = 0;
deleted = 0;
}
/*
* (non-Javadoc)
*
* @see
* eu.europeana.uim.plugin.ingestion.IngestionPlugin#process(eu.europeana
* .uim.store.UimDataSet, eu.europeana.uim.orchestration.ExecutionContext)
*/
@Override
public boolean process(MetaDataRecord<I> mdr,
ExecutionContext<MetaDataRecord<I>, I> context)
throws IngestionPluginFailedException, CorruptedDatasetException {
String value = null;
processCount++;
if (mdr.getValues(EuropeanaModelRegistry.EDMDEREFERENCEDRECORD) != null
&& mdr.getValues(EuropeanaModelRegistry.EDMDEREFERENCEDRECORD)
.size() > 0) {
value = mdr.getValues(EuropeanaModelRegistry.EDMDEREFERENCEDRECORD)
.get(0);
} else {
value = mdr.getValues(EuropeanaModelRegistry.EDMRECORD).get(0);
}
log.log(Level.INFO,
"Status size = "
+ mdr.getValues(EuropeanaModelRegistry.STATUS).size());
List<Status> status = mdr.getValues(EuropeanaModelRegistry.STATUS);
if (!(status != null && status.get(0).equals(Status.DELETED))) {
MongoConstructor mongoConstructor = new MongoConstructor();
try {
IUnmarshallingContext uctx = bfact.createUnmarshallingContext();
RDF rdf = (RDF) uctx.unmarshalDocument(new StringReader(value));
log.log(Level.INFO, "Processing record "
+ rdf.getProvidedCHOList().get(0).getAbout());
SolrInputDocument basicDocument = new SolrConstructor()
.constructSolrDocument(rdf);
SolrInputDocument mockDocument = createMockForEnrichment(basicDocument);
List<Entity> entities = null;
log.log(Level.INFO, "Before tagging Document");
entities = tagger.tagDocument(mockDocument);
log.log(Level.INFO, "Tagged document");
mergeEntities(rdf, entities);
RDF rdfFinal = cleanRDF(rdf);
boolean hasEuropeanaProxy = false;
for (ProxyType proxy : rdfFinal.getProxyList()) {
if (proxy.getEuropeanaProxy() != null
&& proxy.getEuropeanaProxy().isEuropeanaProxy()) {
hasEuropeanaProxy = true;
}
}
if (!hasEuropeanaProxy) {
ProxyType europeanaProxy = new ProxyType();
EuropeanaProxy prx = new EuropeanaProxy();
prx.setEuropeanaProxy(true);
europeanaProxy.setEuropeanaProxy(prx);
List<String> years = new ArrayList<String>();
for (ProxyType proxy : rdfFinal.getProxyList()) {
years.addAll(new EuropeanaDateUtils()
.createEuropeanaYears(proxy));
europeanaProxy.setType(proxy.getType());
}
List<Year> yearList = new ArrayList<Year>();
for (String year : years) {
Year yearObj = new Year();
LiteralType.Lang lang = new LiteralType.Lang();
lang.setLang("eur");
yearObj.setLang(lang);
yearObj.setString(year);
yearList.add(yearObj);
}
europeanaProxy.setYearList(yearList);
for (ProxyType proxy : rdfFinal.getProxyList()) {
if (proxy != null && proxy.getEuropeanaProxy() != null
&& proxy.getEuropeanaProxy().isEuropeanaProxy()) {
rdfFinal.getProxyList().remove(proxy);
}
}
rdfFinal.getProxyList().add(europeanaProxy);
}
SolrInputDocument solrInputDocument = new SolrConstructor()
.constructSolrDocument(rdfFinal);
FullBeanImpl fullBean = mongoConstructor.constructFullBean(
rdfFinal, mongoServer);
solrInputDocument.addField(
EdmLabel.PREVIEW_NO_DISTRIBUTE.toString(),
previewsOnlyInPortal);
fullBean.getAggregations()
.get(0)
.setEdmPreviewNoDistribute(
Boolean.parseBoolean(previewsOnlyInPortal));
int completeness = RecordCompletenessRanking
.rankRecordCompleteness(solrInputDocument);
fullBean.setEuropeanaCompleteness(completeness);
solrInputDocument.addField(
EdmLabel.EUROPEANA_COMPLETENESS.toString(),
completeness);
fullBean.setEuropeanaCollectionName(new String[] { mdr
.getCollection().getName() });
if (fullBean.getEuropeanaAggregation().getEdmLanguage() != null) {
fullBean.setLanguage(new String[] { fullBean
.getEuropeanaAggregation().getEdmLanguage()
.values().iterator().next().get(0) });
}
solrInputDocument.setField("europeana_collectionName", mdr
.getCollection().getName());
ProxyImpl providerProxy = getProviderProxy(fullBean);
List<String> titles = new ArrayList<String>();
for (Entry<String, List<String>> entry : providerProxy
.getDcTitle().entrySet()) {
titles.addAll(entry.getValue());
}
fullBean.setTitle(titles.toArray(new String[titles.size()]));
if (mdr.getValues(EuropeanaModelRegistry.INITIALSAVE) != null
&& mdr.getValues(EuropeanaModelRegistry.INITIALSAVE)
.size() > 0) {
fullBean.setTimestampCreated(new Date(mdr.getValues(
EuropeanaModelRegistry.INITIALSAVE).get(0)));
} else {
Date timestampCreated = new Date();
fullBean.setTimestampCreated(timestampCreated);
mdr.addValue(EuropeanaModelRegistry.INITIALSAVE,
timestampCreated.getTime());
}
mdr.deleteValues(EuropeanaModelRegistry.UPDATEDSAVE);
Date timestampUpdated = new Date();
fullBean.setTimestampUpdated(timestampUpdated);
mdr.addValue(EuropeanaModelRegistry.UPDATEDSAVE,
timestampUpdated.getTime());
mdr.deleteValues(EuropeanaModelRegistry.EDMENRICHEDRECORD);
mdr.addValue(EuropeanaModelRegistry.EDMENRICHEDRECORD,
EdmUtils.toEDM(fullBean));
if (mongoServer.getFullBean(fullBean.getAbout()) == null) {
mongoServer.getDatastore().save(fullBean);
} else {
updateFullBean(mongoServer, fullBean);
}
recordNumber++;
solrServer.add(solrInputDocument);
return true;
} catch (JiBXException e) {
log.log(Level.SEVERE,
"JibX Exception occured with error " + e.getMessage()
+ "\nRetrying");
e.printStackTrace();
return false;
} catch (MalformedURLException e) {
log.log(Level.SEVERE,
"Malformed URL Exception occured with error "
+ e.getMessage() + "\nRetrying");
e.printStackTrace();
return false;
} catch (InstantiationException e) {
log.log(Level.SEVERE,
"Instantiation Exception occured with error "
+ e.getMessage() + "\nRetrying");
e.printStackTrace();
return false;
} catch (IllegalAccessException e) {
log.log(Level.SEVERE,
"Illegal Access Exception occured with error "
+ e.getMessage() + "\nRetrying");
e.printStackTrace();
return false;
} catch (IOException e) {
log.log(Level.SEVERE,
"IO Exception occured with error " + e.getMessage()
+ "\nRetrying");
e.printStackTrace();
return false;
} catch (Exception e) {
e.printStackTrace();
log.log(Level.SEVERE, "Generic Exception occured with error "
+ e.getMessage() + "\nRetrying");
return false;
}
} else {
deleted++;
}
return false;
}
private SolrInputDocument createMockForEnrichment(
SolrInputDocument basicDocument) {
SolrInputDocument mockDocument = new SolrInputDocument();
for (String fieldName : basicDocument.keySet()) {
for (EnrichmentFields field : EnrichmentFields.values()) {
if (StringUtils.equals(field.getValue(), fieldName)
|| StringUtils.startsWith(fieldName, field.getValue())) {
if (field.equals(EnrichmentFields.DC_CREATOR)
|| field.equals(EnrichmentFields.DC_CONTRIBUTOR)) {
mockDocument.addField(field.getValue(), AgentNormalizer
.normalize(basicDocument
.getFieldValue(fieldName)));
} else {
mockDocument.addField(field.getValue(),
basicDocument.getFieldValue(fieldName));
}
}
}
}
return mockDocument;
}
private void clearData(EdmMongoServer mongoServer2, String collection) {
DBCollection records = mongoServer2.getDatastore().getDB()
.getCollection("record");
DBCollection proxies = mongoServer2.getDatastore().getDB()
.getCollection("Proxy");
DBCollection providedCHOs = mongoServer2.getDatastore().getDB()
.getCollection("ProvidedCHO");
DBCollection aggregations = mongoServer2.getDatastore().getDB()
.getCollection("Aggregation");
DBCollection europeanaAggregations = mongoServer2.getDatastore()
.getDB().getCollection("EuropeanaAggregation");
DBObject query = new BasicDBObject("about", Pattern.compile("^/"
+ collection + "/"));
DBObject proxyQuery = new BasicDBObject("about",
Pattern.compile("^/proxy/provider/" + collection + "/"));
DBObject europeanaProxyQuery = new BasicDBObject("about",
Pattern.compile("^/proxy/europeana/" + collection + "/"));
DBObject providedCHOQuery = new BasicDBObject("about",
Pattern.compile("^/item/" + collection + "/"));
DBObject aggregationQuery = new BasicDBObject("about",
Pattern.compile("^/aggregation/provider/" + collection + "/"));
DBObject europeanaAggregationQuery = new BasicDBObject("about",
Pattern.compile("^/aggregation/europeana/" + collection + "/"));
europeanaAggregations.remove(europeanaAggregationQuery,
WriteConcern.FSYNC_SAFE);
records.remove(query, WriteConcern.FSYNC_SAFE);
proxies.remove(europeanaProxyQuery, WriteConcern.FSYNC_SAFE);
proxies.remove(proxyQuery, WriteConcern.FSYNC_SAFE);
providedCHOs.remove(providedCHOQuery, WriteConcern.FSYNC_SAFE);
aggregations.remove(aggregationQuery, WriteConcern.FSYNC_SAFE);
}
// update a FullBean
private void updateFullBean(EdmMongoServer mongoServer2,
FullBeanImpl fullBean) {
Query<FullBeanImpl> updateQuery = mongoServer2.getDatastore()
.createQuery(FullBeanImpl.class).field("about")
.equal(fullBean.getAbout().replace("/item", ""));
UpdateOperations<FullBeanImpl> ops = mongoServer2.getDatastore()
.createUpdateOperations(FullBeanImpl.class);
ops.set("title", fullBean.getTitle() != null ? fullBean.getTitle()
: new String[] {});
ops.set("year", fullBean.getYear() != null ? fullBean.getYear()
: new String[] {});
ops.set("provider",
fullBean.getProvider() != null ? fullBean.getProvider()
: new String[] {});
ops.set("language",
fullBean.getLanguage() != null ? fullBean.getLanguage()
: new String[] {});
ops.set("type", fullBean.getType() != null ? fullBean.getType()
: DocType.IMAGE);
ops.set("europeanaCompleteness", fullBean.getEuropeanaCompleteness());
ops.set("optOut", fullBean.isOptedOut());
ops.set("places", fullBean.getPlaces() != null ? fullBean.getPlaces()
: new ArrayList<PlaceImpl>());
ops.set("agents", fullBean.getAgents() != null ? fullBean.getAgents()
: new ArrayList<AgentImpl>());
ops.set("timespans",
fullBean.getTimespans() != null ? fullBean.getTimespans()
: new ArrayList<TimespanImpl>());
ops.set("concepts",
fullBean.getConcepts() != null ? fullBean.getConcepts()
: new ArrayList<ConceptImpl>());
ops.set("aggregations", fullBean.getAggregations());
ops.set("providedCHOs", fullBean.getProvidedCHOs());
ops.set("europeanaAggregation", fullBean.getEuropeanaAggregation());
ops.set("proxies", fullBean.getProxies());
ops.set("country",
fullBean.getCountry() != null ? fullBean.getCountry()
: new String[] {});
ops.set("europeanaCollectionName",
fullBean.getEuropeanaCollectionName());
mongoServer2.getDatastore().update(updateQuery, ops);
}
/*
* Merge Contextual Entities
*/
private void mergeEntities(RDF rdf, List<Entity> entities)
throws SecurityException, IllegalArgumentException,
NoSuchMethodException, IllegalAccessException,
InvocationTargetException {
ProxyType europeanaProxy = null;
ProvidedCHOType cho = null;
List<ProvidedCHOType> providedChoList = rdf.getProvidedCHOList();
cho = providedChoList.get(0);
List<ProxyType> proxyList = rdf.getProxyList();
+ int i = 0;
+ int index=0;
for (ProxyType proxy : proxyList) {
if (proxy.getEuropeanaProxy() != null
&& proxy.getEuropeanaProxy().isEuropeanaProxy()) {
europeanaProxy = proxy;
+ index=i;
} else {
if (!StringUtils
.startsWith(proxy.getAbout(), "/proxy/provider")) {
proxy.setAbout("/proxy/provider" + proxy.getAbout());
}
}
+ i++;
}
if (europeanaProxy == null) {
europeanaProxy = createEuropeanaProxy(rdf);
}
europeanaProxy.setAbout("/proxy/europeana" + cho.getAbout());
ProxyFor pf = new ProxyFor();
pf.setResource("/item" + cho.getAbout());
europeanaProxy.setProxyFor(pf);
List<ProxyIn> pinList = new ArrayList<ProxyIn>();
ProxyIn pin = new ProxyIn();
pin.setResource("/aggregation/europeana" + cho.getAbout());
pinList.add(pin);
europeanaProxy.setProxyInList(pinList);
for (Entity entity : entities) {
if (StringUtils.equals(entity.getClassName(), "Concept")) {
Concept concept = new Concept();
List<Field> fields = entity.getFields();
if (fields != null && fields.size() > 0) {
for (Field field : fields) {
if (StringUtils.equalsIgnoreCase(field.getName(),
"skos_concept")) {
concept.setAbout(field
.getValues()
.get(field.getValues().keySet().iterator()
.next()).get(0));
} else {
if (field.getValues() != null) {
for (Entry<String, List<String>> entry : field
.getValues().entrySet()) {
for (String str : entry.getValue()) {
appendConceptValue(concept,
field.getName(), str, XML_LANG,
entry.getKey());
}
}
}
}
}
List<Concept> conceptList = rdf.getConceptList() != null ? rdf
.getConceptList() : new ArrayList<Concept>();
conceptList.add(concept);
rdf.setConceptList(conceptList);
try {
if (StringUtils.isNotBlank(entity.getOriginalField())) {
europeanaProxy = OriginalField.getOriginalField(
entity.getOriginalField()).appendField(
europeanaProxy, concept.getAbout());
}
} catch (IllegalArgumentException e) {
log.log(Level.SEVERE,
"Exception generated appending the skos:Concept original Field. "
+ e.getMessage() + ".");
}
}
} else if (StringUtils.equals(entity.getClassName(), "Timespan")) {
TimeSpanType ts = new TimeSpanType();
List<Field> fields = entity.getFields();
if (fields != null && fields.size() > 0) {
for (Field field : fields) {
if (StringUtils.equalsIgnoreCase(field.getName(),
"edm_timespan")) {
ts.setAbout(field
.getValues()
.get(field.getValues().keySet().iterator()
.next()).get(0));
} else {
for (Entry<String, List<String>> entry : field
.getValues().entrySet()) {
for (String str : entry.getValue()) {
appendValue(TimeSpanType.class, ts,
field.getName(), str, XML_LANG,
entry.getKey());
}
}
}
}
List<TimeSpanType> timespans = rdf.getTimeSpanList() != null ? rdf
.getTimeSpanList() : new ArrayList<TimeSpanType>();
timespans.add(ts);
rdf.setTimeSpanList(timespans);
try {
if (StringUtils.isNotBlank(entity.getOriginalField())) {
europeanaProxy = OriginalField.getOriginalField(
entity.getOriginalField()).appendField(
europeanaProxy, ts.getAbout());
}
} catch (IllegalArgumentException e) {
log.log(Level.SEVERE,
"Exception generated appending the edm:Timespan original Field. "
+ e.getMessage() + ".");
}
}
} else if (StringUtils.equals(entity.getClassName(), "Agent")) {
AgentType ts = new AgentType();
List<Field> fields = entity.getFields();
if (fields != null && fields.size() > 0) {
for (Field field : fields) {
if (StringUtils.equalsIgnoreCase(field.getName(),
"edm_agent")) {
ts.setAbout(field
.getValues()
.get(field.getValues().keySet().iterator()
.next()).get(0));
} else {
for (Entry<String, List<String>> entry : field
.getValues().entrySet()) {
for (String str : entry.getValue()) {
appendValue(AgentType.class, ts,
field.getName(), str, XML_LANG,
entry.getKey());
}
}
}
}
List<AgentType> agents = rdf.getAgentList() != null ? rdf
.getAgentList() : new ArrayList<AgentType>();
agents.add(ts);
rdf.setAgentList(agents);
try {
if (StringUtils.isNotBlank(entity.getOriginalField())) {
europeanaProxy = OriginalField.getOriginalField(
entity.getOriginalField()).appendField(
europeanaProxy, ts.getAbout());
}
} catch (IllegalArgumentException e) {
log.log(Level.SEVERE,
"Exception generated appending the edm:Agent original Field. "
+ e.getMessage() + ".");
}
}
} else {
PlaceType ts = new PlaceType();
List<Field> fields = entity.getFields();
if (fields != null && fields.size() > 0) {
for (Field field : fields) {
if (StringUtils.equalsIgnoreCase(field.getName(),
"edm_place")) {
ts.setAbout(field
.getValues()
.get(field.getValues().keySet().iterator()
.next()).get(0));
} else {
if (field.getValues() != null) {
for (Entry<String, List<String>> entry : field
.getValues().entrySet()) {
for (String str : entry.getValue()) {
appendValue(PlaceType.class, ts,
field.getName(), str, XML_LANG,
entry.getKey());
}
}
}
}
}
List<PlaceType> places = rdf.getPlaceList() != null ? rdf
.getPlaceList() : new ArrayList<PlaceType>();
places.add(ts);
rdf.setPlaceList(places);
try {
if (StringUtils.isNotBlank(entity.getOriginalField())) {
europeanaProxy = OriginalField.getOriginalField(
entity.getOriginalField()).appendField(
europeanaProxy, ts.getAbout());
}
} catch (IllegalArgumentException e) {
log.log(Level.SEVERE,
"Exception generated appending the edm:Place original Field. "
+ e.getMessage() + ".");
}
}
}
}
+ proxyList.remove(index);
proxyList.add(europeanaProxy);
rdf.setProxyList(proxyList);
}
private ProxyType createEuropeanaProxy(RDF rdf) {
ProxyType europeanaProxy = new ProxyType();
EuropeanaProxy prx = new EuropeanaProxy();
prx.setEuropeanaProxy(true);
europeanaProxy.setEuropeanaProxy(prx);
List<String> years = new ArrayList<String>();
for (ProxyType proxy : rdf.getProxyList()) {
years.addAll(new EuropeanaDateUtils().createEuropeanaYears(proxy));
europeanaProxy.setType(proxy.getType());
}
System.out.println("Create EuropeanaProxy years:" + years.size());
List<Year> yearList = new ArrayList<Year>();
for (String year : years) {
Year yearObj = new Year();
LiteralType.Lang lang = new LiteralType.Lang();
lang.setLang("eur");
yearObj.setLang(lang);
yearObj.setString(year);
yearList.add(yearObj);
}
europeanaProxy.setYearList(yearList);
return europeanaProxy;
}
// Clean duplicate contextual entities
private RDF cleanRDF(RDF rdf) {
RDF rdfFinal = new RDF();
List<AgentType> agents = new CopyOnWriteArrayList<AgentType>();
List<TimeSpanType> timespans = new CopyOnWriteArrayList<TimeSpanType>();
List<PlaceType> places = new CopyOnWriteArrayList<PlaceType>();
List<Concept> concepts = new CopyOnWriteArrayList<Concept>();
if (rdf.getAgentList() != null) {
for (AgentType newAgent : rdf.getAgentList()) {
for (AgentType agent : agents) {
if (StringUtils.equals(agent.getAbout(),
newAgent.getAbout())) {
if (agent.getPrefLabelList() != null
&& newAgent.getPrefLabelList() != null) {
if (agent.getPrefLabelList().size() <= newAgent
.getPrefLabelList().size()) {
agents.remove(agent);
}
}
}
}
agents.add(newAgent);
}
rdfFinal.setAgentList(agents);
}
if (rdf.getConceptList() != null) {
for (Concept newConcept : rdf.getConceptList()) {
for (Concept concept : concepts) {
if (StringUtils.equals(concept.getAbout(),
newConcept.getAbout())) {
if (concept.getChoiceList() != null
&& newConcept.getChoiceList() != null) {
if (concept.getChoiceList().size() <= newConcept
.getChoiceList().size()) {
concepts.remove(concept);
}
}
}
}
concepts.add(newConcept);
}
rdfFinal.setConceptList(concepts);
}
if (rdf.getTimeSpanList() != null) {
for (TimeSpanType newTs : rdf.getTimeSpanList()) {
for (TimeSpanType ts : timespans) {
if (StringUtils.equals(ts.getAbout(), newTs.getAbout())) {
if (newTs.getIsPartOfList() != null
&& ts.getIsPartOfList() != null) {
if (ts.getIsPartOfList().size() <= newTs
.getIsPartOfList().size()) {
timespans.remove(ts);
}
}
}
}
timespans.add(newTs);
}
rdfFinal.setTimeSpanList(timespans);
}
if (rdf.getPlaceList() != null) {
for (PlaceType newPlace : rdf.getPlaceList()) {
for (PlaceType place : places) {
if (StringUtils.equals(place.getAbout(),
newPlace.getAbout())) {
if (place.getPrefLabelList() != null
&& newPlace.getPrefLabelList() != null) {
if (place.getPrefLabelList().size() <= newPlace
.getPrefLabelList().size()) {
places.remove(place);
}
}
}
}
places.add(newPlace);
}
rdfFinal.setPlaceList(places);
}
rdfFinal.setProxyList(rdf.getProxyList());
rdfFinal.setProvidedCHOList(rdf.getProvidedCHOList());
rdfFinal.setAggregationList(rdf.getAggregationList());
rdfFinal.setWebResourceList(rdf.getWebResourceList());
List<WebResourceType> webResources = new ArrayList<WebResourceType>();
for (Aggregation aggr : rdf.getAggregationList()) {
if (aggr.getIsShownAt() != null) {
WebResourceType wr = new WebResourceType();
wr.setAbout(aggr.getIsShownAt().getResource());
webResources.add(wr);
}
if (aggr.getIsShownBy() != null) {
WebResourceType wr = new WebResourceType();
wr.setAbout(aggr.getIsShownBy().getResource());
webResources.add(wr);
}
if (aggr.getObject() != null) {
WebResourceType wr = new WebResourceType();
wr.setAbout(aggr.getObject().getResource());
webResources.add(wr);
}
if (aggr.getHasViewList() != null) {
for (HasView hasView : aggr.getHasViewList()) {
WebResourceType wr = new WebResourceType();
wr.setAbout(hasView.getResource());
webResources.add(wr);
}
}
}
if (webResources.size() > 0) {
if (rdfFinal.getWebResourceList() != null) {
rdfFinal.getWebResourceList().addAll(webResources);
} else {
rdfFinal.setWebResourceList(webResources);
}
}
List<EuropeanaAggregationType> eTypeList = new ArrayList<EuropeanaAggregationType>();
eTypeList.add(createEuropeanaAggregation(rdf));
rdfFinal.setEuropeanaAggregationList(eTypeList);
return rdfFinal;
}
private EuropeanaAggregationType createEuropeanaAggregation(RDF rdf) {
EuropeanaAggregationType europeanaAggregation = null;
if (rdf.getEuropeanaAggregationList() != null
&& rdf.getEuropeanaAggregationList().size() > 0) {
europeanaAggregation = rdf.getEuropeanaAggregationList().get(0);
} else {
europeanaAggregation = new EuropeanaAggregationType();
}
ProvidedCHOType cho = rdf.getProvidedCHOList().get(0);
europeanaAggregation
.setAbout("/aggregation/europeana" + cho.getAbout());
LandingPage lp = new LandingPage();
lp.setResource(PORTALURL + cho.getAbout() + SUFFIX);
europeanaAggregation.setLandingPage(lp);
Country countryType = new Country();
countryType
.setCountry(europeanaAggregation.getCountry() != null ? europeanaAggregation
.getCountry().getCountry() : CountryCodes.EUROPE);
europeanaAggregation.setCountry(countryType);
Creator creatorType = new Creator();
creatorType.setString("Europeana");
europeanaAggregation.setCreator(creatorType);
Language1 languageType = new Language1();
languageType
.setLanguage(europeanaAggregation.getLanguage() != null ? europeanaAggregation
.getLanguage().getLanguage() : LanguageCodes.EN);
europeanaAggregation.setLanguage(languageType);
Rights1 rightsType = new Rights1();
if (europeanaAggregation.getRights() != null) {
rightsType.setResource(europeanaAggregation.getRights()
.getResource());
} else {
Resource res = new Resource();
res.setResource("http://creativecommons.org/licenses/by-sa/3.0/");
rightsType.setResource(res);
}
europeanaAggregation.setRights(rightsType);
AggregatedCHO aggrCHO = new AggregatedCHO();
aggrCHO.setResource("/item" + cho.getAbout());
europeanaAggregation.setAggregatedCHO(aggrCHO);
return europeanaAggregation;
}
public HttpSolrServer getSolrServer() {
return solrServer;
}
public void setSolrServer(HttpSolrServer solrServer) {
EnrichmentPlugin.solrServer = solrServer;
}
public void setSugarCrmService(SugarCrmService sugarCrmService) {
EnrichmentPlugin.sugarCrmService = sugarCrmService;
}
public String getEuropeanaID() {
return europeanaID;
}
public void setEuropeanaID(String europeanaID) {
EnrichmentPlugin.europeanaID = europeanaID;
}
public int getRecords() {
return recordNumber;
}
public String getRepository() {
return repository;
}
public void setRepository(String repository) {
EnrichmentPlugin.repository = repository;
}
public String getCollections() {
return collections;
}
public void setCollections(String collections) {
EnrichmentPlugin.collections = collections;
}
public SugarCrmService getSugarCrmService() {
return sugarCrmService;
}
public String getMongoDB() {
return mongoDB;
}
public void setMongoDB(String mongoDB) {
EnrichmentPlugin.mongoDB = mongoDB;
}
public String getMongoHost() {
return mongoHost;
}
public void setMongoHost(String mongoHost) {
EnrichmentPlugin.mongoHost = mongoHost;
}
public String getMongoPort() {
return mongoPort;
}
public void setMongoPort(String mongoPort) {
EnrichmentPlugin.mongoPort = mongoPort;
}
public String getSolrUrl() {
return solrUrl;
}
public void setSolrUrl(String solrUrl) {
EnrichmentPlugin.solrUrl = solrUrl;
}
public String getSolrCore() {
return solrCore;
}
public void setSolrCore(String solrCore) {
EnrichmentPlugin.solrCore = solrCore;
}
public EnrichmentService getEnrichmentService() {
return enrichmentService;
}
public void setEnrichmentService(EnrichmentService enrichmentService) {
EnrichmentPlugin.enrichmentService = enrichmentService;
}
// check if the hash of the record exists
// append the rest of the contextual entities
@SuppressWarnings({ "unchecked", "rawtypes" })
private <T> T appendValue(Class<T> clazz, T obj, String edmLabel,
String val, String edmAttr, String valAttr)
throws SecurityException, NoSuchMethodException,
IllegalArgumentException, IllegalAccessException,
InvocationTargetException {
RdfMethod RDF = null;
for (RdfMethod rdfMethod : RdfMethod.values()) {
if (StringUtils.equals(rdfMethod.getSolrField(), edmLabel)) {
RDF = rdfMethod;
}
}
//
if (RDF != null) {
if (RDF.getMethodName().endsWith("List")) {
Method mthd = clazz.getMethod(RDF.getMethodName());
List lst = mthd.invoke(obj) != null ? (ArrayList) mthd
.invoke(obj) : new ArrayList();
if (RDF.getClazz().getSuperclass()
.isAssignableFrom(ResourceType.class)) {
ResourceType rs = new ResourceType();
rs.setResource(val);
lst.add(RDF.returnObject(RDF.getClazz(), rs));
} else if (RDF.getClazz().getSuperclass()
.isAssignableFrom(ResourceOrLiteralType.class)) {
ResourceOrLiteralType rs = new ResourceOrLiteralType();
if (isURI(val)) {
Resource res = new Resource();
res.setResource(val);
rs.setResource(res);
} else {
rs.setString(val);
}
Lang lang = new Lang();
if (edmAttr != null
&& StringUtils.equals(
StringUtils.split(edmAttr, "@")[1],
"xml:lang")) {
lang.setLang(StringUtils.isEmpty(valAttr) ? "def"
: valAttr);
} else {
lang.setLang("def");
}
rs.setLang(lang);
lst.add(RDF.returnObject(RDF.getClazz(), rs));
} else if (RDF.getClazz().getSuperclass()
.isAssignableFrom(LiteralType.class)) {
LiteralType rs = new LiteralType();
rs.setString(val);
LiteralType.Lang lang = new LiteralType.Lang();
if (edmAttr != null
&& StringUtils.equals(
StringUtils.split(edmAttr, "@")[1],
"xml:lang")) {
lang.setLang(StringUtils.isEmpty(valAttr) ? "def"
: valAttr);
} else {
lang.setLang("def");
}
rs.setLang(lang);
lst.add(RDF.returnObject(RDF.getClazz(), rs));
}
Class<?>[] cls = new Class<?>[1];
cls[0] = List.class;
Method method = obj.getClass().getMethod(
StringUtils.replace(RDF.getMethodName(), "get", "set"),
cls);
method.invoke(obj, lst);
} else {
if (RDF.getClazz().isAssignableFrom(ResourceType.class)) {
ResourceType rs = new ResourceType();
rs.setResource(val);
Class<?>[] cls = new Class<?>[1];
cls[0] = RDF.getClazz();
Method method = obj.getClass().getMethod(
StringUtils.replace(RDF.getMethodName(), "get",
"set"), cls);
method.invoke(obj, RDF.returnObject(RDF.getClazz(), rs));
} else if (RDF.getClazz().isAssignableFrom(LiteralType.class)) {
LiteralType rs = new LiteralType();
rs.setString(val);
LiteralType.Lang lang = new LiteralType.Lang();
if (edmAttr != null
&& StringUtils.equals(
StringUtils.split(edmAttr, "@")[1],
"xml:lang")) {
lang.setLang(StringUtils.isEmpty(valAttr) ? "def"
: valAttr);
} else {
lang.setLang("def");
}
rs.setLang(lang);
Class<?>[] cls = new Class<?>[1];
cls[0] = RDF.getClazz();
Method method = obj.getClass().getMethod(
StringUtils.replace(RDF.getMethodName(), "get",
"set"), cls);
method.invoke(obj, RDF.returnObject(RDF.getClazz(), rs));
} else if (RDF.getClazz().isAssignableFrom(
ResourceOrLiteralType.class)) {
ResourceOrLiteralType rs = new ResourceOrLiteralType();
if (isURI(val)) {
Resource res = new Resource();
res.setResource(val);
rs.setResource(res);
} else {
rs.setString(val);
}
Lang lang = new Lang();
if (edmAttr != null
&& StringUtils.equals(
StringUtils.split(edmAttr, "@")[1],
"xml:lang")) {
lang.setLang(StringUtils.isEmpty(valAttr) ? "def"
: valAttr);
} else {
lang.setLang("def");
}
rs.setLang(lang);
Class<?>[] cls = new Class<?>[1];
cls[0] = clazz;
Method method = obj.getClass().getMethod(
StringUtils.replace(RDF.getMethodName(), "get",
"set"), cls);
method.invoke(obj, RDF.returnObject(RDF.getClazz(), rs));
} else if (RDF.getClazz().isAssignableFrom(_Long.class)) {
Float rs = Float.parseFloat(val);
_Long lng = new _Long();
lng.setLong(rs);
((PlaceType) obj).setLong(lng);
} else if (RDF.getClazz().isAssignableFrom(Lat.class)) {
Float rs = Float.parseFloat(val);
Lat lng = new Lat();
lng.setLat(rs);
((PlaceType) obj).setLat(lng);
} else if (RDF.getClazz().isAssignableFrom(Alt.class)) {
Float rs = Float.parseFloat(val);
Alt lng = new Alt();
lng.setAlt(rs);
((PlaceType) obj).setAlt(lng);
}
}
}
//
return obj;
}
// Append concepts
private Concept appendConceptValue(Concept concept, String edmLabel,
String val, String edmAttr, String valAttr)
throws SecurityException, NoSuchMethodException,
IllegalArgumentException, IllegalAccessException,
InvocationTargetException {
RdfMethod RDF = null;
for (RdfMethod rdfMethod : RdfMethod.values()) {
if (StringUtils.equals(rdfMethod.getSolrField(), edmLabel)) {
RDF = rdfMethod;
break;
}
}
List<Concept.Choice> lst = concept.getChoiceList() != null ? concept
.getChoiceList() : new ArrayList<Concept.Choice>();
if (RDF.getClazz().getSuperclass().isAssignableFrom(ResourceType.class)) {
ResourceType obj = new ResourceType();
obj.setResource(val);
Class<?>[] cls = new Class<?>[1];
cls[0] = RDF.getClazz();
Concept.Choice choice = new Concept.Choice();
Method method = choice.getClass()
.getMethod(
StringUtils.replace(RDF.getMethodName(), "get",
"set"), cls);
method.invoke(choice, RDF.returnObject(RDF.getClazz(), obj));
lst.add(choice);
} else if (RDF.getClazz().getSuperclass()
.isAssignableFrom(ResourceOrLiteralType.class)) {
ResourceOrLiteralType obj = new ResourceOrLiteralType();
if (isURI(val)) {
Resource res = new Resource();
res.setResource(val);
obj.setResource(res);
} else {
obj.setString(val);
}
Lang lang = new Lang();
if (edmAttr != null
&& StringUtils.equals(StringUtils.split(edmAttr, "@")[1],
"xml:lang")) {
lang.setLang(valAttr);
} else {
lang.setLang("def");
}
obj.setLang(lang);
Class<?>[] cls = new Class<?>[1];
cls[0] = RDF.getClazz();
Concept.Choice choice = new Concept.Choice();
Method method = choice.getClass()
.getMethod(
StringUtils.replace(RDF.getMethodName(), "get",
"set"), cls);
method.invoke(choice, RDF.returnObject(RDF.getClazz(), obj));
lst.add(choice);
} else if (RDF.getClazz().getSuperclass()
.isAssignableFrom(LiteralType.class)) {
LiteralType obj = new LiteralType();
obj.setString(val);
LiteralType.Lang lang = new LiteralType.Lang();
if (edmAttr != null) {
lang.setLang(valAttr);
} else {
lang.setLang("def");
}
obj.setLang(lang);
Class<?>[] cls = new Class<?>[1];
cls[0] = RDF.getClazz();
Concept.Choice choice = new Concept.Choice();
Method method = choice.getClass()
.getMethod(
StringUtils.replace(RDF.getMethodName(), "get",
"set"), cls);
method.invoke(choice, RDF.returnObject(RDF.getClazz(), obj));
lst.add(choice);
}
concept.setChoiceList(lst);
return concept;
}
/**
* Check if a String is a URI
*
* @param uri
* @return
*/
private static boolean isURI(String uri) {
try {
new URL(uri);
return true;
} catch (MalformedURLException e) {
return false;
}
}
private static ProxyImpl getProviderProxy(FullBeanImpl fbean) {
for (ProxyImpl proxy : fbean.getProxies()) {
if (!proxy.isEuropeanaProxy()) {
return proxy;
}
}
return null;
}
}
| false | true | private void mergeEntities(RDF rdf, List<Entity> entities)
throws SecurityException, IllegalArgumentException,
NoSuchMethodException, IllegalAccessException,
InvocationTargetException {
ProxyType europeanaProxy = null;
ProvidedCHOType cho = null;
List<ProvidedCHOType> providedChoList = rdf.getProvidedCHOList();
cho = providedChoList.get(0);
List<ProxyType> proxyList = rdf.getProxyList();
for (ProxyType proxy : proxyList) {
if (proxy.getEuropeanaProxy() != null
&& proxy.getEuropeanaProxy().isEuropeanaProxy()) {
europeanaProxy = proxy;
} else {
if (!StringUtils
.startsWith(proxy.getAbout(), "/proxy/provider")) {
proxy.setAbout("/proxy/provider" + proxy.getAbout());
}
}
}
if (europeanaProxy == null) {
europeanaProxy = createEuropeanaProxy(rdf);
}
europeanaProxy.setAbout("/proxy/europeana" + cho.getAbout());
ProxyFor pf = new ProxyFor();
pf.setResource("/item" + cho.getAbout());
europeanaProxy.setProxyFor(pf);
List<ProxyIn> pinList = new ArrayList<ProxyIn>();
ProxyIn pin = new ProxyIn();
pin.setResource("/aggregation/europeana" + cho.getAbout());
pinList.add(pin);
europeanaProxy.setProxyInList(pinList);
for (Entity entity : entities) {
if (StringUtils.equals(entity.getClassName(), "Concept")) {
Concept concept = new Concept();
List<Field> fields = entity.getFields();
if (fields != null && fields.size() > 0) {
for (Field field : fields) {
if (StringUtils.equalsIgnoreCase(field.getName(),
"skos_concept")) {
concept.setAbout(field
.getValues()
.get(field.getValues().keySet().iterator()
.next()).get(0));
} else {
if (field.getValues() != null) {
for (Entry<String, List<String>> entry : field
.getValues().entrySet()) {
for (String str : entry.getValue()) {
appendConceptValue(concept,
field.getName(), str, XML_LANG,
entry.getKey());
}
}
}
}
}
List<Concept> conceptList = rdf.getConceptList() != null ? rdf
.getConceptList() : new ArrayList<Concept>();
conceptList.add(concept);
rdf.setConceptList(conceptList);
try {
if (StringUtils.isNotBlank(entity.getOriginalField())) {
europeanaProxy = OriginalField.getOriginalField(
entity.getOriginalField()).appendField(
europeanaProxy, concept.getAbout());
}
} catch (IllegalArgumentException e) {
log.log(Level.SEVERE,
"Exception generated appending the skos:Concept original Field. "
+ e.getMessage() + ".");
}
}
} else if (StringUtils.equals(entity.getClassName(), "Timespan")) {
TimeSpanType ts = new TimeSpanType();
List<Field> fields = entity.getFields();
if (fields != null && fields.size() > 0) {
for (Field field : fields) {
if (StringUtils.equalsIgnoreCase(field.getName(),
"edm_timespan")) {
ts.setAbout(field
.getValues()
.get(field.getValues().keySet().iterator()
.next()).get(0));
} else {
for (Entry<String, List<String>> entry : field
.getValues().entrySet()) {
for (String str : entry.getValue()) {
appendValue(TimeSpanType.class, ts,
field.getName(), str, XML_LANG,
entry.getKey());
}
}
}
}
List<TimeSpanType> timespans = rdf.getTimeSpanList() != null ? rdf
.getTimeSpanList() : new ArrayList<TimeSpanType>();
timespans.add(ts);
rdf.setTimeSpanList(timespans);
try {
if (StringUtils.isNotBlank(entity.getOriginalField())) {
europeanaProxy = OriginalField.getOriginalField(
entity.getOriginalField()).appendField(
europeanaProxy, ts.getAbout());
}
} catch (IllegalArgumentException e) {
log.log(Level.SEVERE,
"Exception generated appending the edm:Timespan original Field. "
+ e.getMessage() + ".");
}
}
} else if (StringUtils.equals(entity.getClassName(), "Agent")) {
AgentType ts = new AgentType();
List<Field> fields = entity.getFields();
if (fields != null && fields.size() > 0) {
for (Field field : fields) {
if (StringUtils.equalsIgnoreCase(field.getName(),
"edm_agent")) {
ts.setAbout(field
.getValues()
.get(field.getValues().keySet().iterator()
.next()).get(0));
} else {
for (Entry<String, List<String>> entry : field
.getValues().entrySet()) {
for (String str : entry.getValue()) {
appendValue(AgentType.class, ts,
field.getName(), str, XML_LANG,
entry.getKey());
}
}
}
}
List<AgentType> agents = rdf.getAgentList() != null ? rdf
.getAgentList() : new ArrayList<AgentType>();
agents.add(ts);
rdf.setAgentList(agents);
try {
if (StringUtils.isNotBlank(entity.getOriginalField())) {
europeanaProxy = OriginalField.getOriginalField(
entity.getOriginalField()).appendField(
europeanaProxy, ts.getAbout());
}
} catch (IllegalArgumentException e) {
log.log(Level.SEVERE,
"Exception generated appending the edm:Agent original Field. "
+ e.getMessage() + ".");
}
}
} else {
PlaceType ts = new PlaceType();
List<Field> fields = entity.getFields();
if (fields != null && fields.size() > 0) {
for (Field field : fields) {
if (StringUtils.equalsIgnoreCase(field.getName(),
"edm_place")) {
ts.setAbout(field
.getValues()
.get(field.getValues().keySet().iterator()
.next()).get(0));
} else {
if (field.getValues() != null) {
for (Entry<String, List<String>> entry : field
.getValues().entrySet()) {
for (String str : entry.getValue()) {
appendValue(PlaceType.class, ts,
field.getName(), str, XML_LANG,
entry.getKey());
}
}
}
}
}
List<PlaceType> places = rdf.getPlaceList() != null ? rdf
.getPlaceList() : new ArrayList<PlaceType>();
places.add(ts);
rdf.setPlaceList(places);
try {
if (StringUtils.isNotBlank(entity.getOriginalField())) {
europeanaProxy = OriginalField.getOriginalField(
entity.getOriginalField()).appendField(
europeanaProxy, ts.getAbout());
}
} catch (IllegalArgumentException e) {
log.log(Level.SEVERE,
"Exception generated appending the edm:Place original Field. "
+ e.getMessage() + ".");
}
}
}
}
proxyList.add(europeanaProxy);
rdf.setProxyList(proxyList);
}
| private void mergeEntities(RDF rdf, List<Entity> entities)
throws SecurityException, IllegalArgumentException,
NoSuchMethodException, IllegalAccessException,
InvocationTargetException {
ProxyType europeanaProxy = null;
ProvidedCHOType cho = null;
List<ProvidedCHOType> providedChoList = rdf.getProvidedCHOList();
cho = providedChoList.get(0);
List<ProxyType> proxyList = rdf.getProxyList();
int i = 0;
int index=0;
for (ProxyType proxy : proxyList) {
if (proxy.getEuropeanaProxy() != null
&& proxy.getEuropeanaProxy().isEuropeanaProxy()) {
europeanaProxy = proxy;
index=i;
} else {
if (!StringUtils
.startsWith(proxy.getAbout(), "/proxy/provider")) {
proxy.setAbout("/proxy/provider" + proxy.getAbout());
}
}
i++;
}
if (europeanaProxy == null) {
europeanaProxy = createEuropeanaProxy(rdf);
}
europeanaProxy.setAbout("/proxy/europeana" + cho.getAbout());
ProxyFor pf = new ProxyFor();
pf.setResource("/item" + cho.getAbout());
europeanaProxy.setProxyFor(pf);
List<ProxyIn> pinList = new ArrayList<ProxyIn>();
ProxyIn pin = new ProxyIn();
pin.setResource("/aggregation/europeana" + cho.getAbout());
pinList.add(pin);
europeanaProxy.setProxyInList(pinList);
for (Entity entity : entities) {
if (StringUtils.equals(entity.getClassName(), "Concept")) {
Concept concept = new Concept();
List<Field> fields = entity.getFields();
if (fields != null && fields.size() > 0) {
for (Field field : fields) {
if (StringUtils.equalsIgnoreCase(field.getName(),
"skos_concept")) {
concept.setAbout(field
.getValues()
.get(field.getValues().keySet().iterator()
.next()).get(0));
} else {
if (field.getValues() != null) {
for (Entry<String, List<String>> entry : field
.getValues().entrySet()) {
for (String str : entry.getValue()) {
appendConceptValue(concept,
field.getName(), str, XML_LANG,
entry.getKey());
}
}
}
}
}
List<Concept> conceptList = rdf.getConceptList() != null ? rdf
.getConceptList() : new ArrayList<Concept>();
conceptList.add(concept);
rdf.setConceptList(conceptList);
try {
if (StringUtils.isNotBlank(entity.getOriginalField())) {
europeanaProxy = OriginalField.getOriginalField(
entity.getOriginalField()).appendField(
europeanaProxy, concept.getAbout());
}
} catch (IllegalArgumentException e) {
log.log(Level.SEVERE,
"Exception generated appending the skos:Concept original Field. "
+ e.getMessage() + ".");
}
}
} else if (StringUtils.equals(entity.getClassName(), "Timespan")) {
TimeSpanType ts = new TimeSpanType();
List<Field> fields = entity.getFields();
if (fields != null && fields.size() > 0) {
for (Field field : fields) {
if (StringUtils.equalsIgnoreCase(field.getName(),
"edm_timespan")) {
ts.setAbout(field
.getValues()
.get(field.getValues().keySet().iterator()
.next()).get(0));
} else {
for (Entry<String, List<String>> entry : field
.getValues().entrySet()) {
for (String str : entry.getValue()) {
appendValue(TimeSpanType.class, ts,
field.getName(), str, XML_LANG,
entry.getKey());
}
}
}
}
List<TimeSpanType> timespans = rdf.getTimeSpanList() != null ? rdf
.getTimeSpanList() : new ArrayList<TimeSpanType>();
timespans.add(ts);
rdf.setTimeSpanList(timespans);
try {
if (StringUtils.isNotBlank(entity.getOriginalField())) {
europeanaProxy = OriginalField.getOriginalField(
entity.getOriginalField()).appendField(
europeanaProxy, ts.getAbout());
}
} catch (IllegalArgumentException e) {
log.log(Level.SEVERE,
"Exception generated appending the edm:Timespan original Field. "
+ e.getMessage() + ".");
}
}
} else if (StringUtils.equals(entity.getClassName(), "Agent")) {
AgentType ts = new AgentType();
List<Field> fields = entity.getFields();
if (fields != null && fields.size() > 0) {
for (Field field : fields) {
if (StringUtils.equalsIgnoreCase(field.getName(),
"edm_agent")) {
ts.setAbout(field
.getValues()
.get(field.getValues().keySet().iterator()
.next()).get(0));
} else {
for (Entry<String, List<String>> entry : field
.getValues().entrySet()) {
for (String str : entry.getValue()) {
appendValue(AgentType.class, ts,
field.getName(), str, XML_LANG,
entry.getKey());
}
}
}
}
List<AgentType> agents = rdf.getAgentList() != null ? rdf
.getAgentList() : new ArrayList<AgentType>();
agents.add(ts);
rdf.setAgentList(agents);
try {
if (StringUtils.isNotBlank(entity.getOriginalField())) {
europeanaProxy = OriginalField.getOriginalField(
entity.getOriginalField()).appendField(
europeanaProxy, ts.getAbout());
}
} catch (IllegalArgumentException e) {
log.log(Level.SEVERE,
"Exception generated appending the edm:Agent original Field. "
+ e.getMessage() + ".");
}
}
} else {
PlaceType ts = new PlaceType();
List<Field> fields = entity.getFields();
if (fields != null && fields.size() > 0) {
for (Field field : fields) {
if (StringUtils.equalsIgnoreCase(field.getName(),
"edm_place")) {
ts.setAbout(field
.getValues()
.get(field.getValues().keySet().iterator()
.next()).get(0));
} else {
if (field.getValues() != null) {
for (Entry<String, List<String>> entry : field
.getValues().entrySet()) {
for (String str : entry.getValue()) {
appendValue(PlaceType.class, ts,
field.getName(), str, XML_LANG,
entry.getKey());
}
}
}
}
}
List<PlaceType> places = rdf.getPlaceList() != null ? rdf
.getPlaceList() : new ArrayList<PlaceType>();
places.add(ts);
rdf.setPlaceList(places);
try {
if (StringUtils.isNotBlank(entity.getOriginalField())) {
europeanaProxy = OriginalField.getOriginalField(
entity.getOriginalField()).appendField(
europeanaProxy, ts.getAbout());
}
} catch (IllegalArgumentException e) {
log.log(Level.SEVERE,
"Exception generated appending the edm:Place original Field. "
+ e.getMessage() + ".");
}
}
}
}
proxyList.remove(index);
proxyList.add(europeanaProxy);
rdf.setProxyList(proxyList);
}
|
diff --git a/ui/webui/src/eu/sqooss/webui/Functions.java b/ui/webui/src/eu/sqooss/webui/Functions.java
index 24a8ef39..aed7637b 100644
--- a/ui/webui/src/eu/sqooss/webui/Functions.java
+++ b/ui/webui/src/eu/sqooss/webui/Functions.java
@@ -1,20 +1,20 @@
package eu.sqooss.webui;
public class Functions {
public static final String NOT_YET_EVALUATED =
"This project has not yet been evaluated!";
public static String dude() {
- return "<h1>Duuuuuuude!</h1>";
+ return "<h1>Boogers!</h1>";
}
public static String error(String msg) {
return "<strong><font color=\"red\">" + msg + "</font></strong>";
}
public static String debug(String msg) {
return "<strong><font color=\"orange\">" + msg + "</font></strong>";
}
}
| true | true | public static String dude() {
return "<h1>Duuuuuuude!</h1>";
}
| public static String dude() {
return "<h1>Boogers!</h1>";
}
|
diff --git a/any23-core/src/main/java/org/deri/any23/servlet/Any23Server.java b/any23-core/src/main/java/org/deri/any23/servlet/Any23Server.java
index e7a721df..97804daf 100644
--- a/any23-core/src/main/java/org/deri/any23/servlet/Any23Server.java
+++ b/any23-core/src/main/java/org/deri/any23/servlet/Any23Server.java
@@ -1,50 +1,50 @@
/*
* Copyright 2008-2010 Digital Enterprise Research Institute (DERI)
*
* 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.deri.any23.servlet;
import org.mortbay.jetty.Server;
import org.mortbay.jetty.webapp.WebAppContext;
import java.io.File;
/**
* A simple server that uses <i>Jetty</i> to launch the Any23 Servlet.
* Starts up on port 8080.
*
* @author Richard Cyganiak
*/
public class Any23Server {
/**
* Runs the {@link org.deri.any23.servlet.Servlet} instance on the local <code>8080</code> port.
*
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
final String webapp = args.length > 0 ? args[0] : "./webapp";
if (!new File(webapp).isDirectory()) {
- System.err.println("webapp directory not found. Server must be launched from the any23 directory.");
+ System.err.println("webapp directory not found. Server must be launched from any23's /bin directory.");
System.exit(1);
}
Server server = new Server(8080);
WebAppContext app = new WebAppContext(server, webapp, "/");
server.setHandler(app);
server.start();
}
}
| true | true | public static void main(String[] args) throws Exception {
final String webapp = args.length > 0 ? args[0] : "./webapp";
if (!new File(webapp).isDirectory()) {
System.err.println("webapp directory not found. Server must be launched from the any23 directory.");
System.exit(1);
}
Server server = new Server(8080);
WebAppContext app = new WebAppContext(server, webapp, "/");
server.setHandler(app);
server.start();
}
| public static void main(String[] args) throws Exception {
final String webapp = args.length > 0 ? args[0] : "./webapp";
if (!new File(webapp).isDirectory()) {
System.err.println("webapp directory not found. Server must be launched from any23's /bin directory.");
System.exit(1);
}
Server server = new Server(8080);
WebAppContext app = new WebAppContext(server, webapp, "/");
server.setHandler(app);
server.start();
}
|
diff --git a/src/com/turbonips/troglodytes/states/OptionState.java b/src/com/turbonips/troglodytes/states/OptionState.java
index 4dcafc8..50fb7c9 100644
--- a/src/com/turbonips/troglodytes/states/OptionState.java
+++ b/src/com/turbonips/troglodytes/states/OptionState.java
@@ -1,257 +1,257 @@
package com.turbonips.troglodytes.states;
import java.awt.Font;
import org.newdawn.slick.Color;
import org.newdawn.slick.GameContainer;
import org.newdawn.slick.Graphics;
import org.newdawn.slick.SlickException;
import org.newdawn.slick.UnicodeFont;
import org.newdawn.slick.font.effects.ColorEffect;
import org.newdawn.slick.state.StateBasedGame;
public class OptionState extends BaseMenuState {
public static final int ID = 2;
private UnicodeFont buttonFont;
private String windowedSt = "Windowed";
private int windowedX, windowedY;
private String fullscreenSt = "Fullscreen";
private int fullscreenX, fullscreenY;
private String backSt = "Back";
private int backX, backY;
private String musicSt = "Music:";
private int musicX, musicY;
private String musicOnSt = "On";
private int musicOnX, musicOnY;
private String musicOffSt = "Off";
private int musicOffX, musicOffY;
private String soundSt = "Sound:";
private int soundX, soundY;
private String soundOnSt = "On";
private int soundOnX, soundOnY;
private String soundOffSt = "Off";
private int soundOffX, soundOffY;
String titleSt = "Options";
int titleX, titleY;
private StateBasedGame game;
private GameContainer container;
enum SelectedState {NONE,
BACK,
WINDOWED,
FULLSCREEN,
MUSIC_ON,
MUSIC_OFF,
SOUND_ON,
SOUND_OFF};
SelectedState selectedState = SelectedState.NONE;
private UnicodeFont titleFont;
@Override
public void init(GameContainer container, StateBasedGame game)
throws SlickException {
super.init(container, game);
String fontName = "Palatino";
buttonFont = new UnicodeFont (new Font(fontName, Font.BOLD, 25));
buttonFont.getEffects().add(new ColorEffect(java.awt.Color.white));
titleFont = new UnicodeFont (new Font(fontName, Font.BOLD, 70));
titleFont.getEffects().add(new ColorEffect(java.awt.Color.white));
int windowedWidth = buttonFont.getWidth(windowedSt);
int fullWidth = buttonFont.getWidth(fullscreenSt);
int fullHeight = buttonFont.getHeight(fullscreenSt);
int backWidth = buttonFont.getWidth(backSt);
int musicWidth = buttonFont.getWidth(musicSt);
int musicHeight = buttonFont.getHeight(musicSt);
int onWidth = buttonFont.getWidth(musicOnSt);
int offWidth = buttonFont.getWidth(musicOffSt);
int soundWidth = buttonFont.getWidth(soundSt);
int soundHeight = buttonFont.getHeight(soundSt);
int titleWidth = titleFont.getWidth(titleSt);
int titleHeight = titleFont.getHeight(titleSt);
titleX = container.getWidth()/2-titleWidth/2;
titleY = container.getHeight()/4;
windowedX = container.getWidth()/2-(windowedWidth+fullWidth)/2 - 5;
windowedY = titleY + titleHeight + 40;
fullscreenX = container.getWidth()/2-(windowedWidth+fullWidth)/2 + windowedWidth + 5;
fullscreenY = titleY + titleHeight + 40;
musicX = container.getWidth()/2-(musicWidth+onWidth+offWidth+20)/2;
musicY = fullscreenY + fullHeight+20;
musicOnX = musicX + musicWidth + 10;
musicOnY = musicY;
musicOffX = musicOnX + onWidth + 10;
musicOffY = musicY;
soundX = container.getWidth()/2-(soundWidth+onWidth+offWidth+20)/2;
soundY = musicY + musicHeight + 20;
soundOnX = soundX + soundWidth + 10;
soundOnY = soundY;
soundOffX = soundOnX + onWidth + 10;
soundOffY = soundY;
backX = container.getWidth()/2-(backWidth/2);
backY = soundY + soundHeight + 20;
this.game = game;
this.container = container;
}
@Override
public void render(GameContainer container, StateBasedGame game, Graphics g)
throws SlickException {
super.render(container, game, g);
Color WHITE = new Color(255,255,255);
Color ORANGE = new Color(255,127,0);
titleFont.drawString(titleX, titleY, titleSt, WHITE);
// Draw the windowed button
if (selectedState == SelectedState.WINDOWED && container.isFullscreen()) {
buttonFont.drawString(windowedX, windowedY, windowedSt, ORANGE);
} else {
buttonFont.drawString(windowedX, windowedY, windowedSt, WHITE);
}
if (!container.isFullscreen())
- g.drawRect(windowedX-2, windowedY-2, buttonFont.getWidth(windowedSt)+4, buttonFont.getHeight(windowedSt)+4);
+ g.drawRect(windowedX-2, windowedY, buttonFont.getWidth(windowedSt)+4, buttonFont.getHeight(windowedSt)+4);
// Draw the fullscreen button
if (selectedState == SelectedState.FULLSCREEN && !container.isFullscreen()) {
buttonFont.drawString(fullscreenX, fullscreenY, fullscreenSt, ORANGE);
} else {
buttonFont.drawString(fullscreenX, fullscreenY, fullscreenSt, WHITE);
}
if (container.isFullscreen())
- g.drawRect(fullscreenX-2, fullscreenY-2, buttonFont.getWidth(fullscreenSt)+4, buttonFont.getHeight(fullscreenSt)+4);
+ g.drawRect(fullscreenX-2, fullscreenY, buttonFont.getWidth(fullscreenSt)+4, buttonFont.getHeight(fullscreenSt)+4);
// Draw the music label
buttonFont.drawString(musicX, musicY, musicSt, WHITE);
// Draw the music on button
if (selectedState == SelectedState.MUSIC_ON) {
buttonFont.drawString(musicOnX, musicOnY, musicOnSt, ORANGE);
} else {
buttonFont.drawString(musicOnX, musicOnY, musicOnSt, WHITE);
}
// Draw the music off button
if (selectedState == SelectedState.MUSIC_OFF) {
buttonFont.drawString(musicOffX, musicOffY, musicOffSt, ORANGE);
} else {
buttonFont.drawString(musicOffX, musicOffY, musicOffSt, WHITE);
}
// Draw the sound label
buttonFont.drawString(soundX, soundY, soundSt, WHITE);
// Draw the sound on button
if (selectedState == SelectedState.SOUND_ON) {
buttonFont.drawString(soundOnX, soundOnY, soundOnSt, ORANGE);
} else {
buttonFont.drawString(soundOnX, soundOnY, soundOnSt, WHITE);
}
// Draw the sound off button
if (selectedState == SelectedState.SOUND_OFF) {
buttonFont.drawString(soundOffX, soundOffY, soundOffSt, ORANGE);
} else {
buttonFont.drawString(soundOffX, soundOffY, soundOffSt, WHITE);
}
// Draw the back button
if (selectedState == SelectedState.BACK) {
buttonFont.drawString(backX, backY, backSt, ORANGE);
} else {
buttonFont.drawString(backX, backY, backSt, WHITE);
}
buttonFont.loadGlyphs();
titleFont.loadGlyphs();
}
@Override
public void update(GameContainer container, StateBasedGame game, int delta)
throws SlickException {
}
@Override
public void mouseClicked(int button, int x, int y, int clickCount) {
// Back clicked
if (x > backX && x < backX + buttonFont.getWidth(backSt) &&
y > backY && y < backY + buttonFont.getHeight(backSt)) {
game.enterState(MenuState.ID);
}
// Fullscreen clicked
if (x > fullscreenX && x < fullscreenX + buttonFont.getWidth(fullscreenSt) &&
y > fullscreenY && y < fullscreenY + buttonFont.getHeight(fullscreenSt)) {
try {
container.setFullscreen(true);
} catch (Exception ex) { }
}
// Windowed clicked
if (x > windowedX && x < windowedX + buttonFont.getWidth(windowedSt) &&
y > windowedY && y < windowedY + buttonFont.getHeight(windowedSt)) {
try {
container.setFullscreen(false);
} catch (Exception ex) { }
}
selectedState = SelectedState.NONE;
}
@Override
public void mouseMoved(int oldx, int oldy, int newx, int newy) {
selectedState = SelectedState.NONE;
// Back selected
if (newx > backX && newx < backX + buttonFont.getWidth(backSt) &&
newy > backY && newy < backY + buttonFont.getHeight(backSt)) {
selectedState = SelectedState.BACK;
}
// Windowed selected
if (newx > windowedX && newx < windowedX + buttonFont.getWidth(windowedSt) &&
newy > windowedY && newy < windowedY + buttonFont.getHeight(windowedSt)) {
selectedState = SelectedState.WINDOWED;
}
// Fullscreen selected
if (newx > fullscreenX && newx < fullscreenX + buttonFont.getWidth(fullscreenSt) &&
newy > fullscreenY && newy < fullscreenY + buttonFont.getHeight(fullscreenSt)) {
selectedState = SelectedState.FULLSCREEN;
}
// Music on selected
if (newx > musicOnX && newx < musicOnX + buttonFont.getWidth(musicOnSt) &&
newy > musicOnY && newy < musicOnY + buttonFont.getHeight(musicOnSt)) {
selectedState = SelectedState.MUSIC_ON;
}
// Music off selected
if (newx > musicOffX && newx < musicOffX + buttonFont.getWidth(musicOffSt) &&
newy > musicOffY && newy < musicOffY + buttonFont.getHeight(musicOffSt)) {
selectedState = SelectedState.MUSIC_OFF;
}
// Sound on selected
if (newx > soundOnX && newx < soundOnX + buttonFont.getWidth(soundOnSt) &&
newy > soundOnY && newy < soundOnY + buttonFont.getHeight(soundOnSt)) {
selectedState = SelectedState.SOUND_ON;
}
// Sound off selected
if (newx > soundOffX && newx < soundOffX + buttonFont.getWidth(soundOffSt) &&
newy > soundOffY && newy < soundOffY + buttonFont.getHeight(soundOffSt)) {
selectedState = SelectedState.SOUND_OFF;
}
}
@Override
public int getID() {
return ID;
}
}
| false | true | public void render(GameContainer container, StateBasedGame game, Graphics g)
throws SlickException {
super.render(container, game, g);
Color WHITE = new Color(255,255,255);
Color ORANGE = new Color(255,127,0);
titleFont.drawString(titleX, titleY, titleSt, WHITE);
// Draw the windowed button
if (selectedState == SelectedState.WINDOWED && container.isFullscreen()) {
buttonFont.drawString(windowedX, windowedY, windowedSt, ORANGE);
} else {
buttonFont.drawString(windowedX, windowedY, windowedSt, WHITE);
}
if (!container.isFullscreen())
g.drawRect(windowedX-2, windowedY-2, buttonFont.getWidth(windowedSt)+4, buttonFont.getHeight(windowedSt)+4);
// Draw the fullscreen button
if (selectedState == SelectedState.FULLSCREEN && !container.isFullscreen()) {
buttonFont.drawString(fullscreenX, fullscreenY, fullscreenSt, ORANGE);
} else {
buttonFont.drawString(fullscreenX, fullscreenY, fullscreenSt, WHITE);
}
if (container.isFullscreen())
g.drawRect(fullscreenX-2, fullscreenY-2, buttonFont.getWidth(fullscreenSt)+4, buttonFont.getHeight(fullscreenSt)+4);
// Draw the music label
buttonFont.drawString(musicX, musicY, musicSt, WHITE);
// Draw the music on button
if (selectedState == SelectedState.MUSIC_ON) {
buttonFont.drawString(musicOnX, musicOnY, musicOnSt, ORANGE);
} else {
buttonFont.drawString(musicOnX, musicOnY, musicOnSt, WHITE);
}
// Draw the music off button
if (selectedState == SelectedState.MUSIC_OFF) {
buttonFont.drawString(musicOffX, musicOffY, musicOffSt, ORANGE);
} else {
buttonFont.drawString(musicOffX, musicOffY, musicOffSt, WHITE);
}
// Draw the sound label
buttonFont.drawString(soundX, soundY, soundSt, WHITE);
// Draw the sound on button
if (selectedState == SelectedState.SOUND_ON) {
buttonFont.drawString(soundOnX, soundOnY, soundOnSt, ORANGE);
} else {
buttonFont.drawString(soundOnX, soundOnY, soundOnSt, WHITE);
}
// Draw the sound off button
if (selectedState == SelectedState.SOUND_OFF) {
buttonFont.drawString(soundOffX, soundOffY, soundOffSt, ORANGE);
} else {
buttonFont.drawString(soundOffX, soundOffY, soundOffSt, WHITE);
}
// Draw the back button
if (selectedState == SelectedState.BACK) {
buttonFont.drawString(backX, backY, backSt, ORANGE);
} else {
buttonFont.drawString(backX, backY, backSt, WHITE);
}
buttonFont.loadGlyphs();
titleFont.loadGlyphs();
}
| public void render(GameContainer container, StateBasedGame game, Graphics g)
throws SlickException {
super.render(container, game, g);
Color WHITE = new Color(255,255,255);
Color ORANGE = new Color(255,127,0);
titleFont.drawString(titleX, titleY, titleSt, WHITE);
// Draw the windowed button
if (selectedState == SelectedState.WINDOWED && container.isFullscreen()) {
buttonFont.drawString(windowedX, windowedY, windowedSt, ORANGE);
} else {
buttonFont.drawString(windowedX, windowedY, windowedSt, WHITE);
}
if (!container.isFullscreen())
g.drawRect(windowedX-2, windowedY, buttonFont.getWidth(windowedSt)+4, buttonFont.getHeight(windowedSt)+4);
// Draw the fullscreen button
if (selectedState == SelectedState.FULLSCREEN && !container.isFullscreen()) {
buttonFont.drawString(fullscreenX, fullscreenY, fullscreenSt, ORANGE);
} else {
buttonFont.drawString(fullscreenX, fullscreenY, fullscreenSt, WHITE);
}
if (container.isFullscreen())
g.drawRect(fullscreenX-2, fullscreenY, buttonFont.getWidth(fullscreenSt)+4, buttonFont.getHeight(fullscreenSt)+4);
// Draw the music label
buttonFont.drawString(musicX, musicY, musicSt, WHITE);
// Draw the music on button
if (selectedState == SelectedState.MUSIC_ON) {
buttonFont.drawString(musicOnX, musicOnY, musicOnSt, ORANGE);
} else {
buttonFont.drawString(musicOnX, musicOnY, musicOnSt, WHITE);
}
// Draw the music off button
if (selectedState == SelectedState.MUSIC_OFF) {
buttonFont.drawString(musicOffX, musicOffY, musicOffSt, ORANGE);
} else {
buttonFont.drawString(musicOffX, musicOffY, musicOffSt, WHITE);
}
// Draw the sound label
buttonFont.drawString(soundX, soundY, soundSt, WHITE);
// Draw the sound on button
if (selectedState == SelectedState.SOUND_ON) {
buttonFont.drawString(soundOnX, soundOnY, soundOnSt, ORANGE);
} else {
buttonFont.drawString(soundOnX, soundOnY, soundOnSt, WHITE);
}
// Draw the sound off button
if (selectedState == SelectedState.SOUND_OFF) {
buttonFont.drawString(soundOffX, soundOffY, soundOffSt, ORANGE);
} else {
buttonFont.drawString(soundOffX, soundOffY, soundOffSt, WHITE);
}
// Draw the back button
if (selectedState == SelectedState.BACK) {
buttonFont.drawString(backX, backY, backSt, ORANGE);
} else {
buttonFont.drawString(backX, backY, backSt, WHITE);
}
buttonFont.loadGlyphs();
titleFont.loadGlyphs();
}
|
diff --git a/Tupl/src/main/java/org/cojen/tupl/TreeCursor.java b/Tupl/src/main/java/org/cojen/tupl/TreeCursor.java
index f789186e..236e960c 100644
--- a/Tupl/src/main/java/org/cojen/tupl/TreeCursor.java
+++ b/Tupl/src/main/java/org/cojen/tupl/TreeCursor.java
@@ -1,3468 +1,3473 @@
/*
* Copyright 2011-2012 Brian S O'Neill
*
* 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.cojen.tupl;
import java.io.IOException;
import java.util.Arrays;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
/**
* Internal cursor implementation, which can be used by one thread at a time.
*
* @author Brian S O'Neill
*/
final class TreeCursor extends CauseCloseable implements Cursor {
// Sign is important because values are passed to Node.retrieveKeyCmp
// method. Bit 0 is set for inclusive variants and clear for exclusive.
private static final int LIMIT_LE = 1, LIMIT_LT = 2, LIMIT_GE = -1, LIMIT_GT = -2;
final Tree mTree;
private Transaction mTxn;
// Top stack frame for cursor, always a leaf.
private TreeCursorFrame mLeaf;
byte[] mKey;
byte[] mValue;
boolean mKeyOnly;
// Hashcode is defined by LockManager.
private int mKeyHash;
TreeCursor(Tree tree, Transaction txn) {
mTree = tree;
mTxn = txn;
}
@Override
public byte[] key() {
return mKey;
}
@Override
public byte[] value() {
return mValue;
}
@Override
public void autoload(boolean mode) {
mKeyOnly = !mode;
}
@Override
public int compareKeyTo(byte[] rkey) {
byte[] lkey = mKey;
return Utils.compareKeys(lkey, 0, lkey.length, rkey, 0, rkey.length);
}
@Override
public int compareKeyTo(byte[] rkey, int offset, int length) {
byte[] lkey = mKey;
return Utils.compareKeys(lkey, 0, lkey.length, rkey, offset, length);
}
private int keyHash() {
int hash = mKeyHash;
if (hash == 0) {
mKeyHash = hash = LockManager.hash(mTree.mId, mKey);
}
return hash;
}
@Override
public LockResult first() throws IOException {
Node root = mTree.mRoot;
TreeCursorFrame frame = reset(root);
if (!root.hasKeys()) {
root.releaseExclusive();
mKey = null;
mKeyHash = 0;
mValue = null;
return LockResult.UNOWNED;
}
toFirst(root, frame);
Transaction txn = mTxn;
LockResult result = tryCopyCurrent(txn);
if (result != null) {
// Extra check for filtering tombstones.
if (mKey == null || mValue != null) {
return result;
}
} else if ((result = lockAndCopyIfExists(txn)) != null) {
return result;
}
// If this point is reached, then entry was deleted after latch was
// released. Move to next entry, which is consistent with findGe.
// First means, "find greater than or equal to lowest possible key".
return next();
}
@Override
public LockResult first(long maxWait, TimeUnit unit) throws IOException {
Node root = mTree.mRoot;
TreeCursorFrame frame = reset(root);
if (!root.hasKeys()) {
root.releaseExclusive();
mKey = null;
mKeyHash = 0;
mValue = null;
return LockResult.UNOWNED;
}
toFirst(root, frame);
Transaction txn = mTxn;
LockResult result = tryCopyCurrent(txn);
if (result != null) {
// Extra check for filtering tombstones.
if (mKey == null || mValue != null) {
return result;
}
} else if ((result = lockAndCopyIfExists(txn, maxWait, unit)) != null) {
return result;
}
// If this point is reached, then entry was deleted after latch was
// released. Move to next entry, which is consistent with findGe.
// First means, "find greater than or equal to lowest possible key".
return next(maxWait, unit);
}
/**
* Moves the cursor to the first subtree entry. Leaf frame remains latched
* when method returns normally.
*
* @param node latched node
* @param frame frame to bind node to
*/
private void toFirst(Node node, TreeCursorFrame frame) throws IOException {
try {
while (true) {
frame.bind(node, 0);
if (node.isLeaf()) {
mLeaf = frame;
// FIXME: Node can be empty if in the process of merging.
return;
}
if (node.mSplit != null) {
node = node.mSplit.latchLeft(node);
}
// FIXME: Node can be empty if in the process of merging.
node = latchChild(node, 0, true);
frame = new TreeCursorFrame(frame);
}
} catch (Throwable e) {
throw cleanup(e, frame);
}
}
@Override
public LockResult last() throws IOException {
Node root = mTree.mRoot;
TreeCursorFrame frame = reset(root);
if (!root.hasKeys()) {
root.releaseExclusive();
mKey = null;
mKeyHash = 0;
mValue = null;
return LockResult.UNOWNED;
}
toLast(root, frame);
Transaction txn = mTxn;
LockResult result = tryCopyCurrent(txn);
if (result != null) {
// Extra check for filtering tombstones.
if (mKey == null || mValue != null) {
return result;
}
} else if ((result = lockAndCopyIfExists(txn)) != null) {
return result;
}
// If this point is reached, then entry was deleted after latch was
// released. Move to previous entry, which is consistent with findLe.
// Last means, "find less than or equal to highest possible key".
return previous();
}
@Override
public LockResult last(long maxWait, TimeUnit unit) throws IOException {
Node root = mTree.mRoot;
TreeCursorFrame frame = reset(root);
if (!root.hasKeys()) {
root.releaseExclusive();
mKey = null;
mKeyHash = 0;
mValue = null;
return LockResult.UNOWNED;
}
toLast(root, frame);
Transaction txn = mTxn;
LockResult result = tryCopyCurrent(txn);
if (result != null) {
// Extra check for filtering tombstones.
if (mKey == null || mValue != null) {
return result;
}
} else if ((result = lockAndCopyIfExists(txn, maxWait, unit)) != null) {
return result;
}
// If this point is reached, then entry was deleted after latch was
// released. Move to previous entry, which is consistent with findLe.
// Last means, "find less than or equal to highest possible key".
return previous(maxWait, unit);
}
/**
* Moves the cursor to the last subtree entry. Leaf frame remains latched
* when method returns normally.
*
* @param node latched node
* @param frame frame to bind node to
*/
private void toLast(Node node, TreeCursorFrame frame) throws IOException {
try {
while (true) {
if (node.isLeaf()) {
// FIXME: Node can be empty if in the process of merging.
int pos;
if (node.mSplit == null) {
pos = node.highestLeafPos();
} else {
pos = node.mSplit.highestLeafPos(node);
}
frame.bind(node, pos);
mLeaf = frame;
return;
}
Split split = node.mSplit;
if (split == null) {
int childPos = node.highestInternalPos();
frame.bind(node, childPos);
// FIXME: Node can be empty if in the process of merging.
node = latchChild(node, childPos, true);
} else {
// Follow highest position of split, binding this frame to the
// unsplit node as if it had not split. The binding will be
// corrected when split is finished.
final Node sibling = split.latchSibling();
final Node left, right;
if (split.mSplitRight) {
left = node;
right = sibling;
} else {
left = sibling;
right = node;
}
int highestRightPos = right.highestInternalPos();
frame.bind(node, left.highestInternalPos() + 2 + highestRightPos);
left.releaseExclusive();
// FIXME: Node can be empty if in the process of merging.
node = latchChild(right, highestRightPos, true);
}
frame = new TreeCursorFrame(frame);
}
} catch (Throwable e) {
throw cleanup(e, frame);
}
}
@Override
public LockResult skip(long amount) throws IOException {
if (amount == 0) {
Transaction txn = mTxn;
if (txn != null && txn != Transaction.BOGUS) {
byte[] key = mKey;
if (key != null) {
return txn.mManager.check(txn, mTree.mId, key, keyHash());
}
}
return LockResult.UNOWNED;
}
try {
TreeCursorFrame frame = leafExclusiveNotSplit();
if (amount > 0) {
if (amount > 1 && (frame = skipNextGap(frame, amount - 1)) == null) {
return LockResult.UNOWNED;
}
return next(mTxn, frame);
} else {
if (amount < -1 && (frame = skipPreviousGap(frame, -1 - amount)) == null) {
return LockResult.UNOWNED;
}
return previous(mTxn, frame);
}
} catch (Throwable e) {
throw handleException(e);
}
}
@Override
public LockResult next() throws IOException {
return next(mTxn, leafExclusiveNotSplit());
}
@Override
public LockResult next(long maxWait, TimeUnit unit) throws IOException {
return next(mTxn, leafExclusiveNotSplit(), maxWait, unit);
}
@Override
public LockResult nextLe(byte[] limitKey) throws IOException {
return nextCmp(limitKey, LIMIT_LE);
}
@Override
public LockResult nextLe(byte[] limitKey, long maxWait, TimeUnit unit) throws IOException {
return nextCmp(limitKey, LIMIT_LE, maxWait, unit);
}
@Override
public LockResult nextLt(byte[] limitKey) throws IOException {
return nextCmp(limitKey, LIMIT_LT);
}
@Override
public LockResult nextLt(byte[] limitKey, long maxWait, TimeUnit unit) throws IOException {
return nextCmp(limitKey, LIMIT_LT, maxWait, unit);
}
private LockResult nextCmp(byte[] limitKey, int limitMode) throws IOException {
Transaction txn = mTxn;
TreeCursorFrame frame = leafExclusiveNotSplit();
while (true) {
if (!toNext(frame)) {
return LockResult.UNOWNED;
}
LockResult result = tryCopyCurrentCmp(txn, limitKey, limitMode);
if (result != null) {
// Extra check for filtering tombstones.
if (mKey == null || mValue != null) {
return result;
}
} else if ((result = lockAndCopyIfExists(txn)) != null) {
return result;
}
frame = leafExclusiveNotSplit();
}
}
private LockResult nextCmp(byte[] limitKey, int limitMode, long maxWait, TimeUnit unit)
throws IOException
{
Transaction txn = mTxn;
TreeCursorFrame frame = leafExclusiveNotSplit();
while (true) {
if (!toNext(frame)) {
return LockResult.UNOWNED;
}
LockResult result = tryCopyCurrentCmp(txn, limitKey, limitMode);
if (result != null) {
// Extra check for filtering tombstones.
if (mKey == null || mValue != null) {
return result;
}
} else if ((result = lockAndCopyIfExists(txn, maxWait, unit)) != null) {
return result;
}
frame = leafExclusiveNotSplit();
}
}
/**
* Note: When method returns, frame is unlatched and may no longer be valid.
*
* @param frame leaf frame, not split, with exclusive latch
*/
private LockResult next(Transaction txn, TreeCursorFrame frame) throws IOException {
while (true) {
if (!toNext(frame)) {
return LockResult.UNOWNED;
}
LockResult result = tryCopyCurrent(txn);
if (result != null) {
// Extra check for filtering tombstones.
if (mKey == null || mValue != null) {
return result;
}
} else if ((result = lockAndCopyIfExists(txn)) != null) {
return result;
}
frame = leafExclusiveNotSplit();
}
}
/**
* Note: When method returns, frame is unlatched and may no longer be valid.
*
* @param frame leaf frame, not split, with exclusive latch
*/
private LockResult next(Transaction txn, TreeCursorFrame frame,
long maxWait, TimeUnit unit)
throws IOException
{
while (true) {
if (!toNext(frame)) {
return LockResult.UNOWNED;
}
LockResult result = tryCopyCurrent(txn);
if (result != null) {
// Extra check for filtering tombstones.
if (mKey == null || mValue != null) {
return result;
}
} else if ((result = lockAndCopyIfExists(txn, maxWait, unit)) != null) {
return result;
}
frame = leafExclusiveNotSplit();
}
}
/**
* Note: When method returns, frame is unlatched and may no longer be
* valid. Leaf frame remains latched when method returns true.
*
* @param frame leaf frame, not split, with exclusive latch
* @return false if nothing left
*/
private boolean toNext(TreeCursorFrame frame) throws IOException {
Node node = frame.mNode;
quick: {
int pos = frame.mNodePos;
if (pos < 0) {
pos = ~2 - pos; // eq: (~pos) - 2;
if (pos >= node.highestLeafPos()) {
break quick;
}
frame.mNotFoundKey = null;
} else if (pos >= node.highestLeafPos()) {
break quick;
}
frame.mNodePos = pos + 2;
return true;
}
while (true) {
TreeCursorFrame parentFrame = frame.peek();
if (parentFrame == null) {
frame.popv();
node.releaseExclusive();
mLeaf = null;
mKey = null;
mKeyHash = 0;
mValue = null;
return false;
}
Node parentNode;
int parentPos;
latchParent: {
splitCheck: {
// Latch coupling up the tree usually works, so give it a
// try. If it works, then there's no need to worry about a
// node merge.
parentNode = parentFrame.tryAcquireExclusive();
if (parentNode == null) {
// Latch coupling failed, and so acquire parent latch
// without holding child latch. The child might have
// changed, and so it must be checked again.
node.releaseExclusive();
parentNode = parentFrame.acquireExclusive();
if (parentNode.mSplit == null) {
break splitCheck;
}
} else {
if (parentNode.mSplit == null) {
frame.popv();
node.releaseExclusive();
parentPos = parentFrame.mNodePos;
break latchParent;
}
node.releaseExclusive();
}
// When this point is reached, parent node must be split.
// Parent latch is held, child latch is not held, but the
// frame is still valid.
parentNode = finishSplit(parentFrame, parentNode);
}
// When this point is reached, child must be relatched. Parent
// latch is held, and the child frame is still valid.
parentPos = parentFrame.mNodePos;
node = latchChild(parentNode, parentPos, false);
// Quick check again, in case node got bigger due to merging.
// Unlike the earlier quick check, this one must handle
// internal nodes too.
quick: {
int pos = frame.mNodePos;
if (pos < 0) {
pos = ~2 - pos; // eq: (~pos) - 2;
if (pos >= node.highestLeafPos()) {
break quick;
}
frame.mNotFoundKey = null;
} else if (pos >= node.highestPos()) {
break quick;
}
parentNode.releaseExclusive();
frame.mNodePos = (pos += 2);
if (frame != mLeaf) {
toFirst(latchChild(node, pos, true), new TreeCursorFrame(frame));
}
return true;
}
frame.popv();
node.releaseExclusive();
}
// When this point is reached, only the parent latch is held. Child
// frame is no longer valid.
if (parentPos < parentNode.highestInternalPos()) {
parentFrame.mNodePos = (parentPos += 2);
toFirst(latchChild(parentNode, parentPos, true), new TreeCursorFrame(parentFrame));
return true;
}
frame = parentFrame;
node = parentNode;
}
}
/**
* @param frame leaf frame, not split, with exclusive latch
* @return latched leaf frame or null if reached end
*/
private TreeCursorFrame skipNextGap(TreeCursorFrame frame, long amount) throws IOException {
outer: while (true) {
Node node = frame.mNode;
quick: {
int pos = frame.mNodePos;
int highest;
if (pos < 0) {
pos = ~2 - pos; // eq: (~pos) - 2;
if (pos >= (highest = node.highestLeafPos())) {
break quick;
}
frame.mNotFoundKey = null;
} else if (pos >= (highest = node.highestLeafPos())) {
break quick;
}
int avail = (highest - pos) >> 1;
if (avail >= amount) {
frame.mNodePos = pos + (((int) amount) << 1);
return frame;
} else {
frame.mNodePos = highest;
amount -= avail;
}
}
while (true) {
TreeCursorFrame parentFrame = frame.peek();
if (parentFrame == null) {
frame.popv();
node.releaseExclusive();
mLeaf = null;
mKey = null;
mKeyHash = 0;
mValue = null;
return null;
}
Node parentNode;
int parentPos;
latchParent: {
splitCheck: {
// Latch coupling up the tree usually works, so give it a
// try. If it works, then there's no need to worry about a
// node merge.
parentNode = parentFrame.tryAcquireExclusive();
if (parentNode == null) {
// Latch coupling failed, and so acquire parent latch
// without holding child latch. The child might have
// changed, and so it must be checked again.
node.releaseExclusive();
parentNode = parentFrame.acquireExclusive();
if (parentNode.mSplit == null) {
break splitCheck;
}
} else {
if (parentNode.mSplit == null) {
frame.popv();
node.releaseExclusive();
parentPos = parentFrame.mNodePos;
break latchParent;
}
node.releaseExclusive();
}
// When this point is reached, parent node must be split.
// Parent latch is held, child latch is not held, but the
// frame is still valid.
parentNode = finishSplit(parentFrame, parentNode);
}
// When this point is reached, child must be relatched. Parent
// latch is held, and the child frame is still valid.
parentPos = parentFrame.mNodePos;
node = latchChild(parentNode, parentPos, false);
// Quick check again, in case node got bigger due to merging.
// Unlike the earlier quick check, this one must handle
// internal nodes too.
quick: {
int pos = frame.mNodePos;
int highest;
if (pos < 0) {
pos = ~2 - pos; // eq: (~pos) - 2;
if (pos >= (highest = node.highestLeafPos())) {
break quick;
}
frame.mNotFoundKey = null;
} else if (pos >= (highest = node.highestPos())) {
break quick;
}
parentNode.releaseExclusive();
if (frame == mLeaf) {
int avail = (highest - pos) >> 1;
if (avail >= amount) {
frame.mNodePos = pos + (((int) amount) << 1);
return frame;
} else {
frame.mNodePos = highest;
amount -= avail;
}
}
// Increment position of internal node.
frame.mNodePos = (pos += 2);
frame = skipToFirst(latchChild(node, pos, true),
new TreeCursorFrame(frame));
if (--amount <= 0) {
return frame;
}
continue outer;
}
frame.popv();
node.releaseExclusive();
}
// When this point is reached, only the parent latch is held. Child
// frame is no longer valid.
if (parentPos < parentNode.highestInternalPos()) {
parentFrame.mNodePos = (parentPos += 2);
frame = skipToFirst(latchChild(parentNode, parentPos, true),
new TreeCursorFrame(parentFrame));
if (--amount <= 0) {
return frame;
}
continue outer;
}
frame = parentFrame;
node = parentNode;
}
}
}
/**
* @param node latched node
* @param frame frame to bind node to
* @return latched leaf frame
*/
private TreeCursorFrame skipToFirst(Node node, TreeCursorFrame frame) throws IOException {
try {
while (true) {
frame.bind(node, 0);
if (node.isLeaf()) {
mLeaf = frame;
return frame;
}
if (node.mSplit != null) {
node = node.mSplit.latchLeft(node);
}
// FIXME: Node can be empty if in the process of merging.
node = latchChild(node, 0, true);
frame = new TreeCursorFrame(frame);
}
} catch (Throwable e) {
throw cleanup(e, frame);
}
}
@Override
public LockResult previous() throws IOException {
return previous(mTxn, leafExclusiveNotSplit());
}
@Override
public LockResult previous(long maxWait, TimeUnit unit) throws IOException {
return previous(mTxn, leafExclusiveNotSplit(), maxWait, unit);
}
@Override
public LockResult previousGe(byte[] limitKey) throws IOException {
return previousCmp(limitKey, LIMIT_GE);
}
@Override
public LockResult previousGe(byte[] limitKey, long maxWait, TimeUnit unit) throws IOException {
return previousCmp(limitKey, LIMIT_GE, maxWait, unit);
}
@Override
public LockResult previousGt(byte[] limitKey) throws IOException {
return previousCmp(limitKey, LIMIT_GT);
}
@Override
public LockResult previousGt(byte[] limitKey, long maxWait, TimeUnit unit) throws IOException {
return previousCmp(limitKey, LIMIT_GT, maxWait, unit);
}
private LockResult previousCmp(byte[] limitKey, int limitMode) throws IOException {
Transaction txn = mTxn;
TreeCursorFrame frame = leafExclusiveNotSplit();
while (true) {
if (!toPrevious(frame)) {
return LockResult.UNOWNED;
}
LockResult result = tryCopyCurrentCmp(txn, limitKey, limitMode);
if (result != null) {
// Extra check for filtering tombstones.
if (mKey == null || mValue != null) {
return result;
}
} else if ((result = lockAndCopyIfExists(txn)) != null) {
return result;
}
frame = leafExclusiveNotSplit();
}
}
private LockResult previousCmp(byte[] limitKey, int limitMode, long maxWait, TimeUnit unit)
throws IOException
{
Transaction txn = mTxn;
TreeCursorFrame frame = leafExclusiveNotSplit();
while (true) {
if (!toPrevious(frame)) {
return LockResult.UNOWNED;
}
LockResult result = tryCopyCurrentCmp(txn, limitKey, limitMode);
if (result != null) {
// Extra check for filtering tombstones.
if (mKey == null || mValue != null) {
return result;
}
} else if ((result = lockAndCopyIfExists(txn, maxWait, unit)) != null) {
return result;
}
frame = leafExclusiveNotSplit();
}
}
/**
* Note: When method returns, frame is unlatched and may no longer be valid.
*
* @param frame leaf frame, not split, with exclusive latch
*/
private LockResult previous(Transaction txn, TreeCursorFrame frame) throws IOException {
while (true) {
if (!toPrevious(frame)) {
return LockResult.UNOWNED;
}
LockResult result = tryCopyCurrent(txn);
if (result != null) {
// Extra check for filtering tombstones.
if (mKey == null || mValue != null) {
return result;
}
} else if ((result = lockAndCopyIfExists(txn)) != null) {
return result;
}
frame = leafExclusiveNotSplit();
}
}
/**
* Note: When method returns, frame is unlatched and may no longer be valid.
*
* @param frame leaf frame, not split, with exclusive latch
*/
private LockResult previous(Transaction txn, TreeCursorFrame frame,
long maxWait, TimeUnit unit)
throws IOException
{
while (true) {
if (!toPrevious(frame)) {
return LockResult.UNOWNED;
}
LockResult result = tryCopyCurrent(txn);
if (result != null) {
// Extra check for filtering tombstones.
if (mKey == null || mValue != null) {
return result;
}
} else if ((result = lockAndCopyIfExists(txn, maxWait, unit)) != null) {
return result;
}
frame = leafExclusiveNotSplit();
}
}
/**
* Note: When method returns, frame is unlatched and may no longer be
* valid. Leaf frame remains latched when method returns true.
*
* @param frame leaf frame, not split, with exclusive latch
* @return false if nothing left
*/
private boolean toPrevious(TreeCursorFrame frame) throws IOException {
Node node = frame.mNode;
quick: {
int pos = frame.mNodePos;
if (pos < 0) {
pos = ~pos;
if (pos == 0) {
break quick;
}
frame.mNotFoundKey = null;
} else if (pos == 0) {
break quick;
}
frame.mNodePos = pos - 2;
return true;
}
while (true) {
TreeCursorFrame parentFrame = frame.peek();
if (parentFrame == null) {
frame.popv();
node.releaseExclusive();
mLeaf = null;
mKey = null;
mKeyHash = 0;
mValue = null;
return false;
}
Node parentNode;
int parentPos;
latchParent: {
splitCheck: {
// Latch coupling up the tree usually works, so give it a
// try. If it works, then there's no need to worry about a
// node merge.
parentNode = parentFrame.tryAcquireExclusive();
if (parentNode == null) {
// Latch coupling failed, and so acquire parent latch
// without holding child latch. The child might have
// changed, and so it must be checked again.
node.releaseExclusive();
parentNode = parentFrame.acquireExclusive();
if (parentNode.mSplit == null) {
break splitCheck;
}
} else {
if (parentNode.mSplit == null) {
frame.popv();
node.releaseExclusive();
parentPos = parentFrame.mNodePos;
break latchParent;
}
node.releaseExclusive();
}
// When this point is reached, parent node must be split.
// Parent latch is held, child latch is not held, but the
// frame is still valid.
parentNode = finishSplit(parentFrame, parentNode);
}
// When this point is reached, child must be relatched. Parent
// latch is held, and the child frame is still valid.
parentPos = parentFrame.mNodePos;
node = latchChild(parentNode, parentPos, false);
// Quick check again, in case node got bigger due to merging.
// Unlike the earlier quick check, this one must handle
// internal nodes too.
quick: {
int pos = frame.mNodePos;
if (pos < 0) {
pos = ~pos;
if (pos == 0) {
break quick;
}
frame.mNotFoundKey = null;
} else if (pos == 0) {
break quick;
}
parentNode.releaseExclusive();
frame.mNodePos = (pos -= 2);
if (frame != mLeaf) {
toLast(latchChild(node, pos, true), new TreeCursorFrame(frame));
}
return true;
}
frame.popv();
node.releaseExclusive();
}
// When this point is reached, only the parent latch is held. Child
// frame is no longer valid.
if (parentPos > 0) {
parentFrame.mNodePos = (parentPos -= 2);
toLast(latchChild(parentNode, parentPos, true), new TreeCursorFrame(parentFrame));
return true;
}
frame = parentFrame;
node = parentNode;
}
}
/**
* @param frame leaf frame, not split, with exclusive latch
* @return latched leaf frame or null if reached end
*/
private TreeCursorFrame skipPreviousGap(TreeCursorFrame frame, long amount)
throws IOException
{
outer: while (true) {
Node node = frame.mNode;
quick: {
int pos = frame.mNodePos;
if (pos < 0) {
pos = ~pos;
if (pos == 0) {
break quick;
}
frame.mNotFoundKey = null;
} else if (pos == 0) {
break quick;
}
int avail = pos >> 1;
if (avail >= amount) {
frame.mNodePos = pos - (((int) amount) << 1);
return frame;
} else {
frame.mNodePos = 0;
amount -= avail;
}
}
while (true) {
TreeCursorFrame parentFrame = frame.peek();
if (parentFrame == null) {
frame.popv();
node.releaseExclusive();
mLeaf = null;
mKey = null;
mKeyHash = 0;
mValue = null;
return null;
}
Node parentNode;
int parentPos;
latchParent: {
splitCheck: {
// Latch coupling up the tree usually works, so give it a
// try. If it works, then there's no need to worry about a
// node merge.
parentNode = parentFrame.tryAcquireExclusive();
if (parentNode == null) {
// Latch coupling failed, and so acquire parent latch
// without holding child latch. The child might have
// changed, and so it must be checked again.
node.releaseExclusive();
parentNode = parentFrame.acquireExclusive();
if (parentNode.mSplit == null) {
break splitCheck;
}
} else {
if (parentNode.mSplit == null) {
frame.popv();
node.releaseExclusive();
parentPos = parentFrame.mNodePos;
break latchParent;
}
node.releaseExclusive();
}
// When this point is reached, parent node must be split.
// Parent latch is held, child latch is not held, but the
// frame is still valid.
parentNode = finishSplit(parentFrame, parentNode);
}
// When this point is reached, child must be relatched. Parent
// latch is held, and the child frame is still valid.
parentPos = parentFrame.mNodePos;
node = latchChild(parentNode, parentPos, false);
// Quick check again, in case node got bigger due to merging.
// Unlike the earlier quick check, this one must handle
// internal nodes too.
quick: {
int pos = frame.mNodePos;
if (pos < 0) {
pos = ~pos;
if (pos == 0) {
break quick;
}
frame.mNotFoundKey = null;
} else if (pos == 0) {
break quick;
}
parentNode.releaseExclusive();
if (frame == mLeaf) {
int avail = pos >> 1;
if (avail >= amount) {
frame.mNodePos = pos - (((int) amount) << 1);
return frame;
} else {
frame.mNodePos = 0;
amount -= avail;
}
}
// Decrement position of internal node.
frame.mNodePos = (pos -= 2);
frame = skipToLast(latchChild(node, pos, true),
new TreeCursorFrame(frame));
if (--amount <= 0) {
return frame;
}
continue outer;
}
frame.popv();
node.releaseExclusive();
}
// When this point is reached, only the parent latch is held. Child
// frame is no longer valid.
if (parentPos > 0) {
parentFrame.mNodePos = (parentPos -= 2);
frame = skipToLast(latchChild(parentNode, parentPos, true),
new TreeCursorFrame(parentFrame));
if (--amount <= 0) {
return frame;
}
continue outer;
}
frame = parentFrame;
node = parentNode;
}
}
}
/**
* @param node latched node
* @param frame frame to bind node to
* @return latched leaf frame
*/
private TreeCursorFrame skipToLast(Node node, TreeCursorFrame frame) throws IOException {
try {
while (true) {
if (node.isLeaf()) {
int pos;
if (node.mSplit == null) {
pos = node.highestLeafPos();
} else {
pos = node.mSplit.highestLeafPos(node);
}
frame.bind(node, pos);
mLeaf = frame;
return frame;
}
Split split = node.mSplit;
if (split == null) {
int childPos = node.highestInternalPos();
frame.bind(node, childPos);
// FIXME: Node can be empty if in the process of merging.
node = latchChild(node, childPos, true);
} else {
// Follow highest position of split, binding this frame to the
// unsplit node as if it had not split. The binding will be
// corrected when split is finished.
final Node sibling = split.latchSibling();
final Node left, right;
if (split.mSplitRight) {
left = node;
right = sibling;
} else {
left = sibling;
right = node;
}
int highestRightPos = right.highestInternalPos();
frame.bind(node, left.highestInternalPos() + 2 + highestRightPos);
left.releaseExclusive();
// FIXME: Node can be empty if in the process of merging.
node = latchChild(right, highestRightPos, true);
}
frame = new TreeCursorFrame(frame);
}
} catch (Throwable e) {
throw cleanup(e, frame);
}
}
/**
* Try to copy the current entry, locking it if required. Null is returned
* if lock is not immediately available and only the key was copied. Node
* latch is always released by this method, even if an exception is thrown.
*
* @return null, UNOWNED, INTERRUPTED, TIMED_OUT_LOCK, ACQUIRED,
* OWNED_SHARED, OWNED_UPGRADABLE, or OWNED_EXCLUSIVE
* @param txn optional
*/
private LockResult tryCopyCurrent(Transaction txn) throws IOException {
final Node node;
final int pos;
{
TreeCursorFrame leaf = mLeaf;
node = leaf.mNode;
pos = leaf.mNodePos;
}
try {
mKeyHash = 0;
final LockMode mode;
if (txn == null) {
mode = LockMode.READ_COMMITTED;
} else if ((mode = txn.lockMode()).noReadLock) {
if (mKeyOnly) {
mKey = node.retrieveKey(pos);
mValue = node.hasLeafValue(pos);
} else {
node.retrieveLeafEntry(pos, this);
}
return LockResult.UNOWNED;
}
// Copy key for now, because lock might not be available. Value
// might change after latch is released. Assign NOT_LOADED, in case
// lock cannot be granted at all. This prevents uncommited value
// from being exposed.
mKey = node.retrieveKey(pos);
mValue = NOT_LOADED;
try {
LockResult result;
switch (mode) {
default:
if (mTree.isLockAvailable(txn, mKey, keyHash())) {
// No need to acquire full lock.
mValue = mKeyOnly ? node.hasLeafValue(pos)
: node.retrieveLeafValue(mTree, pos);
return LockResult.UNOWNED;
} else {
return null;
}
case REPEATABLE_READ:
result = txn.tryLockShared(mTree.mId, mKey, keyHash(), 0);
break;
case UPGRADABLE_READ:
result = txn.tryLockUpgradable(mTree.mId, mKey, keyHash(), 0);
break;
}
if (result.isHeld()) {
mValue = mKeyOnly ? node.hasLeafValue(pos)
: node.retrieveLeafValue(mTree, pos);
return result;
} else {
return null;
}
} catch (DeadlockException e) {
// Not expected with timeout of zero anyhow.
return null;
}
} finally {
node.releaseExclusive();
}
}
/**
* Variant of tryCopyCurrent used by iteration methods which have a
* limit. If limit is reached, cursor is reset and UNOWNED is returned.
*/
private LockResult tryCopyCurrentCmp(Transaction txn, byte[] limitKey, int limitMode)
throws IOException
{
final Node node;
final int pos;
{
TreeCursorFrame leaf = mLeaf;
node = leaf.mNode;
pos = leaf.mNodePos;
}
byte[] key = node.retrieveKeyCmp(pos, limitKey, limitMode);
check: {
if (key != null) {
if (key != limitKey) {
mKey = key;
break check;
} else if ((limitMode & 1) != 0) {
// Cursor contract does not claim ownership of limitKey instance.
mKey = key.clone();
break check;
}
}
// Limit has been reached.
node.releaseExclusive();
reset();
return LockResult.UNOWNED;
}
mKeyHash = 0;
try {
final LockMode mode;
if (txn == null) {
mode = LockMode.READ_COMMITTED;
} else if ((mode = txn.lockMode()).noReadLock) {
mValue = mKeyOnly ? node.hasLeafValue(pos) : node.retrieveLeafValue(mTree, pos);
return LockResult.UNOWNED;
}
mValue = NOT_LOADED;
try {
LockResult result;
switch (mode) {
default:
if (mTree.isLockAvailable(txn, mKey, keyHash())) {
// No need to acquire full lock.
mValue = mKeyOnly ? node.hasLeafValue(pos)
: node.retrieveLeafValue(mTree, pos);
return LockResult.UNOWNED;
} else {
return null;
}
case REPEATABLE_READ:
result = txn.tryLockShared(mTree.mId, mKey, keyHash(), 0);
break;
case UPGRADABLE_READ:
result = txn.tryLockUpgradable(mTree.mId, mKey, keyHash(), 0);
break;
}
if (result.isHeld()) {
mValue = mKeyOnly ? node.hasLeafValue(pos)
: node.retrieveLeafValue(mTree, pos);
return result;
} else {
return null;
}
} catch (DeadlockException e) {
// Not expected with timeout of zero anyhow.
return null;
}
} finally {
node.releaseExclusive();
}
}
/**
* With node latch not held, lock the current key. Returns the lock result
* if entry exists, null otherwise. Method is intended to be called for
* operations which move the position, and so it should not retain locks
* for entries which were concurrently deleted. The find operation is
* required to lock entries which don't exist.
*
* @param txn optional
* @return null if current entry has been deleted
*/
private LockResult lockAndCopyIfExists(Transaction txn) throws IOException {
if (txn == null) {
Locker locker = mTree.lockSharedLocal(mKey, keyHash());
try {
if (copyIfExists()) {
return LockResult.UNOWNED;
}
} finally {
locker.unlock();
}
} else {
LockResult result;
switch (txn.lockMode()) {
// Default case should only capture READ_COMMITTED, since the
// no-lock modes were already handled.
default:
if ((result = txn.lockShared(mTree.mId, mKey, keyHash())) == LockResult.ACQUIRED) {
result = LockResult.UNOWNED;
}
break;
case REPEATABLE_READ:
result = txn.lockShared(mTree.mId, mKey, keyHash());
break;
case UPGRADABLE_READ:
result = txn.lockUpgradable(mTree.mId, mKey, keyHash());
break;
}
if (copyIfExists()) {
if (result == LockResult.UNOWNED) {
txn.unlock();
}
return result;
}
if (result == LockResult.UNOWNED || result == LockResult.ACQUIRED) {
txn.unlock();
}
}
// Entry does not exist, and lock has been released if was just acquired.
return null;
}
/**
* With node latch not held, lock the current key. Returns the lock result
* if entry exists, null otherwise. Method is intended to be called for
* operations which move the position, and so it should not retain locks
* for entries which were concurrently deleted. The find operation is
* required to lock entries which don't exist.
*
* @param txn optional
* @return null if current entry has been deleted or lock not available in time
*/
private LockResult lockAndCopyIfExists(Transaction txn, long maxWait, TimeUnit unit)
throws IOException
{
long nanosTimeout = Utils.toNanos(maxWait, unit);
if (txn == null) {
Locker locker = mTree.mLockManager.localLocker();
LockResult result = locker.lockSharedNT(mTree.mId, mKey, keyHash(), nanosTimeout);
if (!result.isHeld()) {
return null;
}
try {
if (copyIfExists()) {
return LockResult.UNOWNED;
}
} finally {
locker.unlock();
}
} else {
LockResult result;
switch (txn.lockMode()) {
// Default case should only capture READ_COMMITTED, since the
// no-lock modes were already handled.
default:
result = txn.lockSharedNT(mTree.mId, mKey, keyHash(), nanosTimeout);
if (!result.isHeld()) {
return null;
}
if (result == LockResult.ACQUIRED) {
result = LockResult.UNOWNED;
}
break;
case REPEATABLE_READ:
result = txn.lockSharedNT(mTree.mId, mKey, keyHash(), nanosTimeout);
if (!result.isHeld()) {
return null;
}
break;
case UPGRADABLE_READ:
result = txn.lockUpgradableNT(mTree.mId, mKey, keyHash(), nanosTimeout);
if (!result.isHeld()) {
return null;
}
break;
}
if (copyIfExists()) {
if (result == LockResult.UNOWNED) {
txn.unlock();
}
return result;
}
if (result == LockResult.UNOWNED || result == LockResult.ACQUIRED) {
txn.unlock();
}
}
// Entry does not exist, and lock has been released if was just acquired.
return null;
}
private boolean copyIfExists() throws IOException {
TreeCursorFrame frame = leafSharedNotSplit();
Node node = frame.mNode;
try {
int pos = frame.mNodePos;
if (pos < 0) {
return false;
} else if (mKeyOnly) {
return (mValue = node.hasLeafValue(pos)) != null;
} else {
return (mValue = node.retrieveLeafValue(mTree, pos)) != null;
}
} finally {
node.releaseShared();
}
}
/**
* @return 0 if load operation does not acquire a lock
*/
private int keyHashForLoad(Transaction txn, byte[] key) {
if (txn != null) {
LockMode mode = txn.lockMode();
if (mode == LockMode.READ_UNCOMMITTED || mode == LockMode.UNSAFE) {
return 0;
}
}
return LockManager.hash(mTree.mId, key);
}
/**
* @return 0 if load operation does not acquire a lock
*/
private int keyHashForStore(Transaction txn, byte[] key) {
return (txn != null && txn.lockMode() == LockMode.UNSAFE) ? 0
: LockManager.hash(mTree.mId, key);
}
private static final int
VARIANT_REGULAR = 0,
VARIANT_NEARBY = 1,
VARIANT_RETAIN = 2, // retain node latch only if value is null
VARIANT_NO_LOCK = 3, // retain node latch always, don't lock entry
VARIANT_CHECK = 4; // retain node latch always, don't lock entry, don't load entry
@Override
public LockResult find(byte[] key) throws IOException {
Transaction txn = mTxn;
return find(txn, key, keyHashForLoad(txn, key), VARIANT_REGULAR);
}
@Override
public LockResult findGe(byte[] key) throws IOException {
// If isolation level is read committed, then key must be
// locked. Otherwise, an uncommitted delete could be observed.
Transaction txn = mTxn;
LockResult result = find(txn, key, keyHashForLoad(txn, key), VARIANT_RETAIN);
if (mValue != null) {
return result;
} else {
if (result == LockResult.ACQUIRED) {
txn.unlock();
}
return next(txn, mLeaf);
}
}
@Override
public LockResult findGe(byte[] key, long maxWait, TimeUnit unit) throws IOException {
Transaction txn = mTxn;
find(txn, key, 0, VARIANT_CHECK);
if (mValue != null) { // mValue == NOT_LOADED
mLeaf.mNode.releaseExclusive();
LockResult result = loadNT(maxWait, unit);
if (result != LockResult.TIMED_OUT_LOCK) {
return result;
}
return next(maxWait, unit);
} else {
return next(txn, mLeaf, maxWait, unit);
}
}
@Override
public LockResult findGt(byte[] key) throws IOException {
// Never lock the requested key.
Transaction txn = mTxn;
find(txn, key, 0, VARIANT_CHECK);
return next(txn, mLeaf);
}
@Override
public LockResult findGt(byte[] key, long maxWait, TimeUnit unit) throws IOException {
// Never lock the requested key.
Transaction txn = mTxn;
find(txn, key, 0, VARIANT_CHECK);
return next(txn, mLeaf, maxWait, unit);
}
@Override
public LockResult findLe(byte[] key) throws IOException {
// If isolation level is read committed, then key must be
// locked. Otherwise, an uncommitted delete could be observed.
Transaction txn = mTxn;
LockResult result = find(txn, key, keyHashForLoad(txn, key), VARIANT_RETAIN);
if (mValue != null) {
return result;
} else {
if (result == LockResult.ACQUIRED) {
txn.unlock();
}
return previous(txn, mLeaf);
}
}
@Override
public LockResult findLe(byte[] key, long maxWait, TimeUnit unit) throws IOException {
Transaction txn = mTxn;
find(txn, key, 0, VARIANT_CHECK);
if (mValue != null) { // mValue == NOT_LOADED
mLeaf.mNode.releaseExclusive();
LockResult result = loadNT(maxWait, unit);
if (result != LockResult.TIMED_OUT_LOCK) {
return result;
}
return previous(maxWait, unit);
} else {
return previous(txn, mLeaf, maxWait, unit);
}
}
@Override
public LockResult findLt(byte[] key) throws IOException {
// Never lock the requested key.
Transaction txn = mTxn;
find(txn, key, 0, VARIANT_CHECK);
return previous(txn, mLeaf);
}
@Override
public LockResult findLt(byte[] key, long maxWait, TimeUnit unit) throws IOException {
// Never lock the requested key.
Transaction txn = mTxn;
find(txn, key, 0, VARIANT_CHECK);
return previous(txn, mLeaf, maxWait, unit);
}
@Override
public LockResult findNearby(byte[] key) throws IOException {
Transaction txn = mTxn;
return find(txn, key, keyHashForLoad(txn, key), VARIANT_NEARBY);
}
/**
* @param hash can pass 0 if no lock is required
*/
private LockResult find(Transaction txn, byte[] key, int hash, int variant)
throws IOException
{
if (key == null) {
throw new NullPointerException("Key is null");
}
mKey = key;
mKeyHash = hash;
Node node;
TreeCursorFrame frame;
nearby: if (variant == VARIANT_NEARBY) {
frame = mLeaf;
if (frame == null) {
node = mTree.mRoot;
node.acquireExclusive();
frame = new TreeCursorFrame();
break nearby;
}
node = frame.acquireExclusive();
if (node.mSplit != null) {
node = finishSplit(frame, node);
}
int startPos = frame.mNodePos;
if (startPos < 0) {
startPos = ~startPos;
}
int pos = node.binarySearch(key, startPos);
if (pos >= 0) {
frame.mNotFoundKey = null;
frame.mNodePos = pos;
try {
LockResult result = tryLockKey(txn);
if (result == null) {
mValue = NOT_LOADED;
} else {
try {
mValue = mKeyOnly ? node.hasLeafValue(pos)
: node.retrieveLeafValue(mTree, pos);
return result;
} catch (Throwable e) {
mValue = NOT_LOADED;
throw Utils.rethrow(e);
}
}
} finally {
node.releaseExclusive();
}
return doLoad(txn);
} else if (pos != ~0 && ~pos <= node.highestLeafPos()) {
// Not found, but insertion pos is in bounds.
frame.mNotFoundKey = key;
frame.mNodePos = pos;
LockResult result = tryLockKey(txn);
if (result == null) {
mValue = NOT_LOADED;
node.releaseExclusive();
} else {
mValue = null;
node.releaseExclusive();
return result;
}
return doLoad(txn);
}
// Cannot be certain if position is in leaf node, so pop up.
mLeaf = null;
while (true) {
TreeCursorFrame parent = frame.pop();
if (parent == null) {
// Usually the root frame refers to the root node, but it
// can be wrong if the tree height is changing.
Node root = mTree.mRoot;
if (node != root) {
node.releaseExclusive();
root.acquireExclusive();
node = root;
}
break;
}
node.releaseExclusive();
frame = parent;
node = frame.acquireExclusive();
// Only search inside non-split nodes. It's easier to just pop
// up rather than finish or search the split.
if (node.mSplit != null) {
continue;
}
pos = Node.internalPos(node.binarySearch(key, frame.mNodePos));
if (pos == 0 || pos >= node.highestInternalPos()) {
// Cannot be certain if position is in this node, so pop up.
continue;
}
frame.mNodePos = pos;
try {
node = latchChild(node, pos, true);
} catch (Throwable e) {
throw cleanup(e, frame);
}
frame = new TreeCursorFrame(frame);
break;
}
} else {
// Other variants always discard existing frames.
node = mTree.mRoot;
frame = reset(node);
}
while (true) {
if (node.isLeaf()) {
int pos;
if (node.mSplit == null) {
pos = node.binarySearch(key);
frame.bind(node, pos);
} else {
pos = node.mSplit.binarySearch(node, key);
frame.bind(node, pos);
+ if (pos < 0) {
+ // The finishSplit method will release the latch, and
+ // so the frame must be completely defined first.
+ frame.mNotFoundKey = key;
+ }
node = finishSplit(frame, node);
pos = frame.mNodePos;
}
mLeaf = frame;
LockResult result;
if (variant >= VARIANT_NO_LOCK) {
result = LockResult.UNOWNED;
} else if ((result = tryLockKey(txn)) == null) {
// Unable to immediately acquire the lock.
if (pos < 0) {
frame.mNotFoundKey = key;
}
mValue = NOT_LOADED;
node.releaseExclusive();
// This might fail to acquire the lock too, but the cursor
// is at the proper position, and with the proper state.
return doLoad(txn);
}
if (pos < 0) {
frame.mNotFoundKey = key;
mValue = null;
if (variant < VARIANT_RETAIN) {
node.releaseExclusive();
}
} else {
if (variant == VARIANT_CHECK) {
mValue = NOT_LOADED;
} else {
try {
mValue = mKeyOnly ? node.hasLeafValue(pos)
: node.retrieveLeafValue(mTree, pos);
} catch (Throwable e) {
mValue = NOT_LOADED;
node.releaseExclusive();
throw Utils.rethrow(e);
}
if (variant < VARIANT_NO_LOCK) {
node.releaseExclusive();
}
}
}
return result;
}
Split split = node.mSplit;
if (split == null) {
int childPos = Node.internalPos(node.binarySearch(key));
frame.bind(node, childPos);
try {
node = latchChild(node, childPos, true);
} catch (Throwable e) {
throw cleanup(e, frame);
}
} else {
// Follow search into split, binding this frame to the unsplit
// node as if it had not split. The binding will be corrected
// when split is finished.
final Node sibling = split.latchSibling();
final Node left, right;
if (split.mSplitRight) {
left = node;
right = sibling;
} else {
left = sibling;
right = node;
}
final Node selected;
final int selectedPos;
if (split.compare(key) < 0) {
selected = left;
selectedPos = Node.internalPos(left.binarySearch(key));
frame.bind(node, selectedPos);
right.releaseExclusive();
} else {
selected = right;
selectedPos = Node.internalPos(right.binarySearch(key));
frame.bind(node, left.highestInternalPos() + 2 + selectedPos);
left.releaseExclusive();
}
try {
node = latchChild(selected, selectedPos, true);
} catch (Throwable e) {
throw cleanup(e, frame);
}
}
frame = new TreeCursorFrame(frame);
}
}
/**
* With node latched, try to lock the current key. Method expects mKeyHash
* to be valid. Returns null if lock is required but not immediately available.
*
* @param txn can be null
*/
private LockResult tryLockKey(Transaction txn) {
LockMode mode;
if (txn == null || (mode = txn.lockMode()) == LockMode.READ_COMMITTED) {
// If lock is available, no need to acquire full lock and
// immediately release it because node is latched.
return mTree.isLockAvailable(txn, mKey, mKeyHash) ? LockResult.UNOWNED : null;
}
try {
LockResult result;
switch (mode) {
default: // no read lock requested by READ_UNCOMMITTED or UNSAFE
return LockResult.UNOWNED;
case REPEATABLE_READ:
result = txn.tryLockShared(mTree.mId, mKey, mKeyHash, 0);
break;
case UPGRADABLE_READ:
result = txn.tryLockUpgradable(mTree.mId, mKey, mKeyHash, 0);
break;
}
return result.isHeld() ? result : null;
} catch (DeadlockException e) {
// Not expected with timeout of zero anyhow.
return null;
}
}
@Override
public LockResult load() throws IOException {
// This will always acquire a lock if required to. A try-lock pattern
// can skip the lock acquisition is certain cases, but the optimization
// doesn't seem worth the trouble.
return doLoad(mTxn);
}
/**
* Must be called with node latch not held.
*/
private LockResult doLoad(Transaction txn) throws IOException {
byte[] key = mKey;
if (key == null) {
throw new IllegalStateException("Cursor position is undefined");
}
LockResult result;
Locker locker;
if (txn == null) {
result = LockResult.UNOWNED;
locker = mTree.lockSharedLocal(key, keyHash());
} else {
switch (txn.lockMode()) {
default: // no read lock requested by READ_UNCOMMITTED or UNSAFE
result = LockResult.UNOWNED;
locker = null;
break;
case READ_COMMITTED:
if ((result = txn.lockShared(mTree.mId, key, keyHash())) == LockResult.ACQUIRED) {
result = LockResult.UNOWNED;
locker = txn;
} else {
locker = null;
}
break;
case REPEATABLE_READ:
result = txn.lockShared(mTree.mId, key, keyHash());
locker = null;
break;
case UPGRADABLE_READ:
result = txn.lockUpgradable(mTree.mId, key, keyHash());
locker = null;
break;
}
}
try {
TreeCursorFrame frame = leafSharedNotSplit();
Node node = frame.mNode;
try {
int pos = frame.mNodePos;
mValue = pos >= 0 ? node.retrieveLeafValue(mTree, pos) : null;
} finally {
node.releaseShared();
}
return result;
} finally {
if (locker != null) {
locker.unlock();
}
}
}
/**
* NT == No Timeout or deadlock exception thrown
*
* @return TIMED_OUT_LOCK, UNOWNED, ACQUIRED, OWNED_SHARED, OWNED_UPGRADABLE, or
* OWNED_EXCLUSIVE
*/
private LockResult loadNT(long timeout, TimeUnit unit) throws IOException {
byte[] key = mKey;
if (key == null) {
throw new IllegalStateException("Cursor position is undefined");
}
long nanosTimeout = Utils.toNanos(timeout, unit);
LockResult result;
Locker locker;
Transaction txn = mTxn;
if (txn == null) {
locker = mTree.mLockManager.localLocker();
result = locker.lockSharedNT(mTree.mId, mKey, keyHash(), nanosTimeout);
if (!result.isHeld()) {
return result;
}
result = LockResult.UNOWNED;
} else {
switch (txn.lockMode()) {
default: // no read lock requested by READ_UNCOMMITTED or UNSAFE
result = LockResult.UNOWNED;
locker = null;
break;
case READ_COMMITTED:
result = txn.lockSharedNT(mTree.mId, mKey, keyHash(), nanosTimeout);
if (!result.isHeld()) {
return result;
}
if (result == LockResult.ACQUIRED) {
result = LockResult.UNOWNED;
locker = txn;
} else {
locker = null;
}
break;
case REPEATABLE_READ:
result = txn.lockSharedNT(mTree.mId, mKey, keyHash(), nanosTimeout);
if (!result.isHeld()) {
return result;
}
locker = null;
break;
case UPGRADABLE_READ:
result = txn.lockUpgradableNT(mTree.mId, mKey, keyHash(), nanosTimeout);
if (!result.isHeld()) {
return result;
}
locker = null;
break;
}
}
try {
TreeCursorFrame frame = leafSharedNotSplit();
Node node = frame.mNode;
try {
int pos = frame.mNodePos;
mValue = pos >= 0 ? node.retrieveLeafValue(mTree, pos) : null;
} finally {
node.releaseShared();
}
return result;
} finally {
if (locker != null) {
locker.unlock();
}
}
}
@Override
public void store(byte[] value) throws IOException {
byte[] key = mKey;
if (key == null) {
throw new IllegalStateException("Cursor position is undefined");
}
try {
final Transaction txn = mTxn;
final Locker locker = mTree.lockExclusive(txn, key, keyHash());
try {
final Lock sharedCommitLock = mTree.mDatabase.sharedCommitLock();
sharedCommitLock.lock();
try {
store(txn, leafExclusive(), value);
} finally {
sharedCommitLock.unlock();
}
} finally {
if (locker != null) {
locker.unlock();
}
}
} catch (Throwable e) {
throw handleException(e);
}
}
/**
* Called by Tree.clear method when using auto-commit transaction. Lock
* acquisition is lenient. If record cannot be locked, it is skipped.
*/
/*
long clearTo(byte[] end, boolean inclusive) throws IOException {
byte[] key = mKey;
if (key == null) {
return 0;
}
final Lock sharedCommitLock = mTree.mDatabase.sharedCommitLock();
final long indexId = mTree.mId;
final Locker locker = mTree.mLockManager.localLocker();
long count = 0;
do {
int compare;
if (end == null) {
compare = -1;
} else {
compare = Utils.compareKeys(key, 0, key.length, end, 0, end.length);
if (compare > 0 || (compare == 0 && !inclusive)) {
break;
}
}
sharedCommitLock.lock();
try {
if (locker.tryLockExclusive(indexId, key, keyHash(), 0).isHeld()) {
try {
store(null, leafExclusive(), null);
count++;
} finally {
locker.unlock();
}
}
} catch (Throwable e) {
throw handleException(e);
} finally {
sharedCommitLock.unlock();
}
if (compare >= 0) {
break;
}
next();
} while ((key = mKey) != null);
return count;
}
*/
/**
* Atomic find and store operation.
*/
void findAndStore(byte[] key, byte[] value) throws IOException {
try {
final Transaction txn = mTxn;
final int hash = keyHashForStore(txn, key);
final Locker locker = mTree.lockExclusive(txn, key, hash);
try {
// Find with no lock because it has already been acquired.
find(null, key, hash, VARIANT_NO_LOCK);
final Lock sharedCommitLock = mTree.mDatabase.sharedCommitLock();
sharedCommitLock.lock();
try {
store(txn, mLeaf, value);
} finally {
sharedCommitLock.unlock();
}
} finally {
if (locker != null) {
locker.unlock();
}
}
} catch (Throwable e) {
throw handleException(e);
}
}
/**
* Atomic find and swap operation.
*/
/*
byte[] findAndSwap(byte[] key, byte[] newValue) throws IOException {
try {
final Transaction txn = mTxn;
final int hash = keyHashForStore(txn, key);
final Locker locker = mTree.lockExclusive(txn, key, hash);
byte[] oldValue;
try {
// Find with no lock because it has already been acquired.
find(null, key, hash, VARIANT_NO_LOCK);
oldValue = mValue;
final Lock sharedCommitLock = mTree.mDatabase.sharedCommitLock();
sharedCommitLock.lock();
try {
store(txn, mLeaf, newValue);
} finally {
sharedCommitLock.unlock();
}
} finally {
if (locker != null) {
locker.unlock();
}
}
return oldValue;
} catch (Throwable e) {
throw handleException(e);
}
}
*/
static final byte[] MODIFY_INSERT = new byte[0], MODIFY_REPLACE = new byte[0];
/**
* Atomic find and modify operation.
*
* @param oldValue MODIFY_INSERT, MODIFY_REPLACE, else update mode
*/
boolean findAndModify(byte[] key, byte[] oldValue, byte[] newValue) throws IOException {
final Transaction txn = mTxn;
final int hash = keyHashForStore(txn, key);
try {
// Note: Acquire exclusive lock instead of performing upgrade
// sequence. The upgrade would need to be performed with the node
// latch held, which is deadlock prone.
if (txn == null) {
Locker locker = mTree.lockExclusiveLocal(key, hash);
try {
return doFindAndModify(null, key, hash, oldValue, newValue);
} finally {
locker.unlock();
}
}
LockResult result;
LockMode mode = txn.lockMode();
if (mode == LockMode.UNSAFE) {
// Indicate that no unlock should be performed.
result = LockResult.OWNED_EXCLUSIVE;
} else {
result = txn.lockExclusive(mTree.mId, key, hash);
if (result == LockResult.ACQUIRED &&
(mode == LockMode.REPEATABLE_READ || mode == LockMode.UPGRADABLE_READ))
{
// Downgrade to upgradable when no modification is made, to
// preserve repeatable semantics and allow upgrade later.
result = LockResult.UPGRADED;
}
}
try {
if (doFindAndModify(txn, key, hash, oldValue, newValue)) {
// Indicate that no unlock should be performed.
result = LockResult.OWNED_EXCLUSIVE;
return true;
}
return false;
} finally {
if (result == LockResult.ACQUIRED) {
txn.unlock();
} else if (result == LockResult.UPGRADED) {
txn.unlockToUpgradable();
}
}
} catch (Throwable e) {
throw handleException(e);
}
}
private boolean doFindAndModify(Transaction txn, byte[] key, int hash,
byte[] oldValue, byte[] newValue)
throws IOException
{
// Find with no lock because caller must already acquire exclusive lock.
find(null, key, hash, VARIANT_NO_LOCK);
check: {
if (oldValue == MODIFY_INSERT) {
if (mValue == null) {
// Insert allowed.
break check;
}
} else if (oldValue == MODIFY_REPLACE) {
if (mValue != null) {
// Replace allowed.
break check;
}
} else {
if (mValue != null) {
if (Arrays.equals(oldValue, mValue)) {
// Update allowed.
break check;
}
} else if (oldValue == null) {
if (newValue == null) {
// Update allowed, but nothing changed.
mLeaf.mNode.releaseExclusive();
return true;
} else {
// Update allowed.
break check;
}
}
}
mLeaf.mNode.releaseExclusive();
return false;
}
final Lock sharedCommitLock = mTree.mDatabase.sharedCommitLock();
sharedCommitLock.lock();
try {
store(txn, mLeaf, newValue);
return true;
} finally {
sharedCommitLock.unlock();
}
}
/**
* Non-transactional tombstone delete. Caller is expected to hold exclusive
* key lock. Method does nothing if a value exists.
*/
void deleteTombstone(byte[] key) throws IOException {
try {
// Find with no lock because it has already been acquired.
// TODO: Use nearby optimization when used with transactional Index.clear.
find(null, key, 0, VARIANT_NO_LOCK);
if (mValue == null) {
final Lock sharedCommitLock = mTree.mDatabase.sharedCommitLock();
sharedCommitLock.lock();
try {
store(Transaction.BOGUS, mLeaf, null);
} finally {
sharedCommitLock.unlock();
}
} else {
mLeaf.mNode.releaseExclusive();
}
} catch (Throwable e) {
throw handleException(e);
}
}
/**
* Note: caller must hold shared commit lock, to prevent deadlock.
*
* @param leaf leaf frame, latched exclusively, which is released by this method
*/
private void store(Transaction txn, final TreeCursorFrame leaf, byte[] value)
throws IOException
{
byte[] key = mKey;
Node node = leaf.mNode;
try {
if (value == null) {
// Delete entry...
if (leaf.mNodePos < 0) {
// Entry doesn't exist, so nothing to do.
mValue = null;
return;
}
node = notSplitDirty(leaf);
final int pos = leaf.mNodePos;
if (txn == null) {
mTree.redoStore(key, null);
node.deleteLeafEntry(mTree, pos);
} else {
if (txn.lockMode() == LockMode.UNSAFE) {
node.deleteLeafEntry(mTree, pos);
if (txn.mDurabilityMode != DurabilityMode.NO_LOG) {
txn.redoStore(mTree.mId, key, null);
}
} else {
node.txnDeleteLeafEntry(txn, mTree, key, keyHash(), pos);
// Above operation leaves a tombstone, so no cursors to fix.
mValue = null;
return;
}
}
int newPos = ~pos;
leaf.mNodePos = newPos;
leaf.mNotFoundKey = key;
// Fix all cursors bound to the node.
TreeCursorFrame frame = node.mLastCursorFrame;
do {
if (frame == leaf) {
// Don't need to fix self.
continue;
}
int framePos = frame.mNodePos;
if (framePos == pos) {
frame.mNodePos = newPos;
frame.mNotFoundKey = key;
} else if (framePos > pos) {
frame.mNodePos = framePos - 2;
} else if (framePos < newPos) {
// Position is a complement, so add instead of subtract.
frame.mNodePos = framePos + 2;
}
} while ((frame = frame.mPrevCousin) != null);
if (node.shouldLeafMerge()) {
try {
mergeLeaf(leaf, node);
} finally {
// Always released by mergeLeaf.
node = null;
}
}
mValue = null;
return;
}
// Update and insert always dirty the node.
node = notSplitDirty(leaf);
final int pos = leaf.mNodePos;
if (pos >= 0) {
// Update entry...
if (txn == null) {
mTree.redoStore(key, value);
} else {
if (txn.lockMode() != LockMode.UNSAFE) {
node.txnPreUpdateLeafEntry(txn, mTree, key, pos);
}
if (txn.mDurabilityMode != DurabilityMode.NO_LOG) {
txn.redoStore(mTree.mId, key, value);
}
}
node.updateLeafValue(mTree, pos, 0, value);
if (node.shouldLeafMerge()) {
try {
mergeLeaf(leaf, node);
} finally {
// Always released by mergeLeaf.
node = null;
}
} else {
if (node.mSplit != null) {
node = finishSplit(leaf, node);
}
}
mValue = value;
return;
}
// Insert entry...
if (txn == null) {
mTree.redoStore(key, value);
} else {
if (txn.lockMode() != LockMode.UNSAFE) {
txn.undoDelete(mTree.mId, key);
}
if (txn.mDurabilityMode != DurabilityMode.NO_LOG) {
txn.redoStore(mTree.mId, key, value);
}
}
int newPos = ~pos;
node.insertLeafEntry(mTree, newPos, key, value);
leaf.mNodePos = newPos;
leaf.mNotFoundKey = null;
// Fix all cursors bound to the node.
// Note: Same code as in insertFragmented method.
TreeCursorFrame frame = node.mLastCursorFrame;
do {
if (frame == leaf) {
// Don't need to fix self.
continue;
}
int framePos = frame.mNodePos;
if (framePos == pos) {
// Other cursor is at same not-found position as this one
// was. If keys are the same, then other cursor switches
// to a found state as well. If key is greater, then
// position needs to be updated.
byte[] frameKey = frame.mNotFoundKey;
int compare = Utils.compareKeys
(frameKey, 0, frameKey.length, key, 0, key.length);
if (compare > 0) {
// Position is a complement, so subtract instead of add.
frame.mNodePos = framePos - 2;
} else if (compare == 0) {
frame.mNodePos = newPos;
frame.mNotFoundKey = null;
}
} else if (framePos >= newPos) {
frame.mNodePos = framePos + 2;
} else if (framePos < pos) {
// Position is a complement, so subtract instead of add.
frame.mNodePos = framePos - 2;
}
} while ((frame = frame.mPrevCousin) != null);
if (node.mSplit != null) {
node = finishSplit(leaf, node);
}
mValue = value;
} finally {
if (node != null) {
node.releaseExclusive();
}
}
}
/**
* Non-transactional insert of a fragmented value. Cursor value is
* NOT_LOADED as a side-effect.
*
* @param leaf leaf frame, latched exclusively, which is released by this method
*/
boolean insertFragmented(byte[] value) throws IOException {
byte[] key = mKey;
if (key == null) {
throw new IllegalStateException("Cursor position is undefined");
}
if (value == null) {
throw new IllegalArgumentException("Value is null");
}
Lock sharedCommitLock = mTree.mDatabase.sharedCommitLock();
sharedCommitLock.lock();
try {
final TreeCursorFrame leaf = leafExclusive();
Node node = notSplitDirty(leaf);
try {
final int pos = leaf.mNodePos;
if (pos >= 0) {
// Entry already exists.
if (mValue != null) {
return false;
}
// Replace tombstone.
node.updateLeafValue(mTree, pos, Node.VALUE_FRAGMENTED, value);
} else {
int newPos = ~pos;
node.insertFragmentedLeafEntry(mTree, newPos, key, value);
leaf.mNodePos = newPos;
leaf.mNotFoundKey = null;
// Fix all cursors bound to the node.
// Note: Same code as in store method.
TreeCursorFrame frame = node.mLastCursorFrame;
do {
if (frame == leaf) {
// Don't need to fix self.
continue;
}
int framePos = frame.mNodePos;
if (framePos == pos) {
// Other cursor is at same not-found position as this one
// was. If keys are the same, then other cursor switches
// to a found state as well. If key is greater, then
// position needs to be updated.
byte[] frameKey = frame.mNotFoundKey;
int compare = Utils.compareKeys
(frameKey, 0, frameKey.length, key, 0, key.length);
if (compare > 0) {
// Position is a complement, so subtract instead of add.
frame.mNodePos = framePos - 2;
} else if (compare == 0) {
frame.mNodePos = newPos;
frame.mNotFoundKey = null;
}
} else if (framePos >= newPos) {
frame.mNodePos = framePos + 2;
} else if (framePos < pos) {
// Position is a complement, so subtract instead of add.
frame.mNodePos = framePos - 2;
}
} while ((frame = frame.mPrevCousin) != null);
}
if (node.mSplit != null) {
node = finishSplit(leaf, node);
}
mValue = NOT_LOADED;
} finally {
node.releaseExclusive();
}
} catch (Throwable e) {
throw handleException(e);
} finally {
sharedCommitLock.unlock();
}
return true;
}
private IOException handleException(Throwable e) throws IOException {
// Any unexpected exception can corrupt the internal store state.
// Closing down protects the persisted state.
if (mLeaf == null && e instanceof IllegalStateException) {
// Exception is caused by cursor state; store is safe.
throw (IllegalStateException) e;
}
if (e instanceof DatabaseException) {
DatabaseException de = (DatabaseException) e;
if (de.isRecoverable()) {
throw de;
}
}
try {
throw Utils.closeOnFailure(mTree.mDatabase, e);
} finally {
reset();
}
}
@Override
public void link(Transaction txn) {
mTxn = txn;
}
@Override
public TreeCursor copy() {
TreeCursor copy = new TreeCursor(mTree, mTxn);
TreeCursorFrame frame = mLeaf;
if (frame != null) {
TreeCursorFrame frameCopy = new TreeCursorFrame();
frame.copyInto(frameCopy);
copy.mLeaf = frameCopy;
}
copy.mKey = mKey;
copy.mKeyHash = mKeyHash;
if (!(copy.mKeyOnly = mKeyOnly)) {
byte[] value = mValue;
copy.mValue = (value == null || value.length == 0) ? value : value.clone();
}
return copy;
}
@Override
public void reset() {
TreeCursorFrame frame = mLeaf;
mLeaf = null;
mKey = null;
mKeyHash = 0;
mValue = null;
if (frame != null) {
TreeCursorFrame.popAll(frame);
}
}
/**
* Called if an exception is thrown while frames are being constructed.
* Given frame does not need to be bound, but it must not be latched.
*/
private RuntimeException cleanup(Throwable e, TreeCursorFrame frame) {
mLeaf = frame;
reset();
return Utils.rethrow(e);
}
@Override
public void close() {
reset();
}
@Override
public void close(Throwable cause) {
try {
if (cause instanceof DatabaseException) {
DatabaseException de = (DatabaseException) cause;
if (de.isRecoverable()) {
return;
}
}
throw Utils.closeOnFailure(mTree.mDatabase, cause);
} catch (IOException e) {
// Ignore.
} finally {
reset();
}
}
/**
* Resets all frames and latches root node, exclusively. Although the
* normal reset could be called directly, this variant avoids unlatching
* the root node, since a find operation would immediately relatch it.
*
* @return new or recycled frame
*/
private TreeCursorFrame reset(Node root) {
TreeCursorFrame frame = mLeaf;
if (frame == null) {
root.acquireExclusive();
return new TreeCursorFrame();
}
mLeaf = null;
while (true) {
Node node = frame.acquireExclusive();
TreeCursorFrame parent = frame.pop();
if (parent == null) {
// Usually the root frame refers to the root node, but it
// can be wrong if the tree height is changing.
if (node != root) {
node.releaseExclusive();
root.acquireExclusive();
}
return frame;
}
node.releaseExclusive();
frame = parent;
}
}
/**
* Verifies that cursor state is correct by performing a find operation.
*
* @return false if unable to verify completely at this time
*/
/*
boolean verify() throws IOException, IllegalStateException {
return verify(mKey);
}
*/
/**
* Verifies that cursor state is correct by performing a find operation.
*
* @return false if unable to verify completely at this time
* @throws NullPointerException if key is null
*/
/*
boolean verify(byte[] key) throws IllegalStateException {
ArrayDeque<TreeCursorFrame> frames;
{
TreeCursorFrame frame = mLeaf;
if (frame == null) {
return true;
}
frames = new ArrayDeque<TreeCursorFrame>(10);
do {
frames.addFirst(frame);
frame = frame.mParentFrame;
} while (frame != null);
}
TreeCursorFrame frame = frames.removeFirst();
Node node = frame.acquireShared();
if (node.mSplit != null) {
// Cannot verify into split nodes.
node.releaseShared();
return false;
}
/* This check cannot be reliably performed, because the snapshot of
* frames can be stale.
if (node != mTree.mRoot) {
node.releaseShared();
throw new IllegalStateException("Bottom frame is not at root node");
}
* /
while (true) {
if (node.isLeaf()) {
int pos = node.binarySearch(key);
try {
if (frame.mNodePos != pos) {
throw new IllegalStateException
("Leaf frame position incorrect: " + frame.mNodePos + " != " + pos);
}
if (pos < 0) {
if (frame.mNotFoundKey == null) {
throw new IllegalStateException
("Leaf frame key is not set; pos=" + pos);
}
} else if (frame.mNotFoundKey != null) {
throw new IllegalStateException
("Leaf frame key should not be set; pos=" + pos);
}
} finally {
node.releaseShared();
}
return true;
}
int childPos = Node.internalPos(node.binarySearch(key));
TreeCursorFrame next;
try {
if (frame.mNodePos != childPos) {
throw new IllegalStateException
("Internal frame position incorrect: " +
frame.mNodePos + " != " + childPos);
}
if (frame.mNotFoundKey != null) {
throw new IllegalStateException("Internal frame key should not be set");
}
next = frames.pollFirst();
if (next == null) {
throw new IllegalStateException("Top frame is not a leaf node");
}
next.acquireShared();
} finally {
node.releaseShared();
}
frame = next;
node = frame.mNode;
if (node.mSplit != null) {
// Cannot verify into split nodes.
node.releaseShared();
return false;
}
}
}
*/
/**
* Checks that leaf is defined and returns it.
*/
private TreeCursorFrame leaf() {
TreeCursorFrame leaf = mLeaf;
if (leaf == null) {
throw new IllegalStateException("Cursor position is undefined");
}
return leaf;
}
/**
* Latches and returns leaf frame, which might be split.
*/
private TreeCursorFrame leafExclusive() {
TreeCursorFrame leaf = leaf();
leaf.acquireExclusive();
return leaf;
}
/**
* Latches and returns leaf frame, not split.
*/
private TreeCursorFrame leafExclusiveNotSplit() throws IOException {
TreeCursorFrame leaf = leaf();
Node node = leaf.acquireExclusive();
if (node.mSplit != null) {
finishSplit(leaf, node);
}
return leaf;
}
/**
* Latches and returns leaf frame, not split.
*/
private TreeCursorFrame leafSharedNotSplit() throws IOException {
TreeCursorFrame leaf = leaf();
Node node = leaf.acquireShared();
if (node.mSplit != null) {
doSplit: {
if (!node.tryUpgrade()) {
node.releaseShared();
node = leaf.acquireExclusive();
if (node.mSplit == null) {
break doSplit;
}
}
node = finishSplit(leaf, node);
}
node.downgrade();
}
return leaf;
}
/**
* Called with exclusive frame latch held, which is retained. Leaf frame is
* dirtied, any split is finished, and the same applies to all parent
* nodes. Caller must hold shared commit lock, to prevent deadlock. Node
* latch is released if an exception is thrown.
*
* @return replacement node, still latched
*/
private Node notSplitDirty(final TreeCursorFrame frame) throws IOException {
Node node = frame.mNode;
if (node.mSplit != null) {
// Already dirty, but finish the split.
return finishSplit(frame, node);
}
Database db = mTree.mDatabase;
if (!db.shouldMarkDirty(node)) {
return node;
}
TreeCursorFrame parentFrame = frame.mParentFrame;
if (parentFrame == null) {
try {
db.doMarkDirty(mTree, node);
return node;
} catch (Throwable e) {
node.releaseExclusive();
throw Utils.rethrow(e);
}
}
// Make sure the parent is not split and dirty too.
Node parentNode;
doParent: {
parentNode = parentFrame.tryAcquireExclusive();
if (parentNode == null) {
node.releaseExclusive();
parentFrame.acquireExclusive();
} else if (parentNode.mSplit != null || db.shouldMarkDirty(parentNode)) {
node.releaseExclusive();
} else {
break doParent;
}
parentNode = notSplitDirty(parentFrame);
node = frame.acquireExclusive();
}
while (node.mSplit != null) {
// Already dirty now, but finish the split. Since parent latch is
// already held, no need to call into the regular finishSplit
// method. It would release latches and recheck everything.
try {
parentNode.insertSplitChildRef(mTree, parentFrame.mNodePos, node);
} catch (Throwable e) {
parentNode.releaseExclusive();
node.releaseExclusive();
throw Utils.rethrow(e);
}
if (parentNode.mSplit != null) {
parentNode = finishSplit(parentFrame, parentNode);
}
node = frame.acquireExclusive();
}
try {
if (db.markDirty(mTree, node)) {
parentNode.updateChildRefId(parentFrame.mNodePos, node.mId);
}
return node;
} catch (Throwable e) {
node.releaseExclusive();
throw Utils.rethrow(e);
} finally {
parentNode.releaseExclusive();
}
}
/**
* Caller must hold exclusive latch, which is released by this method.
*/
private void mergeLeaf(final TreeCursorFrame leaf, Node node) throws IOException {
final TreeCursorFrame parentFrame = leaf.mParentFrame;
node.releaseExclusive();
if (parentFrame == null) {
// Root node cannot merge into anything.
return;
}
Node parentNode = parentFrame.acquireExclusive();
Node leftNode, rightNode;
int nodeAvail;
while (true) {
if (parentNode.mSplit != null) {
parentNode = finishSplit(parentFrame, parentNode);
}
if (parentNode.numKeys() <= 0) {
if (parentNode.mId != Node.STUB_ID) {
// TODO: This shouldn't be a problem when internal nodes can be rebalanced.
//System.out.println("tiny internal node: " + (parentNode == mTree.mRoot));
}
parentNode.releaseExclusive();
return;
}
// Latch leaf and siblings in a strict left-to-right order to avoid deadlock.
int pos = parentFrame.mNodePos;
if (pos == 0) {
leftNode = null;
} else {
leftNode = latchChild(parentNode, pos - 2, false);
if (leftNode.mSplit != null) {
// Finish sibling split.
parentNode.insertSplitChildRef(mTree, pos - 2, leftNode);
continue;
}
}
node = leaf.acquireExclusive();
// Double check that node should still merge.
if (!node.shouldMerge(nodeAvail = node.availableLeafBytes())) {
if (leftNode != null) {
leftNode.releaseExclusive();
}
node.releaseExclusive();
parentNode.releaseExclusive();
return;
}
if (pos >= parentNode.highestInternalPos()) {
rightNode = null;
} else {
try {
rightNode = latchChild(parentNode, pos + 2, false);
} catch (Throwable e) {
if (leftNode != null) {
leftNode.releaseExclusive();
}
node.releaseExclusive();
throw Utils.rethrow(e);
}
if (rightNode.mSplit != null) {
// Finish sibling split.
if (leftNode != null) {
leftNode.releaseExclusive();
}
node.releaseExclusive();
parentNode.insertSplitChildRef(mTree, pos + 2, rightNode);
continue;
}
}
break;
}
// Select a left and right pair, and then don't operate directly on the
// original node and leaf parameters afterwards. The original node ends
// up being referenced as a left or right member of the pair.
int leftAvail = leftNode == null ? -1 : leftNode.availableLeafBytes();
int rightAvail = rightNode == null ? -1 : rightNode.availableLeafBytes();
// Choose adjacent node pair which has the most available space. If
// only a rebalance can be performed on the pair, operating on
// underutilized nodes continues them on a path to deletion.
int leftPos;
if (leftAvail < rightAvail) {
if (leftNode != null) {
leftNode.releaseExclusive();
}
leftPos = parentFrame.mNodePos;
leftNode = node;
leftAvail = nodeAvail;
} else {
if (rightNode != null) {
rightNode.releaseExclusive();
}
leftPos = parentFrame.mNodePos - 2;
rightNode = node;
rightAvail = nodeAvail;
}
// Left node must always be marked dirty. Parent is already expected to be dirty.
if (mTree.markDirty(leftNode)) {
parentNode.updateChildRefId(leftPos, leftNode.mId);
}
// Determine if both nodes can fit in one node. If so, migrate and
// delete the right node.
int remaining = leftAvail + rightAvail - node.mPage.length + Node.TN_HEADER_SIZE;
if (remaining >= 0) {
// Migrate the entire contents of the right node into the left
// node, and then delete the right node.
rightNode.transferLeafToLeftAndDelete(mTree, leftNode);
rightNode = null;
parentNode.deleteChildRef(leftPos + 2);
} else if (false) { // TODO: testing
// Rebalance nodes, but don't delete anything. Right node must be dirtied too.
if (mTree.markDirty(rightNode)) {
parentNode.updateChildRefId(leftPos + 2, rightNode.mId);
}
// TODO: testing
if (leftNode.numKeys() == 1 || rightNode.numKeys() == 1) {
System.out.println("left avail: " + leftAvail + ", right avail: " + rightAvail +
", left pos: " + leftPos);
throw new Error("MUST REBALANCE: " + leftNode.numKeys() + ", " +
rightNode.numKeys());
}
/*
System.out.println("left avail: " + leftAvail + ", right avail: " + rightAvail +
", left pos: " + leftPos + ", mode: " + migrateMode);
*/
if (leftNode == node) {
// Rebalance towards left node, which is smaller.
// TODO
} else {
// Rebalance towards right node, which is smaller.
// TODO
}
}
mergeInternal(parentFrame, parentNode, leftNode, rightNode);
}
/**
* Caller must hold exclusive latch, which is released by this method.
*/
private void mergeInternal(TreeCursorFrame frame, Node node,
Node leftChildNode, Node rightChildNode)
throws IOException
{
up: {
if (node.shouldInternalMerge()) {
if (node.numKeys() > 0 || node != mTree.mRoot) {
// Continue merging up the tree.
break up;
}
// Delete the empty root node, eliminating a tree level.
// Note: By retaining child latches (although right might have
// been deleted), another thread is prevented from splitting
// the lone child. The lone child will become the new root.
// TODO: Investigate if this creates deadlocks.
node.rootDelete(mTree);
}
if (rightChildNode != null) {
rightChildNode.releaseExclusive();
}
leftChildNode.releaseExclusive();
node.releaseExclusive();
return;
}
if (rightChildNode != null) {
rightChildNode.releaseExclusive();
}
leftChildNode.releaseExclusive();
// At this point, only one node latch is held, and it should merge with
// a sibling node. Node is guaranteed to be a internal node.
TreeCursorFrame parentFrame = frame.mParentFrame;
node.releaseExclusive();
if (parentFrame == null) {
// Root node cannot merge into anything.
return;
}
Node parentNode = parentFrame.acquireExclusive();
if (parentNode.isLeaf()) {
throw new AssertionError("Parent node is a leaf");
}
Node leftNode, rightNode;
int nodeAvail;
while (true) {
if (parentNode.mSplit != null) {
parentNode = finishSplit(parentFrame, parentNode);
}
if (parentNode.numKeys() <= 0) {
if (parentNode.mId != Node.STUB_ID) {
// TODO: This shouldn't be a problem when internal nodes can be rebalanced.
//System.out.println("tiny internal node (2): " + (parentNode == mTree.mRoot));
}
parentNode.releaseExclusive();
return;
}
// Latch node and siblings in a strict left-to-right order to avoid deadlock.
int pos = parentFrame.mNodePos;
if (pos == 0) {
leftNode = null;
} else {
leftNode = latchChild(parentNode, pos - 2, false);
if (leftNode.mSplit != null) {
// Finish sibling split.
parentNode.insertSplitChildRef(mTree, pos - 2, leftNode);
continue;
}
}
node = frame.acquireExclusive();
// Double check that node should still merge.
if (!node.shouldMerge(nodeAvail = node.availableInternalBytes())) {
if (leftNode != null) {
leftNode.releaseExclusive();
}
node.releaseExclusive();
parentNode.releaseExclusive();
return;
}
if (pos >= parentNode.highestInternalPos()) {
rightNode = null;
} else {
rightNode = latchChild(parentNode, pos + 2, false);
if (rightNode.mSplit != null) {
// Finish sibling split.
if (leftNode != null) {
leftNode.releaseExclusive();
}
node.releaseExclusive();
parentNode.insertSplitChildRef(mTree, pos + 2, rightNode);
continue;
}
}
break;
}
// Select a left and right pair, and then don't operate directly on the
// original node and frame parameters afterwards. The original node
// ends up being referenced as a left or right member of the pair.
int leftAvail = leftNode == null ? -1 : leftNode.availableInternalBytes();
int rightAvail = rightNode == null ? -1 : rightNode.availableInternalBytes();
// Choose adjacent node pair which has the most available space. If
// only a rebalance can be performed on the pair, operating on
// underutilized nodes continues them on a path to deletion.
int leftPos;
if (leftAvail < rightAvail) {
if (leftNode != null) {
leftNode.releaseExclusive();
}
leftPos = parentFrame.mNodePos;
leftNode = node;
leftAvail = nodeAvail;
} else {
if (rightNode != null) {
rightNode.releaseExclusive();
}
leftPos = parentFrame.mNodePos - 2;
rightNode = node;
rightAvail = nodeAvail;
}
if (leftNode == null || rightNode == null) {
throw new AssertionError("No sibling node to merge into");
}
// Left node must always be marked dirty. Parent is already expected to be dirty.
if (mTree.markDirty(leftNode)) {
parentNode.updateChildRefId(leftPos, leftNode.mId);
}
// Determine if both nodes plus parent key can fit in one node. If so,
// migrate and delete the right node.
byte[] parentPage = parentNode.mPage;
int parentEntryLoc = Utils.readUnsignedShortLE
(parentPage, parentNode.mSearchVecStart + leftPos);
int parentEntryLen = Node.internalEntryLengthAtLoc(parentPage, parentEntryLoc);
int remaining = leftAvail - parentEntryLen
+ rightAvail - parentPage.length + (Node.TN_HEADER_SIZE - 2);
if (remaining >= 0) {
// Migrate the entire contents of the right node into the left
// node, and then delete the right node.
rightNode.transferInternalToLeftAndDelete
(mTree, leftNode, parentPage, parentEntryLoc, parentEntryLen);
rightNode = null;
parentNode.deleteChildRef(leftPos + 2);
} else if (false) { // TODO: testing
// Rebalance nodes, but don't delete anything. Right node must be dirtied too.
if (mTree.markDirty(rightNode)) {
parentNode.updateChildRefId(leftPos + 2, rightNode.mId);
}
// TODO: testing
if (leftNode.numKeys() == 1 || rightNode.numKeys() == 1) {
System.out.println("left avail: " + leftAvail + ", right avail: " + rightAvail +
", left pos: " + leftPos);
throw new Error("MUST REBALANCE: " + leftNode.numKeys() + ", " +
rightNode.numKeys());
}
/*
System.out.println("left avail: " + leftAvail + ", right avail: " + rightAvail +
", left pos: " + leftPos + ", mode: " + migrateMode);
*/
if (leftNode == node) {
// Rebalance towards left node, which is smaller.
// TODO
} else {
// Rebalance towards right node, which is smaller.
// TODO
}
}
// Tail call. I could just loop here, but this is simpler.
mergeInternal(parentFrame, parentNode, leftNode, rightNode);
}
/**
* Caller must hold exclusive latch and it must verify that node has
* split. Node latch is released if an exception is thrown.
*
* @return replacement node, still latched
*/
private Node finishSplit(final TreeCursorFrame frame, Node node) throws IOException {
Tree tree = mTree;
// FIXME: How to acquire shared commit lock without deadlock?
while (node == tree.mRoot) {
Node stub;
if (tree.hasStub()) {
// Don't wait for stub latch, to avoid deadlock. The stub stack
// is latched up upwards here, but downwards by cursors.
stub = tree.tryPopStub();
if (stub == null) {
// Latch not immediately available, so release root latch
// and try again. This implementation spins, but root
// splits are expected to be infrequent.
Thread waiter = node.getFirstQueuedThread();
node.releaseExclusive();
do {
Thread.yield();
} while (waiter != null && node.getFirstQueuedThread() == waiter);
node = frame.acquireExclusive();
if (node.mSplit == null) {
return node;
}
continue;
}
stub = tree.validateStub(stub);
} else {
stub = null;
}
try {
node.finishSplitRoot(tree, stub);
return node;
} catch (Throwable e) {
node.releaseExclusive();
throw Utils.rethrow(e);
}
}
final TreeCursorFrame parentFrame = frame.mParentFrame;
node.releaseExclusive();
// To avoid deadlock, ensure shared commit lock is held. Not all
// callers acquire the shared lock first, since they usually only read
// from the tree. Node latch has now been released, which should have
// been the only latch held, and so commit lock can be acquired without
// deadlock.
final Lock sharedCommitLock = tree.mDatabase.sharedCommitLock();
sharedCommitLock.lock();
try {
Node parentNode = parentFrame.acquireExclusive();
while (true) {
if (parentNode.mSplit != null) {
parentNode = finishSplit(parentFrame, parentNode);
}
node = frame.acquireExclusive();
if (node.mSplit == null) {
parentNode.releaseExclusive();
return node;
}
// FIXME: IOException; release latch
parentNode.insertSplitChildRef(tree, parentFrame.mNodePos, node);
}
} finally {
sharedCommitLock.unlock();
}
}
/**
* With parent held exclusively, returns child with exclusive latch held.
* If an exception is thrown, parent and child latches are always released.
*
* @return child node, possibly split
*/
private Node latchChild(Node parent, int childPos, boolean releaseParent)
throws IOException
{
Node childNode = parent.mChildNodes[childPos >> 1];
long childId = parent.retrieveChildRefId(childPos);
if (childNode != null && childId == childNode.mId) {
childNode.acquireExclusive();
// Need to check again in case evict snuck in.
if (childId != childNode.mId) {
childNode.releaseExclusive();
} else {
if (releaseParent) {
parent.releaseExclusive();
}
mTree.mDatabase.used(childNode);
return childNode;
}
}
return parent.loadChild(mTree.mDatabase, childPos, childId, releaseParent);
}
}
| true | true | private LockResult find(Transaction txn, byte[] key, int hash, int variant)
throws IOException
{
if (key == null) {
throw new NullPointerException("Key is null");
}
mKey = key;
mKeyHash = hash;
Node node;
TreeCursorFrame frame;
nearby: if (variant == VARIANT_NEARBY) {
frame = mLeaf;
if (frame == null) {
node = mTree.mRoot;
node.acquireExclusive();
frame = new TreeCursorFrame();
break nearby;
}
node = frame.acquireExclusive();
if (node.mSplit != null) {
node = finishSplit(frame, node);
}
int startPos = frame.mNodePos;
if (startPos < 0) {
startPos = ~startPos;
}
int pos = node.binarySearch(key, startPos);
if (pos >= 0) {
frame.mNotFoundKey = null;
frame.mNodePos = pos;
try {
LockResult result = tryLockKey(txn);
if (result == null) {
mValue = NOT_LOADED;
} else {
try {
mValue = mKeyOnly ? node.hasLeafValue(pos)
: node.retrieveLeafValue(mTree, pos);
return result;
} catch (Throwable e) {
mValue = NOT_LOADED;
throw Utils.rethrow(e);
}
}
} finally {
node.releaseExclusive();
}
return doLoad(txn);
} else if (pos != ~0 && ~pos <= node.highestLeafPos()) {
// Not found, but insertion pos is in bounds.
frame.mNotFoundKey = key;
frame.mNodePos = pos;
LockResult result = tryLockKey(txn);
if (result == null) {
mValue = NOT_LOADED;
node.releaseExclusive();
} else {
mValue = null;
node.releaseExclusive();
return result;
}
return doLoad(txn);
}
// Cannot be certain if position is in leaf node, so pop up.
mLeaf = null;
while (true) {
TreeCursorFrame parent = frame.pop();
if (parent == null) {
// Usually the root frame refers to the root node, but it
// can be wrong if the tree height is changing.
Node root = mTree.mRoot;
if (node != root) {
node.releaseExclusive();
root.acquireExclusive();
node = root;
}
break;
}
node.releaseExclusive();
frame = parent;
node = frame.acquireExclusive();
// Only search inside non-split nodes. It's easier to just pop
// up rather than finish or search the split.
if (node.mSplit != null) {
continue;
}
pos = Node.internalPos(node.binarySearch(key, frame.mNodePos));
if (pos == 0 || pos >= node.highestInternalPos()) {
// Cannot be certain if position is in this node, so pop up.
continue;
}
frame.mNodePos = pos;
try {
node = latchChild(node, pos, true);
} catch (Throwable e) {
throw cleanup(e, frame);
}
frame = new TreeCursorFrame(frame);
break;
}
} else {
// Other variants always discard existing frames.
node = mTree.mRoot;
frame = reset(node);
}
while (true) {
if (node.isLeaf()) {
int pos;
if (node.mSplit == null) {
pos = node.binarySearch(key);
frame.bind(node, pos);
} else {
pos = node.mSplit.binarySearch(node, key);
frame.bind(node, pos);
node = finishSplit(frame, node);
pos = frame.mNodePos;
}
mLeaf = frame;
LockResult result;
if (variant >= VARIANT_NO_LOCK) {
result = LockResult.UNOWNED;
} else if ((result = tryLockKey(txn)) == null) {
// Unable to immediately acquire the lock.
if (pos < 0) {
frame.mNotFoundKey = key;
}
mValue = NOT_LOADED;
node.releaseExclusive();
// This might fail to acquire the lock too, but the cursor
// is at the proper position, and with the proper state.
return doLoad(txn);
}
if (pos < 0) {
frame.mNotFoundKey = key;
mValue = null;
if (variant < VARIANT_RETAIN) {
node.releaseExclusive();
}
} else {
if (variant == VARIANT_CHECK) {
mValue = NOT_LOADED;
} else {
try {
mValue = mKeyOnly ? node.hasLeafValue(pos)
: node.retrieveLeafValue(mTree, pos);
} catch (Throwable e) {
mValue = NOT_LOADED;
node.releaseExclusive();
throw Utils.rethrow(e);
}
if (variant < VARIANT_NO_LOCK) {
node.releaseExclusive();
}
}
}
return result;
}
Split split = node.mSplit;
if (split == null) {
int childPos = Node.internalPos(node.binarySearch(key));
frame.bind(node, childPos);
try {
node = latchChild(node, childPos, true);
} catch (Throwable e) {
throw cleanup(e, frame);
}
} else {
// Follow search into split, binding this frame to the unsplit
// node as if it had not split. The binding will be corrected
// when split is finished.
final Node sibling = split.latchSibling();
final Node left, right;
if (split.mSplitRight) {
left = node;
right = sibling;
} else {
left = sibling;
right = node;
}
final Node selected;
final int selectedPos;
if (split.compare(key) < 0) {
selected = left;
selectedPos = Node.internalPos(left.binarySearch(key));
frame.bind(node, selectedPos);
right.releaseExclusive();
} else {
selected = right;
selectedPos = Node.internalPos(right.binarySearch(key));
frame.bind(node, left.highestInternalPos() + 2 + selectedPos);
left.releaseExclusive();
}
try {
node = latchChild(selected, selectedPos, true);
} catch (Throwable e) {
throw cleanup(e, frame);
}
}
frame = new TreeCursorFrame(frame);
}
}
| private LockResult find(Transaction txn, byte[] key, int hash, int variant)
throws IOException
{
if (key == null) {
throw new NullPointerException("Key is null");
}
mKey = key;
mKeyHash = hash;
Node node;
TreeCursorFrame frame;
nearby: if (variant == VARIANT_NEARBY) {
frame = mLeaf;
if (frame == null) {
node = mTree.mRoot;
node.acquireExclusive();
frame = new TreeCursorFrame();
break nearby;
}
node = frame.acquireExclusive();
if (node.mSplit != null) {
node = finishSplit(frame, node);
}
int startPos = frame.mNodePos;
if (startPos < 0) {
startPos = ~startPos;
}
int pos = node.binarySearch(key, startPos);
if (pos >= 0) {
frame.mNotFoundKey = null;
frame.mNodePos = pos;
try {
LockResult result = tryLockKey(txn);
if (result == null) {
mValue = NOT_LOADED;
} else {
try {
mValue = mKeyOnly ? node.hasLeafValue(pos)
: node.retrieveLeafValue(mTree, pos);
return result;
} catch (Throwable e) {
mValue = NOT_LOADED;
throw Utils.rethrow(e);
}
}
} finally {
node.releaseExclusive();
}
return doLoad(txn);
} else if (pos != ~0 && ~pos <= node.highestLeafPos()) {
// Not found, but insertion pos is in bounds.
frame.mNotFoundKey = key;
frame.mNodePos = pos;
LockResult result = tryLockKey(txn);
if (result == null) {
mValue = NOT_LOADED;
node.releaseExclusive();
} else {
mValue = null;
node.releaseExclusive();
return result;
}
return doLoad(txn);
}
// Cannot be certain if position is in leaf node, so pop up.
mLeaf = null;
while (true) {
TreeCursorFrame parent = frame.pop();
if (parent == null) {
// Usually the root frame refers to the root node, but it
// can be wrong if the tree height is changing.
Node root = mTree.mRoot;
if (node != root) {
node.releaseExclusive();
root.acquireExclusive();
node = root;
}
break;
}
node.releaseExclusive();
frame = parent;
node = frame.acquireExclusive();
// Only search inside non-split nodes. It's easier to just pop
// up rather than finish or search the split.
if (node.mSplit != null) {
continue;
}
pos = Node.internalPos(node.binarySearch(key, frame.mNodePos));
if (pos == 0 || pos >= node.highestInternalPos()) {
// Cannot be certain if position is in this node, so pop up.
continue;
}
frame.mNodePos = pos;
try {
node = latchChild(node, pos, true);
} catch (Throwable e) {
throw cleanup(e, frame);
}
frame = new TreeCursorFrame(frame);
break;
}
} else {
// Other variants always discard existing frames.
node = mTree.mRoot;
frame = reset(node);
}
while (true) {
if (node.isLeaf()) {
int pos;
if (node.mSplit == null) {
pos = node.binarySearch(key);
frame.bind(node, pos);
} else {
pos = node.mSplit.binarySearch(node, key);
frame.bind(node, pos);
if (pos < 0) {
// The finishSplit method will release the latch, and
// so the frame must be completely defined first.
frame.mNotFoundKey = key;
}
node = finishSplit(frame, node);
pos = frame.mNodePos;
}
mLeaf = frame;
LockResult result;
if (variant >= VARIANT_NO_LOCK) {
result = LockResult.UNOWNED;
} else if ((result = tryLockKey(txn)) == null) {
// Unable to immediately acquire the lock.
if (pos < 0) {
frame.mNotFoundKey = key;
}
mValue = NOT_LOADED;
node.releaseExclusive();
// This might fail to acquire the lock too, but the cursor
// is at the proper position, and with the proper state.
return doLoad(txn);
}
if (pos < 0) {
frame.mNotFoundKey = key;
mValue = null;
if (variant < VARIANT_RETAIN) {
node.releaseExclusive();
}
} else {
if (variant == VARIANT_CHECK) {
mValue = NOT_LOADED;
} else {
try {
mValue = mKeyOnly ? node.hasLeafValue(pos)
: node.retrieveLeafValue(mTree, pos);
} catch (Throwable e) {
mValue = NOT_LOADED;
node.releaseExclusive();
throw Utils.rethrow(e);
}
if (variant < VARIANT_NO_LOCK) {
node.releaseExclusive();
}
}
}
return result;
}
Split split = node.mSplit;
if (split == null) {
int childPos = Node.internalPos(node.binarySearch(key));
frame.bind(node, childPos);
try {
node = latchChild(node, childPos, true);
} catch (Throwable e) {
throw cleanup(e, frame);
}
} else {
// Follow search into split, binding this frame to the unsplit
// node as if it had not split. The binding will be corrected
// when split is finished.
final Node sibling = split.latchSibling();
final Node left, right;
if (split.mSplitRight) {
left = node;
right = sibling;
} else {
left = sibling;
right = node;
}
final Node selected;
final int selectedPos;
if (split.compare(key) < 0) {
selected = left;
selectedPos = Node.internalPos(left.binarySearch(key));
frame.bind(node, selectedPos);
right.releaseExclusive();
} else {
selected = right;
selectedPos = Node.internalPos(right.binarySearch(key));
frame.bind(node, left.highestInternalPos() + 2 + selectedPos);
left.releaseExclusive();
}
try {
node = latchChild(selected, selectedPos, true);
} catch (Throwable e) {
throw cleanup(e, frame);
}
}
frame = new TreeCursorFrame(frame);
}
}
|
diff --git a/javasvn/src/org/tmatesoft/svn/core/internal/util/SVNTimeUtil.java b/javasvn/src/org/tmatesoft/svn/core/internal/util/SVNTimeUtil.java
index 05ec135f0..83fb51c50 100644
--- a/javasvn/src/org/tmatesoft/svn/core/internal/util/SVNTimeUtil.java
+++ b/javasvn/src/org/tmatesoft/svn/core/internal/util/SVNTimeUtil.java
@@ -1,90 +1,97 @@
/*
* ====================================================================
* Copyright (c) 2004 TMate Software Ltd. All rights reserved.
*
* This software is licensed as described in the file COPYING, which you should
* have received as part of this distribution. The terms are also available at
* http://tmate.org/svn/license.html. If newer versions of this license are
* posted there, you may use a newer version instead, at your option.
* ====================================================================
*/
package org.tmatesoft.svn.core.internal.util;
import java.text.DateFormat;
import java.text.FieldPosition;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.TimeZone;
/**
* @version 1.0
* @author TMate Software Ltd.
*/
public class SVNTimeUtil {
private static final DateFormat ISO8601_FORMAT_OUT = new SimpleDateFormat(
"yyyy-MM-dd'T'HH:mm:ss.SSS'000Z'");
private static final Calendar CALENDAR = Calendar.getInstance(TimeZone.getTimeZone("GMT"));
private static final Date NULL = new Date(0);
static {
ISO8601_FORMAT_OUT.setTimeZone(TimeZone.getTimeZone("GMT"));
}
public static void formatDate(Date date, StringBuffer buffer) {
ISO8601_FORMAT_OUT.format(date, buffer, new FieldPosition(0));
}
public static String formatDate(Date date) {
if (date == null || date.getTime() == 0) {
return null;
}
return ISO8601_FORMAT_OUT.format(date);
}
public static Date parseDate(String str) {
if (str == null) {
return NULL;
}
try {
int year = Integer.parseInt(str.substring(0, 4));
int month = Integer.parseInt(str.substring(5, 7));
int date = Integer.parseInt(str.substring(8, 10));
int hour = Integer.parseInt(str.substring(11, 13));
int min = Integer.parseInt(str.substring(14, 16));
- int sec = Integer.parseInt(str.substring(17, 19));
- int ms = Integer.parseInt(str.substring(20, 23));
+ int sec;
+ int ms;
+ if (str.charAt(18) == '.') {
+ sec = Integer.parseInt(str.substring(17, 18));
+ ms = Integer.parseInt(str.substring(19, 22));
+ } else {
+ sec = Integer.parseInt(str.substring(17, 19));
+ ms = Integer.parseInt(str.substring(20, 23));
+ }
CALENDAR.clear();
CALENDAR.set(year, month - 1, date, hour, min, sec);
CALENDAR.set(Calendar.MILLISECOND, ms);
return CALENDAR.getTime();
} catch (Throwable th) {
//
}
return NULL;
}
public static long parseDateAsLong(String str) {
if (str == null) {
return -1;
}
int year = Integer.parseInt(str.substring(0, 4));
int month = Integer.parseInt(str.substring(5, 7));
int date = Integer.parseInt(str.substring(8, 10));
int hour = Integer.parseInt(str.substring(11, 13));
int min = Integer.parseInt(str.substring(14, 16));
int sec = Integer.parseInt(str.substring(17, 19));
int ms = Integer.parseInt(str.substring(20, 23));
CALENDAR.clear();
CALENDAR.set(year, month - 1, date, hour, min, sec);
CALENDAR.set(Calendar.MILLISECOND, ms);
return CALENDAR.getTimeInMillis();
}
}
| true | true | public static Date parseDate(String str) {
if (str == null) {
return NULL;
}
try {
int year = Integer.parseInt(str.substring(0, 4));
int month = Integer.parseInt(str.substring(5, 7));
int date = Integer.parseInt(str.substring(8, 10));
int hour = Integer.parseInt(str.substring(11, 13));
int min = Integer.parseInt(str.substring(14, 16));
int sec = Integer.parseInt(str.substring(17, 19));
int ms = Integer.parseInt(str.substring(20, 23));
CALENDAR.clear();
CALENDAR.set(year, month - 1, date, hour, min, sec);
CALENDAR.set(Calendar.MILLISECOND, ms);
return CALENDAR.getTime();
} catch (Throwable th) {
//
}
return NULL;
}
| public static Date parseDate(String str) {
if (str == null) {
return NULL;
}
try {
int year = Integer.parseInt(str.substring(0, 4));
int month = Integer.parseInt(str.substring(5, 7));
int date = Integer.parseInt(str.substring(8, 10));
int hour = Integer.parseInt(str.substring(11, 13));
int min = Integer.parseInt(str.substring(14, 16));
int sec;
int ms;
if (str.charAt(18) == '.') {
sec = Integer.parseInt(str.substring(17, 18));
ms = Integer.parseInt(str.substring(19, 22));
} else {
sec = Integer.parseInt(str.substring(17, 19));
ms = Integer.parseInt(str.substring(20, 23));
}
CALENDAR.clear();
CALENDAR.set(year, month - 1, date, hour, min, sec);
CALENDAR.set(Calendar.MILLISECOND, ms);
return CALENDAR.getTime();
} catch (Throwable th) {
//
}
return NULL;
}
|
diff --git a/YuiLibrary/src/main/java/ru/sviridov/yuilibrary/MainLibActivity.java b/YuiLibrary/src/main/java/ru/sviridov/yuilibrary/MainLibActivity.java
index 628d409..0d241ae 100644
--- a/YuiLibrary/src/main/java/ru/sviridov/yuilibrary/MainLibActivity.java
+++ b/YuiLibrary/src/main/java/ru/sviridov/yuilibrary/MainLibActivity.java
@@ -1,32 +1,32 @@
package ru.sviridov.yuilibrary;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class MainLibActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lib_main);
setTitle(R.string.lib_title);
TextView viewById = (TextView) findViewById(R.id.tvInfo);
viewById.setText(R.string.info_text);
viewById.setTextColor(getResources().getColor(android.R.color.holo_blue_bright));
- Toast.makeText(this,"started",Toast.LENGTH_SHORT).show();
+ Toast.makeText(this,"ended",Toast.LENGTH_SHORT).show();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
}
| true | true | protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lib_main);
setTitle(R.string.lib_title);
TextView viewById = (TextView) findViewById(R.id.tvInfo);
viewById.setText(R.string.info_text);
viewById.setTextColor(getResources().getColor(android.R.color.holo_blue_bright));
Toast.makeText(this,"started",Toast.LENGTH_SHORT).show();
}
| protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.lib_main);
setTitle(R.string.lib_title);
TextView viewById = (TextView) findViewById(R.id.tvInfo);
viewById.setText(R.string.info_text);
viewById.setTextColor(getResources().getColor(android.R.color.holo_blue_bright));
Toast.makeText(this,"ended",Toast.LENGTH_SHORT).show();
}
|
diff --git a/src/java/org/jruby/ext/openssl/x509store/Lookup.java b/src/java/org/jruby/ext/openssl/x509store/Lookup.java
index 4f1a305..e9dbe36 100644
--- a/src/java/org/jruby/ext/openssl/x509store/Lookup.java
+++ b/src/java/org/jruby/ext/openssl/x509store/Lookup.java
@@ -1,551 +1,551 @@
/***** BEGIN LICENSE BLOCK *****
* Version: CPL 1.0/GPL 2.0/LGPL 2.1
*
* The contents of this file are subject to the Common Public
* License Version 1.0 (the "License"); you may not use this file
* except in compliance with the License. You may obtain a copy of
* the License at http://www.eclipse.org/legal/cpl-v10.html
*
* Software distributed under the License is distributed on an "AS
* IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
* implied. See the License for the specific language governing
* rights and limitations under the License.
*
* Copyright (C) 2006 Ola Bini <[email protected]>
*
* Alternatively, the contents of this file may be used under the terms of
* either of the GNU General Public License Version 2 or later (the "GPL"),
* or the GNU Lesser General Public License Version 2.1 or later (the "LGPL"),
* in which case the provisions of the GPL or the LGPL are applicable instead
* of those above. If you wish to allow use of your version of this file only
* under the terms of either the GPL or the LGPL, and not to allow others to
* use your version of this file under the terms of the CPL, indicate your
* decision by deleting the provisions above and replace them with the notice
* and other provisions required by the GPL or the LGPL. If you do not delete
* the provisions above, a recipient may use your version of this file under
* the terms of any one of the CPL, the GPL or the LGPL.
***** END LICENSE BLOCK *****/
package org.jruby.ext.openssl.x509store;
import java.io.File;
import java.io.FileReader;
import java.io.Reader;
import java.io.InputStream;
import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.InputStreamReader;
import java.math.BigInteger;
import java.security.cert.CertificateFactory;
import java.security.cert.X509Certificate;
import java.security.cert.CRL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import org.jruby.ext.openssl.OpenSSLReal;
/**
* X509_LOOKUP
*
* @author <a href="mailto:[email protected]">Ola Bini</a>
*/
public class Lookup {
public boolean init;
public boolean skip;
public LookupMethod method;
public Object methodData;
public Store store;
public final static int FILE_LOAD = 1;
public final static int ADD_DIR = 2;
/**
* c: X509_LOOKUP_new
*/
public Lookup(LookupMethod method) throws Exception {
init=false;
skip=false;
this.method=method;
methodData=null;
store=null;
if(method.newItem != null && method.newItem != Function1.EMPTY && method.newItem.call(this) == 0) {
throw new Exception();
}
}
/**
* c: X509_LOOKUP_load_file
*/
public int loadFile(CertificateFile.Path file) throws Exception {
return control(FILE_LOAD,file.name,file.type,null);
}
/**
* c: X509_LOOKUP_add_dir
*/
public int addDir(CertificateHashDir.Dir dir) throws Exception {
return control(ADD_DIR,dir.name,dir.type,null);
}
/**
* c: X509_LOOKUP_hash_dir
*/
public static LookupMethod hashDirLookup() {
return x509DirectoryLookup;
}
/**
* c: X509_LOOKUP_file
*/
public static LookupMethod fileLookup() {
return x509FileLookup;
}
/**
* c: X509_LOOKUP_ctrl
*/
public int control(int cmd, String argc, long argl, String[] ret) throws Exception {
if(method == null) {
return -1;
}
if(method.control != null && method.control != Function5.EMPTY) {
return method.control.call(this,new Integer(cmd),argc,new Long(argl),ret);
} else {
return 1;
}
}
/**
* c: X509_LOOKUP_load_cert_file
*/
public int loadCertificateFile(String file, int type) throws Exception {
if(file == null) {
return 1;
}
int count = 0;
int ret = 0;
InputStream in = new BufferedInputStream(new FileInputStream(file));
X509AuxCertificate x = null;
if(type == X509Utils.X509_FILETYPE_PEM) {
Reader r = new InputStreamReader(in);
for(;;) {
x = PEMInputOutput.readX509Aux(r,null);
if(null == x) {
break;
}
int i = store.addCertificate(x);
if(i == 0) {
return ret;
}
count++;
x = null;
}
ret = count;
} else if(type == X509Utils.X509_FILETYPE_ASN1) {
CertificateFactory cf = CertificateFactory.getInstance("X.509",OpenSSLReal.PROVIDER);
x = StoreContext.ensureAux((X509Certificate)cf.generateCertificate(in));
if(x == null) {
X509Error.addError(13);
return ret;
}
int i = store.addCertificate(x);
if(i == 0) {
return ret;
}
ret = i;
} else {
X509Error.addError(X509Utils.X509_R_BAD_X509_FILETYPE);
}
return ret;
}
/**
* c: X509_LOOKUP_load_crl_file
*/
public int loadCRLFile(String file, int type) throws Exception {
if(file == null) {
return 1;
}
int count = 0;
int ret = 0;
InputStream in = new BufferedInputStream(new FileInputStream(file));
CRL x = null;
if(type == X509Utils.X509_FILETYPE_PEM) {
Reader r = new InputStreamReader(in);
for(;;) {
x = PEMInputOutput.readX509CRL(r,null);;
if(null == x) {
break;
}
int i = store.addCRL(x);
if(i == 0) {
return ret;
}
count++;
x = null;
}
ret = count;
} else if(type == X509Utils.X509_FILETYPE_ASN1) {
CertificateFactory cf = CertificateFactory.getInstance("X.509",OpenSSLReal.PROVIDER);
x = cf.generateCRL(in);
if(x == null) {
X509Error.addError(13);
return ret;
}
int i = store.addCRL(x);
if(i == 0) {
return ret;
}
ret = i;
} else {
X509Error.addError(X509Utils.X509_R_BAD_X509_FILETYPE);
}
return ret;
}
/**
* c: X509_LOOKUP_load_cert_crl_file
*/
public int loadCertificateOrCRLFile(String file, int type) throws Exception {
if(type != X509Utils.X509_FILETYPE_PEM) {
return loadCertificateFile(file,type);
}
int count = 0;
Reader r = new FileReader(file);
for(;;) {
Object v = PEMInputOutput.readPEM(r,null);
if(null == v) {
break;
}
if(v instanceof X509Certificate) {
store.addCertificate(StoreContext.ensureAux((X509Certificate)v));
count++;
} else if(v instanceof CRL) {
store.addCRL((CRL)v);
count++;
}
}
return count;
}
/**
* c: X509_LOOKUP_free
*/
public void free() throws Exception {
if(method != null && method.free != null && method.free != Function1.EMPTY) {
method.free.call(this);
}
}
/**
* c: X509_LOOKUP_init
*/
public int init() throws Exception {
if(method == null) {
return 0;
}
if(method.init != null && method.init != Function1.EMPTY) {
return method.init.call(this);
}
return 1;
}
/**
* c: X509_LOOKUP_by_subject
*/
public int bySubject(int type, Name name,X509Object[] ret) throws Exception {
if(method == null || method.getBySubject == null || method.getBySubject == Function4.EMPTY) {
return X509Utils.X509_LU_FAIL;
}
if(skip) {
return 0;
}
return method.getBySubject.call(this,new Integer(type),name,ret);
}
/**
* c: X509_LOOKUP_by_issuer_serial
*/
public int byIssuerSerialNumber(int type, Name name,BigInteger serial, X509Object[] ret) throws Exception {
if(method == null || method.getByIssuerSerialNumber == null || method.getByIssuerSerialNumber == Function5.EMPTY) {
return X509Utils.X509_LU_FAIL;
}
return method.getByIssuerSerialNumber.call(this,new Integer(type),name,serial,ret);
}
/**
* c: X509_LOOKUP_by_fingerprint
*/
public int byFingerprint(int type,String bytes, X509Object[] ret) throws Exception {
if(method == null || method.getByFingerprint == null || method.getByFingerprint == Function4.EMPTY) {
return X509Utils.X509_LU_FAIL;
}
return method.getByFingerprint.call(this,new Integer(type),bytes,ret);
}
/**
* c: X509_LOOKUP_by_alias
*/
public int byAlias(int type, String str, X509Object[] ret) throws Exception {
if(method == null || method.getByAlias == null || method.getByAlias == Function4.EMPTY) {
return X509Utils.X509_LU_FAIL;
}
return method.getByAlias.call(this,new Integer(type),str,ret);
}
/**
* c: X509_LOOKUP_shutdown
*/
public int shutdown() throws Exception {
if(method == null) {
return 0;
}
if(method.shutdown != null && method.shutdown != Function1.EMPTY) {
return method.shutdown.call(this);
}
return 1;
}
/**
* c: x509_file_lookup
*/
private final static LookupMethod x509FileLookup = new LookupMethod();
/**
* c: x509_dir_lookup
*/
private final static LookupMethod x509DirectoryLookup = new LookupMethod();
static {
x509FileLookup.name = "Load file into cache";
x509FileLookup.control = new ByFile();
x509DirectoryLookup.name = "Load certs from files in a directory";
x509DirectoryLookup.newItem = new NewLookupDir();
x509DirectoryLookup.free = new FreeLookupDir();
x509DirectoryLookup.control = new LookupDirControl();
x509DirectoryLookup.getBySubject = new GetCertificateBySubject();
}
/**
* c: by_file_ctrl
*/
private static class ByFile implements LookupMethod.ControlFunction {
public int call(Object _ctx, Object _cmd, Object _argp, Object _argl, Object _ret) throws Exception {
Lookup ctx = (Lookup)_ctx;
int cmd = ((Integer)_cmd).intValue();
String argp = (String)_argp;
long argl = ((Long)_argl).longValue();
int ok = 0;
String file = null;
switch(cmd) {
case X509Utils.X509_L_FILE_LOAD:
if (argl == X509Utils.X509_FILETYPE_DEFAULT) {
try {
file = System.getenv(X509Utils.getDefaultCertificateFileEnvironment());
} catch (Error error) {
}
if (file != null) {
ok = ctx.loadCertificateOrCRLFile(file, X509Utils.X509_FILETYPE_PEM) != 0 ? 1 : 0;
} else {
ok = (ctx.loadCertificateOrCRLFile(X509Utils.getDefaultCertificateFile(), X509Utils.X509_FILETYPE_PEM) != 0) ? 1 : 0;
}
if (ok == 0) {
X509Error.addError(X509Utils.X509_R_LOADING_DEFAULTS);
}
} else {
if (argl == X509Utils.X509_FILETYPE_PEM) {
ok = (ctx.loadCertificateOrCRLFile(argp, X509Utils.X509_FILETYPE_PEM) != 0) ? 1 : 0;
} else {
ok = (ctx.loadCertificateFile(argp, (int) argl) != 0) ? 1 : 0;
}
}
break;
}
return ok;
}
}
/**
* c: BY_DIR, lookup_dir_st
*/
private static class LookupDir {
StringBuffer buffer;
List<String> dirs;
List<Integer> dirsType;
}
/**
* c: new_dir
*/
private static class NewLookupDir implements LookupMethod.NewItemFunction {
public int call(Object _lu) {
Lookup lu = (Lookup)_lu;
LookupDir a = new LookupDir();
a.buffer = new StringBuffer();
a.dirs = new ArrayList<String>();
a.dirsType = new ArrayList<Integer>();
lu.methodData = a;
return 1;
}
}
/**
* c: free_dir
*/
private static class FreeLookupDir implements LookupMethod.FreeFunction {
public int call(Object _lu) {
Lookup lu = (Lookup)_lu;
LookupDir a = (LookupDir)lu.methodData;
a.dirs = null;
a.dirsType = null;
a.buffer = null;
lu.methodData = null;
return -1;
}
}
/**
* c: dir_ctrl
*/
private static class LookupDirControl implements LookupMethod.ControlFunction {
public int call(Object _ctx, Object _cmd, Object _argp, Object _argl, Object _retp) {
Lookup ctx = (Lookup)_ctx;
int cmd = ((Integer)_cmd).intValue();
String argp = (String)_argp;
long argl = ((Long)_argl).longValue();
int ret = 0;
LookupDir ld = (LookupDir)ctx.methodData;
String dir = null;
switch(cmd) {
case X509Utils.X509_L_ADD_DIR:
if(argl == X509Utils.X509_FILETYPE_DEFAULT) {
try {
dir = System.getenv(X509Utils.getDefaultCertificateDirectoryEnvironment());
} catch (Error error) {
}
if(null != dir) {
ret = addCertificateDirectory(ld,dir,X509Utils.X509_FILETYPE_PEM);
} else {
ret = addCertificateDirectory(ld,X509Utils.getDefaultCertificateDirectory(),X509Utils.X509_FILETYPE_PEM);
}
if(ret == 0) {
X509Error.addError(X509Utils.X509_R_LOADING_CERT_DIR);
}
} else {
ret = addCertificateDirectory(ld,argp,(int)argl);
}
break;
}
return ret;
}
/**
* c: add_cert_dir
*/
private int addCertificateDirectory(LookupDir ctx,String dir,int type) {
if(dir == null || "".equals(dir)) {
X509Error.addError(X509Utils.X509_R_INVALID_DIRECTORY);
return 0;
}
String[] dirs = dir.split(System.getProperty("path.separator"));
for(int i=0;i<dirs.length;i++) {
if(dirs[i].length() == 0) {
continue;
}
if(ctx.dirs.contains(dirs[i])) {
continue;
}
ctx.dirsType.add(type);
ctx.dirs.add(dirs[i]);
}
return 1;
}
}
/**
* c: get_cert_by_subject
*/
private static class GetCertificateBySubject implements LookupMethod.BySubjectFunction {
public int call(Object _xl, Object _type, Object _name, Object _ret) throws Exception {
Lookup x1 = (Lookup)_xl;
int type = ((Integer)_type).intValue();
Name name = (Name)_name;
X509Object[] ret = (X509Object[])_ret;
X509Object tmp = null;
int ok = 0;
StringBuffer b = new StringBuffer();
if(null == name) {
return 0;
}
String postfix = "";
if(type == X509Utils.X509_LU_X509) {
} else if(type == X509Utils.X509_LU_CRL) {
postfix = "r";
} else {
X509Error.addError(X509Utils.X509_R_WRONG_LOOKUP_TYPE);
return ok;
}
LookupDir ctx = (LookupDir)x1.methodData;
long h = name.hash();
Iterator<Integer> iter = ctx.dirsType.iterator();
for(String cdir : ctx.dirs) {
int tp = iter.next();
int k = 0;
for(;;) {
- b.append(String.format("%s/%08lx.%s%d",new Object[]{cdir,new Long(h),postfix,new Integer(k)}));
+ b.append(String.format("%s/%08x.%s%d",new Object[]{cdir,new Long(h),postfix,new Integer(k)}));
k++;
if(!(new File(b.toString()).exists())) {
break;
}
if(type == X509Utils.X509_LU_X509) {
if((x1.loadCertificateFile(b.toString(),tp)) == 0) {
break;
}
} else if(type == X509Utils.X509_LU_CRL) {
if((x1.loadCRLFile(b.toString(),tp)) == 0) {
break;
}
}
}
synchronized(X509Utils.CRYPTO_LOCK_X509_STORE) {
tmp = null;
for(X509Object o : x1.store.objs) {
if(o.type() == type && o.isName(name)) {
tmp = o;
break;
}
}
}
if(tmp != null) {
ok = 1;
ret[0] = tmp;
break;
}
}
return ok;
}
}
}// X509_LOOKUP
| true | true | public int call(Object _xl, Object _type, Object _name, Object _ret) throws Exception {
Lookup x1 = (Lookup)_xl;
int type = ((Integer)_type).intValue();
Name name = (Name)_name;
X509Object[] ret = (X509Object[])_ret;
X509Object tmp = null;
int ok = 0;
StringBuffer b = new StringBuffer();
if(null == name) {
return 0;
}
String postfix = "";
if(type == X509Utils.X509_LU_X509) {
} else if(type == X509Utils.X509_LU_CRL) {
postfix = "r";
} else {
X509Error.addError(X509Utils.X509_R_WRONG_LOOKUP_TYPE);
return ok;
}
LookupDir ctx = (LookupDir)x1.methodData;
long h = name.hash();
Iterator<Integer> iter = ctx.dirsType.iterator();
for(String cdir : ctx.dirs) {
int tp = iter.next();
int k = 0;
for(;;) {
b.append(String.format("%s/%08lx.%s%d",new Object[]{cdir,new Long(h),postfix,new Integer(k)}));
k++;
if(!(new File(b.toString()).exists())) {
break;
}
if(type == X509Utils.X509_LU_X509) {
if((x1.loadCertificateFile(b.toString(),tp)) == 0) {
break;
}
} else if(type == X509Utils.X509_LU_CRL) {
if((x1.loadCRLFile(b.toString(),tp)) == 0) {
break;
}
}
}
synchronized(X509Utils.CRYPTO_LOCK_X509_STORE) {
tmp = null;
for(X509Object o : x1.store.objs) {
if(o.type() == type && o.isName(name)) {
tmp = o;
break;
}
}
}
if(tmp != null) {
ok = 1;
ret[0] = tmp;
break;
}
}
return ok;
}
| public int call(Object _xl, Object _type, Object _name, Object _ret) throws Exception {
Lookup x1 = (Lookup)_xl;
int type = ((Integer)_type).intValue();
Name name = (Name)_name;
X509Object[] ret = (X509Object[])_ret;
X509Object tmp = null;
int ok = 0;
StringBuffer b = new StringBuffer();
if(null == name) {
return 0;
}
String postfix = "";
if(type == X509Utils.X509_LU_X509) {
} else if(type == X509Utils.X509_LU_CRL) {
postfix = "r";
} else {
X509Error.addError(X509Utils.X509_R_WRONG_LOOKUP_TYPE);
return ok;
}
LookupDir ctx = (LookupDir)x1.methodData;
long h = name.hash();
Iterator<Integer> iter = ctx.dirsType.iterator();
for(String cdir : ctx.dirs) {
int tp = iter.next();
int k = 0;
for(;;) {
b.append(String.format("%s/%08x.%s%d",new Object[]{cdir,new Long(h),postfix,new Integer(k)}));
k++;
if(!(new File(b.toString()).exists())) {
break;
}
if(type == X509Utils.X509_LU_X509) {
if((x1.loadCertificateFile(b.toString(),tp)) == 0) {
break;
}
} else if(type == X509Utils.X509_LU_CRL) {
if((x1.loadCRLFile(b.toString(),tp)) == 0) {
break;
}
}
}
synchronized(X509Utils.CRYPTO_LOCK_X509_STORE) {
tmp = null;
for(X509Object o : x1.store.objs) {
if(o.type() == type && o.isName(name)) {
tmp = o;
break;
}
}
}
if(tmp != null) {
ok = 1;
ret[0] = tmp;
break;
}
}
return ok;
}
|
diff --git a/spring-integration-core/src/test/java/org/springframework/integration/adapter/AdapterBusTests.java b/spring-integration-core/src/test/java/org/springframework/integration/adapter/AdapterBusTests.java
index 895859a0c3..be60e7954e 100644
--- a/spring-integration-core/src/test/java/org/springframework/integration/adapter/AdapterBusTests.java
+++ b/spring-integration-core/src/test/java/org/springframework/integration/adapter/AdapterBusTests.java
@@ -1,49 +1,50 @@
/*
* Copyright 2002-2007 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.springframework.integration.adapter;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import java.io.IOException;
import org.junit.Test;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
/**
* @author Mark Fisher
*/
public class AdapterBusTests {
@Test
public void testAdapters() throws IOException, InterruptedException {
AbstractApplicationContext context = new ClassPathXmlApplicationContext("adapterBusTests.xml", this.getClass());
TestSink sink = (TestSink) context.getBean("sink");
assertNull(sink.get());
context.start();
String result = null;
int attempts = 0;
- while (result == null && attempts++ < 10) {
+ while (result == null && attempts++ < 100) {
Thread.sleep(5);
result = sink.get();
}
assertNotNull(result);
+ context.close();
}
}
| false | true | public void testAdapters() throws IOException, InterruptedException {
AbstractApplicationContext context = new ClassPathXmlApplicationContext("adapterBusTests.xml", this.getClass());
TestSink sink = (TestSink) context.getBean("sink");
assertNull(sink.get());
context.start();
String result = null;
int attempts = 0;
while (result == null && attempts++ < 10) {
Thread.sleep(5);
result = sink.get();
}
assertNotNull(result);
}
| public void testAdapters() throws IOException, InterruptedException {
AbstractApplicationContext context = new ClassPathXmlApplicationContext("adapterBusTests.xml", this.getClass());
TestSink sink = (TestSink) context.getBean("sink");
assertNull(sink.get());
context.start();
String result = null;
int attempts = 0;
while (result == null && attempts++ < 100) {
Thread.sleep(5);
result = sink.get();
}
assertNotNull(result);
context.close();
}
|
diff --git a/src/main/java/org/mozilla/gecko/tokenserver/TokenServerClient.java b/src/main/java/org/mozilla/gecko/tokenserver/TokenServerClient.java
index d366c8e6e..e13d0fe3c 100644
--- a/src/main/java/org/mozilla/gecko/tokenserver/TokenServerClient.java
+++ b/src/main/java/org/mozilla/gecko/tokenserver/TokenServerClient.java
@@ -1,286 +1,286 @@
/* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/. */
package org.mozilla.gecko.tokenserver;
import java.io.IOException;
import java.net.URI;
import java.security.GeneralSecurityException;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Executor;
import org.json.simple.JSONObject;
import org.mozilla.gecko.background.common.log.Logger;
import org.mozilla.gecko.background.fxa.SkewHandler;
import org.mozilla.gecko.sync.ExtendedJSONObject;
import org.mozilla.gecko.sync.NonArrayJSONException;
import org.mozilla.gecko.sync.NonObjectJSONException;
import org.mozilla.gecko.sync.UnexpectedJSONException.BadRequiredFieldJSONException;
import org.mozilla.gecko.sync.net.AuthHeaderProvider;
import org.mozilla.gecko.sync.net.BaseResource;
import org.mozilla.gecko.sync.net.BaseResourceDelegate;
import org.mozilla.gecko.sync.net.BrowserIDAuthHeaderProvider;
import org.mozilla.gecko.sync.net.SyncResponse;
import org.mozilla.gecko.tokenserver.TokenServerException.TokenServerConditionsRequiredException;
import org.mozilla.gecko.tokenserver.TokenServerException.TokenServerInvalidCredentialsException;
import org.mozilla.gecko.tokenserver.TokenServerException.TokenServerMalformedRequestException;
import org.mozilla.gecko.tokenserver.TokenServerException.TokenServerMalformedResponseException;
import org.mozilla.gecko.tokenserver.TokenServerException.TokenServerUnknownServiceException;
import ch.boye.httpclientandroidlib.HttpHeaders;
import ch.boye.httpclientandroidlib.HttpResponse;
import ch.boye.httpclientandroidlib.client.ClientProtocolException;
import ch.boye.httpclientandroidlib.client.methods.HttpRequestBase;
import ch.boye.httpclientandroidlib.impl.client.DefaultHttpClient;
import ch.boye.httpclientandroidlib.message.BasicHeader;
/**
* HTTP client for interacting with the Mozilla Services Token Server API v1.0,
* as documented at
* <a href="http://docs.services.mozilla.com/token/apis.html">http://docs.services.mozilla.com/token/apis.html</a>.
* <p>
* A token server accepts some authorization credential and returns a different
* authorization credential. Usually, it used to exchange a public-key
* authorization token that is expensive to validate for a symmetric-key
* authorization that is cheap to validate. For example, we might exchange a
* BrowserID assertion for a HAWK id and key pair.
*/
public class TokenServerClient {
protected static final String LOG_TAG = "TokenServerClient";
public static final String JSON_KEY_API_ENDPOINT = "api_endpoint";
public static final String JSON_KEY_CONDITION_URLS = "condition_urls";
public static final String JSON_KEY_DURATION = "duration";
public static final String JSON_KEY_ERRORS = "errors";
public static final String JSON_KEY_ID = "id";
public static final String JSON_KEY_KEY = "key";
public static final String JSON_KEY_UID = "uid";
public static final String HEADER_CONDITIONS_ACCEPTED = "X-Conditions-Accepted";
public static final String HEADER_CLIENT_STATE = "X-Client-State";
protected final Executor executor;
protected final URI uri;
public TokenServerClient(URI uri, Executor executor) {
if (uri == null) {
throw new IllegalArgumentException("uri must not be null");
}
if (executor == null) {
throw new IllegalArgumentException("executor must not be null");
}
this.uri = uri;
this.executor = executor;
}
protected void invokeHandleSuccess(final TokenServerClientDelegate delegate, final TokenServerToken token) {
executor.execute(new Runnable() {
@Override
public void run() {
delegate.handleSuccess(token);
}
});
}
protected void invokeHandleFailure(final TokenServerClientDelegate delegate, final TokenServerException e) {
executor.execute(new Runnable() {
@Override
public void run() {
delegate.handleFailure(e);
}
});
}
protected void invokeHandleError(final TokenServerClientDelegate delegate, final Exception e) {
executor.execute(new Runnable() {
@Override
public void run() {
delegate.handleError(e);
}
});
}
public TokenServerToken processResponse(HttpResponse response)
throws TokenServerException {
SyncResponse res = new SyncResponse(response);
int statusCode = res.getStatusCode();
Logger.debug(LOG_TAG, "Got token response with status code " + statusCode + ".");
// Responses should *always* be JSON, even in the case of 4xx and 5xx
// errors. If we don't see JSON, the server is likely very unhappy.
String contentType = response.getEntity().getContentType().getValue();
- if (contentType != "application/json" && !contentType.startsWith("application/json;")) {
+ if (!contentType.equals("application/json") && !contentType.startsWith("application/json;")) {
Logger.warn(LOG_TAG, "Got non-JSON response with Content-Type " +
contentType + ". Misconfigured server?");
throw new TokenServerMalformedResponseException(null, "Non-JSON response Content-Type.");
}
// Responses should *always* be a valid JSON object.
ExtendedJSONObject result;
try {
result = res.jsonObjectBody();
} catch (Exception e) {
Logger.debug(LOG_TAG, "Malformed token response.", e);
throw new TokenServerMalformedResponseException(null, e);
}
// The service shouldn't have any 3xx, so we don't need to handle those.
if (res.getStatusCode() != 200) {
// We should have a (Cornice) error report in the JSON. We log that to
// help with debugging.
List<ExtendedJSONObject> errorList = new ArrayList<ExtendedJSONObject>();
if (result.containsKey(JSON_KEY_ERRORS)) {
try {
for (Object error : result.getArray(JSON_KEY_ERRORS)) {
Logger.warn(LOG_TAG, "" + error);
if (error instanceof JSONObject) {
errorList.add(new ExtendedJSONObject((JSONObject) error));
}
}
} catch (NonArrayJSONException e) {
Logger.warn(LOG_TAG, "Got non-JSON array '" + result.getString(JSON_KEY_ERRORS) + "'.", e);
}
}
if (statusCode == 400) {
throw new TokenServerMalformedRequestException(errorList, result.toJSONString());
}
if (statusCode == 401) {
throw new TokenServerInvalidCredentialsException(errorList, result.toJSONString());
}
// 403 should represent a "condition acceptance needed" response.
//
// The extra validation of "urls" is important. We don't want to signal
// conditions required unless we are absolutely sure that is what the
// server is asking for.
if (statusCode == 403) {
// Bug 792674 and Bug 783598: make this testing simpler. For now, we
// check that errors is an array, and take any condition_urls from the
// first element.
try {
if (errorList == null || errorList.isEmpty()) {
throw new TokenServerMalformedResponseException(errorList, "403 response without proper fields.");
}
ExtendedJSONObject error = errorList.get(0);
ExtendedJSONObject condition_urls = error.getObject(JSON_KEY_CONDITION_URLS);
if (condition_urls != null) {
throw new TokenServerConditionsRequiredException(condition_urls);
}
} catch (NonObjectJSONException e) {
Logger.warn(LOG_TAG, "Got non-JSON error object.");
}
throw new TokenServerMalformedResponseException(errorList, "403 response without proper fields.");
}
if (statusCode == 404) {
throw new TokenServerUnknownServiceException(errorList);
}
// We shouldn't ever get here...
throw new TokenServerException(errorList);
}
try {
result.throwIfFieldsMissingOrMisTyped(new String[] { JSON_KEY_ID, JSON_KEY_KEY, JSON_KEY_API_ENDPOINT }, String.class);
result.throwIfFieldsMissingOrMisTyped(new String[] { JSON_KEY_UID }, Long.class);
} catch (BadRequiredFieldJSONException e ) {
throw new TokenServerMalformedResponseException(null, e);
}
Logger.debug(LOG_TAG, "Successful token response: " + result.getString(JSON_KEY_ID));
return new TokenServerToken(result.getString(JSON_KEY_ID),
result.getString(JSON_KEY_KEY),
result.get(JSON_KEY_UID).toString(),
result.getString(JSON_KEY_API_ENDPOINT));
}
public static class TokenFetchResourceDelegate extends BaseResourceDelegate {
private final TokenServerClient client;
private final TokenServerClientDelegate delegate;
private final String assertion;
private final String clientState;
private final BaseResource resource;
private final boolean conditionsAccepted;
public TokenFetchResourceDelegate(TokenServerClient client,
BaseResource resource,
TokenServerClientDelegate delegate,
String assertion, String clientState,
boolean conditionsAccepted) {
super(resource);
this.client = client;
this.delegate = delegate;
this.assertion = assertion;
this.clientState = clientState;
this.resource = resource;
this.conditionsAccepted = conditionsAccepted;
}
@Override
public void handleHttpResponse(HttpResponse response) {
SkewHandler skewHandler = SkewHandler.getSkewHandlerForResource(resource);
skewHandler.updateSkew(response, System.currentTimeMillis());
try {
TokenServerToken token = client.processResponse(response);
client.invokeHandleSuccess(delegate, token);
} catch (TokenServerException e) {
client.invokeHandleFailure(delegate, e);
}
}
@Override
public void handleTransportException(GeneralSecurityException e) {
client.invokeHandleError(delegate, e);
}
@Override
public void handleHttpProtocolException(ClientProtocolException e) {
client.invokeHandleError(delegate, e);
}
@Override
public void handleHttpIOException(IOException e) {
client.invokeHandleError(delegate, e);
}
@Override
public AuthHeaderProvider getAuthHeaderProvider() {
return new BrowserIDAuthHeaderProvider(assertion);
}
@Override
public void addHeaders(HttpRequestBase request, DefaultHttpClient client) {
String host = request.getURI().getHost();
request.setHeader(new BasicHeader(HttpHeaders.HOST, host));
if (clientState != null) {
request.setHeader(new BasicHeader(HEADER_CLIENT_STATE, clientState));
}
if (conditionsAccepted) {
request.addHeader(HEADER_CONDITIONS_ACCEPTED, "1");
}
}
}
public void getTokenFromBrowserIDAssertion(final String assertion,
final boolean conditionsAccepted,
final String clientState,
final TokenServerClientDelegate delegate) {
final BaseResource resource = new BaseResource(this.uri);
resource.delegate = new TokenFetchResourceDelegate(this, resource, delegate,
assertion, clientState,
conditionsAccepted);
resource.get();
}
}
| true | true | public TokenServerToken processResponse(HttpResponse response)
throws TokenServerException {
SyncResponse res = new SyncResponse(response);
int statusCode = res.getStatusCode();
Logger.debug(LOG_TAG, "Got token response with status code " + statusCode + ".");
// Responses should *always* be JSON, even in the case of 4xx and 5xx
// errors. If we don't see JSON, the server is likely very unhappy.
String contentType = response.getEntity().getContentType().getValue();
if (contentType != "application/json" && !contentType.startsWith("application/json;")) {
Logger.warn(LOG_TAG, "Got non-JSON response with Content-Type " +
contentType + ". Misconfigured server?");
throw new TokenServerMalformedResponseException(null, "Non-JSON response Content-Type.");
}
// Responses should *always* be a valid JSON object.
ExtendedJSONObject result;
try {
result = res.jsonObjectBody();
} catch (Exception e) {
Logger.debug(LOG_TAG, "Malformed token response.", e);
throw new TokenServerMalformedResponseException(null, e);
}
// The service shouldn't have any 3xx, so we don't need to handle those.
if (res.getStatusCode() != 200) {
// We should have a (Cornice) error report in the JSON. We log that to
// help with debugging.
List<ExtendedJSONObject> errorList = new ArrayList<ExtendedJSONObject>();
if (result.containsKey(JSON_KEY_ERRORS)) {
try {
for (Object error : result.getArray(JSON_KEY_ERRORS)) {
Logger.warn(LOG_TAG, "" + error);
if (error instanceof JSONObject) {
errorList.add(new ExtendedJSONObject((JSONObject) error));
}
}
} catch (NonArrayJSONException e) {
Logger.warn(LOG_TAG, "Got non-JSON array '" + result.getString(JSON_KEY_ERRORS) + "'.", e);
}
}
if (statusCode == 400) {
throw new TokenServerMalformedRequestException(errorList, result.toJSONString());
}
if (statusCode == 401) {
throw new TokenServerInvalidCredentialsException(errorList, result.toJSONString());
}
// 403 should represent a "condition acceptance needed" response.
//
// The extra validation of "urls" is important. We don't want to signal
// conditions required unless we are absolutely sure that is what the
// server is asking for.
if (statusCode == 403) {
// Bug 792674 and Bug 783598: make this testing simpler. For now, we
// check that errors is an array, and take any condition_urls from the
// first element.
try {
if (errorList == null || errorList.isEmpty()) {
throw new TokenServerMalformedResponseException(errorList, "403 response without proper fields.");
}
ExtendedJSONObject error = errorList.get(0);
ExtendedJSONObject condition_urls = error.getObject(JSON_KEY_CONDITION_URLS);
if (condition_urls != null) {
throw new TokenServerConditionsRequiredException(condition_urls);
}
} catch (NonObjectJSONException e) {
Logger.warn(LOG_TAG, "Got non-JSON error object.");
}
throw new TokenServerMalformedResponseException(errorList, "403 response without proper fields.");
}
if (statusCode == 404) {
throw new TokenServerUnknownServiceException(errorList);
}
// We shouldn't ever get here...
throw new TokenServerException(errorList);
}
try {
result.throwIfFieldsMissingOrMisTyped(new String[] { JSON_KEY_ID, JSON_KEY_KEY, JSON_KEY_API_ENDPOINT }, String.class);
result.throwIfFieldsMissingOrMisTyped(new String[] { JSON_KEY_UID }, Long.class);
} catch (BadRequiredFieldJSONException e ) {
throw new TokenServerMalformedResponseException(null, e);
}
Logger.debug(LOG_TAG, "Successful token response: " + result.getString(JSON_KEY_ID));
return new TokenServerToken(result.getString(JSON_KEY_ID),
result.getString(JSON_KEY_KEY),
result.get(JSON_KEY_UID).toString(),
result.getString(JSON_KEY_API_ENDPOINT));
}
| public TokenServerToken processResponse(HttpResponse response)
throws TokenServerException {
SyncResponse res = new SyncResponse(response);
int statusCode = res.getStatusCode();
Logger.debug(LOG_TAG, "Got token response with status code " + statusCode + ".");
// Responses should *always* be JSON, even in the case of 4xx and 5xx
// errors. If we don't see JSON, the server is likely very unhappy.
String contentType = response.getEntity().getContentType().getValue();
if (!contentType.equals("application/json") && !contentType.startsWith("application/json;")) {
Logger.warn(LOG_TAG, "Got non-JSON response with Content-Type " +
contentType + ". Misconfigured server?");
throw new TokenServerMalformedResponseException(null, "Non-JSON response Content-Type.");
}
// Responses should *always* be a valid JSON object.
ExtendedJSONObject result;
try {
result = res.jsonObjectBody();
} catch (Exception e) {
Logger.debug(LOG_TAG, "Malformed token response.", e);
throw new TokenServerMalformedResponseException(null, e);
}
// The service shouldn't have any 3xx, so we don't need to handle those.
if (res.getStatusCode() != 200) {
// We should have a (Cornice) error report in the JSON. We log that to
// help with debugging.
List<ExtendedJSONObject> errorList = new ArrayList<ExtendedJSONObject>();
if (result.containsKey(JSON_KEY_ERRORS)) {
try {
for (Object error : result.getArray(JSON_KEY_ERRORS)) {
Logger.warn(LOG_TAG, "" + error);
if (error instanceof JSONObject) {
errorList.add(new ExtendedJSONObject((JSONObject) error));
}
}
} catch (NonArrayJSONException e) {
Logger.warn(LOG_TAG, "Got non-JSON array '" + result.getString(JSON_KEY_ERRORS) + "'.", e);
}
}
if (statusCode == 400) {
throw new TokenServerMalformedRequestException(errorList, result.toJSONString());
}
if (statusCode == 401) {
throw new TokenServerInvalidCredentialsException(errorList, result.toJSONString());
}
// 403 should represent a "condition acceptance needed" response.
//
// The extra validation of "urls" is important. We don't want to signal
// conditions required unless we are absolutely sure that is what the
// server is asking for.
if (statusCode == 403) {
// Bug 792674 and Bug 783598: make this testing simpler. For now, we
// check that errors is an array, and take any condition_urls from the
// first element.
try {
if (errorList == null || errorList.isEmpty()) {
throw new TokenServerMalformedResponseException(errorList, "403 response without proper fields.");
}
ExtendedJSONObject error = errorList.get(0);
ExtendedJSONObject condition_urls = error.getObject(JSON_KEY_CONDITION_URLS);
if (condition_urls != null) {
throw new TokenServerConditionsRequiredException(condition_urls);
}
} catch (NonObjectJSONException e) {
Logger.warn(LOG_TAG, "Got non-JSON error object.");
}
throw new TokenServerMalformedResponseException(errorList, "403 response without proper fields.");
}
if (statusCode == 404) {
throw new TokenServerUnknownServiceException(errorList);
}
// We shouldn't ever get here...
throw new TokenServerException(errorList);
}
try {
result.throwIfFieldsMissingOrMisTyped(new String[] { JSON_KEY_ID, JSON_KEY_KEY, JSON_KEY_API_ENDPOINT }, String.class);
result.throwIfFieldsMissingOrMisTyped(new String[] { JSON_KEY_UID }, Long.class);
} catch (BadRequiredFieldJSONException e ) {
throw new TokenServerMalformedResponseException(null, e);
}
Logger.debug(LOG_TAG, "Successful token response: " + result.getString(JSON_KEY_ID));
return new TokenServerToken(result.getString(JSON_KEY_ID),
result.getString(JSON_KEY_KEY),
result.get(JSON_KEY_UID).toString(),
result.getString(JSON_KEY_API_ENDPOINT));
}
|
diff --git a/src/gwt/src/org/rstudio/studio/client/workbench/views/source/model/SourcePosition.java b/src/gwt/src/org/rstudio/studio/client/workbench/views/source/model/SourcePosition.java
index 44ac90fdfe..9d01d4869c 100644
--- a/src/gwt/src/org/rstudio/studio/client/workbench/views/source/model/SourcePosition.java
+++ b/src/gwt/src/org/rstudio/studio/client/workbench/views/source/model/SourcePosition.java
@@ -1,70 +1,70 @@
/*
* SourcePosition.java
*
* Copyright (C) 2009-11 by RStudio, Inc.
*
* This program is licensed to you under the terms of version 3 of the
* GNU Affero General Public License. This program is distributed WITHOUT
* ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT,
* MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the
* AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details.
*
*/
package org.rstudio.studio.client.workbench.views.source.model;
import com.google.gwt.core.client.JavaScriptObject;
public class SourcePosition extends JavaScriptObject
{
protected SourcePosition() {}
public static native SourcePosition create(int row,
int column) /*-{
return {context: null, row: row, column: column, scroll_position: -1};
}-*/;
public static native SourcePosition create(String context,
int row,
int column,
int scrollPosition) /*-{
return {context: context, row: row, column: column, scroll_position: scrollPosition};
}-*/;
/*
* NOTE: optional context for editors that have multiple internal
* contexts with independent rows & columns (e.g. code browser)
* this will be null for some implementations including TextEditingTarget
*/
public native final String getContext() /*-{
return this.context;
}-*/;
public native final int getRow() /*-{
return this.row;
}-*/;
public native final int getColumn() /*-{
return this.column;
}-*/;
/*
* NOTE: optional scroll position -- can be -1 to indicate no
* scroll position recorded
*/
public native final int getScrollPosition() /*-{
return this.scroll_position;
}-*/;
public final boolean isSameRowAs(SourcePosition other)
{
if (getContext() == null && other.getContext() == null)
- return true;
+ return other.getRow() == getRow();
else if (getContext() == null && other.getContext() != null)
return false;
else if (other.getContext() == null && getContext() != null)
return false;
else
return other.getContext().equals(getContext()) &&
(other.getRow() == getRow());
}
}
| true | true | public final boolean isSameRowAs(SourcePosition other)
{
if (getContext() == null && other.getContext() == null)
return true;
else if (getContext() == null && other.getContext() != null)
return false;
else if (other.getContext() == null && getContext() != null)
return false;
else
return other.getContext().equals(getContext()) &&
(other.getRow() == getRow());
}
| public final boolean isSameRowAs(SourcePosition other)
{
if (getContext() == null && other.getContext() == null)
return other.getRow() == getRow();
else if (getContext() == null && other.getContext() != null)
return false;
else if (other.getContext() == null && getContext() != null)
return false;
else
return other.getContext().equals(getContext()) &&
(other.getRow() == getRow());
}
|
diff --git a/izpack-src/trunk/src/lib/com/izforge/izpack/installer/GUIInstaller.java b/izpack-src/trunk/src/lib/com/izforge/izpack/installer/GUIInstaller.java
index 41cff72c..6765f568 100644
--- a/izpack-src/trunk/src/lib/com/izforge/izpack/installer/GUIInstaller.java
+++ b/izpack-src/trunk/src/lib/com/izforge/izpack/installer/GUIInstaller.java
@@ -1,823 +1,823 @@
/*
* $Id$
* IzPack - Copyright 2001-2007 Julien Ponge, All Rights Reserved.
*
* http://www.izforge.com/izpack/
* http://developer.berlios.de/projects/izpack/
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.izforge.izpack.installer;
import java.awt.Color;
import java.awt.Component;
import java.awt.Dimension;
import java.awt.Font;
import java.awt.GraphicsEnvironment;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.Insets;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.InputStream;
import java.io.ObjectInputStream;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Locale;
import java.util.Map;
import java.util.TreeMap;
import javax.swing.GrayFilter;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.ListCellRenderer;
import javax.swing.LookAndFeel;
import javax.swing.SwingConstants;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.plaf.metal.MetalLookAndFeel;
import javax.swing.plaf.metal.MetalTheme;
import com.izforge.izpack.GUIPrefs;
import com.izforge.izpack.LocaleDatabase;
import com.izforge.izpack.gui.ButtonFactory;
import com.izforge.izpack.gui.IzPackMetalTheme;
import com.izforge.izpack.gui.LabelFactory;
import com.izforge.izpack.util.Debug;
import com.izforge.izpack.util.OsVersion;
import com.izforge.izpack.util.VariableSubstitutor;
/**
* The IzPack graphical installer class.
*
* @author Julien Ponge
*/
public class GUIInstaller extends InstallerBase
{
/** The installation data. */
private InstallData installdata;
/** The L&F. */
protected String lnf;
/** defined modifier for language display type. */
private static final String[] LANGUAGE_DISPLAY_TYPES = { "iso3", "native", "default"};
private static final String[][] LANG_CODES = { { "cat", "ca"}, { "chn", "zh"}, { "cze", "cs"},
{ "dan", "da"}, { "deu", "de"}, { "eng", "en"}, { "fin", "fi"}, { "fra", "fr"},
{ "hun", "hu"}, { "ita", "it"}, { "jpn", "ja"}, { "mys", "ms"}, { "ned", "nl"},
{ "nor", "no"}, { "pol", "pl"}, { "por", "pt"}, { "rom", "or"}, { "rus", "ru"},
{ "spa", "es"}, { "svk", "sk"}, { "swe", "sv"}, { "tur", "tr"}, { "ukr", "uk"}};
/** holds language to ISO-3 language code translation */
private static HashMap isoTable;
/**
* The constructor.
*
* @exception Exception Description of the Exception
*/
public GUIInstaller() throws Exception
{
this.installdata = new InstallData();
// Loads the installation data
loadInstallData(installdata);
// add the GUI install data
loadGUIInstallData();
// Sets up the GUI L&F
loadLookAndFeel();
// Checks the Java version
checkJavaVersion();
// Loads the suitable langpack
SwingUtilities.invokeAndWait(new Runnable() {
public void run()
{
try
{
loadLangPack();
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
// create the resource manager (after the language selection!)
ResourceManager.create(this.installdata);
// Load custom langpack if exist.
addCustomLangpack(installdata);
// We launch the installer GUI
SwingUtilities.invokeLater(new Runnable() {
public void run()
{
try
{
loadGUI();
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
}
/**
* Load GUI preference information.
*
* @throws Exception
*/
public void loadGUIInstallData() throws Exception
{
InputStream in = GUIInstaller.class.getResourceAsStream("/GUIPrefs");
ObjectInputStream objIn = new ObjectInputStream(in);
this.installdata.guiPrefs = (GUIPrefs) objIn.readObject();
objIn.close();
}
/**
* Checks the Java version.
*
* @exception Exception Description of the Exception
*/
private void checkJavaVersion() throws Exception
{
String version = System.getProperty("java.version");
String required = this.installdata.info.getJavaVersion();
if (version.compareTo(required) < 0)
{
StringBuffer msg = new StringBuffer();
msg.append("The application that you are trying to install requires a ");
msg.append(required);
msg.append(" version or later of the Java platform.\n");
msg.append("You are running a ");
msg.append(version);
msg.append(" version of the Java platform.\n");
msg.append("Please upgrade to a newer version.");
System.out.println(msg.toString());
JOptionPane.showMessageDialog(null, msg.toString(), "Error", JOptionPane.ERROR_MESSAGE);
System.exit(1);
}
}
/**
* Loads the suitable langpack.
*
* @exception Exception Description of the Exception
*/
private void loadLangPack() throws Exception
{
// Initialisations
List availableLangPacks = getAvailableLangPacks();
int npacks = availableLangPacks.size();
if (npacks == 0) throw new Exception("no language pack available");
String selectedPack;
// Dummy Frame
JFrame frame = new JFrame();
frame.setIconImage(new ImageIcon(this.getClass().getResource("/img/JFrameIcon.png"))
.getImage());
Dimension frameSize = frame.getSize();
Dimension screenSize = Toolkit.getDefaultToolkit().getScreenSize();
frame.setLocation((screenSize.width - frameSize.width) / 2,
(screenSize.height - frameSize.height) / 2 - 10);
// We get the langpack name
if (npacks != 1)
{
LanguageDialog picker = new LanguageDialog(frame, availableLangPacks.toArray());
picker.setSelection(Locale.getDefault().getISO3Language().toLowerCase());
picker.setModal(true);
picker.toFront();
// frame.setVisible(true);
frame.setVisible(false);
picker.setVisible(true);
selectedPack = (String) picker.getSelection();
if (selectedPack == null) throw new Exception("installation canceled");
}
else
selectedPack = (String) availableLangPacks.get(0);
// We add an xml data information
this.installdata.xmlData.setAttribute("langpack", selectedPack);
// We load the langpack
installdata.localeISO3 = selectedPack;
installdata.setVariable(ScriptParser.ISO3_LANG, installdata.localeISO3);
InputStream in = getClass().getResourceAsStream("/langpacks/" + selectedPack + ".xml");
this.installdata.langpack = new LocaleDatabase(in);
}
/**
* Returns an ArrayList of the available langpacks ISO3 codes.
*
* @return The available langpacks list.
* @exception Exception Description of the Exception
*/
private List getAvailableLangPacks() throws Exception
{
// We read from the langpacks file in the jar
InputStream in = getClass().getResourceAsStream("/langpacks.info");
ObjectInputStream objIn = new ObjectInputStream(in);
List available = (List) objIn.readObject();
objIn.close();
return available;
}
/**
* Loads the suitable L&F.
*
* @exception Exception Description of the Exception
*/
protected void loadLookAndFeel() throws Exception
{
// Do we have any preference for this OS ?
String syskey = "unix";
if (OsVersion.IS_WINDOWS)
{
syskey = "windows";
}
else if (OsVersion.IS_OSX)
{
syskey = "mac";
}
String laf = null;
if (installdata.guiPrefs.lookAndFeelMapping.containsKey(syskey))
{
laf = (String) installdata.guiPrefs.lookAndFeelMapping.get(syskey);
}
// Let's use the system LAF
// Resolve whether button icons should be used or not.
boolean useButtonIcons = true;
if (installdata.guiPrefs.modifier.containsKey("useButtonIcons")
&& "no".equalsIgnoreCase((String) installdata.guiPrefs.modifier
.get("useButtonIcons"))) useButtonIcons = false;
ButtonFactory.useButtonIcons(useButtonIcons);
boolean useLabelIcons = true;
if (installdata.guiPrefs.modifier.containsKey("useLabelIcons")
&& "no".equalsIgnoreCase((String) installdata.guiPrefs.modifier
.get("useLabelIcons"))) useLabelIcons = false;
LabelFactory.setUseLabelIcons(useLabelIcons);
if (laf == null)
{
if (!"mac".equals(syskey))
{
// In Linux we will use the English locale, because of a bug in
// JRE6. In Korean, Persian, Chinese, japanese and some other
// locales the installer throws and exception and doesn't load
// at all. See http://jira.jboss.com/jira/browse/JBINSTALL-232.
// This is a workaround until this bug gets fixed.
- Locale.setDefault(Locale.ENGLISH);
+ if("unix".equals(syskey)) Locale.setDefault(Locale.ENGLISH);
String syslaf = UIManager.getSystemLookAndFeelClassName();
UIManager.setLookAndFeel(syslaf);
if (UIManager.getLookAndFeel() instanceof MetalLookAndFeel)
{
MetalLookAndFeel.setCurrentTheme(new IzPackMetalTheme());
ButtonFactory.useHighlightButtons();
// Reset the use button icons state because
// useHighlightButtons
// make it always true.
ButtonFactory.useButtonIcons(useButtonIcons);
installdata.buttonsHColor = new Color(182, 182, 204);
}
}
lnf = "swing";
return;
}
// Kunststoff (http://www.incors.org/)
if ("kunststoff".equals(laf))
{
ButtonFactory.useHighlightButtons();
// Reset the use button icons state because useHighlightButtons
// make it always true.
ButtonFactory.useButtonIcons(useButtonIcons);
installdata.buttonsHColor = new Color(255, 255, 255);
Class lafClass = Class.forName("com.incors.plaf.kunststoff.KunststoffLookAndFeel");
Class mtheme = Class.forName("javax.swing.plaf.metal.MetalTheme");
Class[] params = { mtheme};
Class theme = Class.forName("com.izforge.izpack.gui.IzPackKMetalTheme");
Method setCurrentThemeMethod = lafClass.getMethod("setCurrentTheme", params);
// We invoke and place Kunststoff as our L&F
LookAndFeel kunststoff = (LookAndFeel) lafClass.newInstance();
MetalTheme ktheme = (MetalTheme) theme.newInstance();
Object[] kparams = { ktheme};
UIManager.setLookAndFeel(kunststoff);
setCurrentThemeMethod.invoke(kunststoff, kparams);
lnf = "kunststoff";
return;
}
// Liquid (http://liquidlnf.sourceforge.net/)
if ("liquid".equals(laf))
{
UIManager.setLookAndFeel("com.birosoft.liquid.LiquidLookAndFeel");
lnf = "liquid";
Map params = (Map) installdata.guiPrefs.lookAndFeelParams.get(laf);
if (params.containsKey("decorate.frames"))
{
String value = (String) params.get("decorate.frames");
if ("yes".equals(value))
{
JFrame.setDefaultLookAndFeelDecorated(true);
}
}
if (params.containsKey("decorate.dialogs"))
{
String value = (String) params.get("decorate.dialogs");
if ("yes".equals(value))
{
JDialog.setDefaultLookAndFeelDecorated(true);
}
}
return;
}
// Metouia (http://mlf.sourceforge.net/)
if ("metouia".equals(laf))
{
UIManager.setLookAndFeel("net.sourceforge.mlf.metouia.MetouiaLookAndFeel");
lnf = "metouia";
return;
}
// JGoodies Looks (http://looks.dev.java.net/)
if ("looks".equals(laf))
{
Map variants = new TreeMap();
variants.put("extwin", "com.jgoodies.plaf.windows.ExtWindowsLookAndFeel");
variants.put("plastic", "com.jgoodies.plaf.plastic.PlasticLookAndFeel");
variants.put("plastic3D", "com.jgoodies.plaf.plastic.Plastic3DLookAndFeel");
variants.put("plasticXP", "com.jgoodies.plaf.plastic.PlasticXPLookAndFeel");
String variant = (String) variants.get("plasticXP");
Map params = (Map) installdata.guiPrefs.lookAndFeelParams.get(laf);
if (params.containsKey("variant"))
{
String param = (String) params.get("variant");
if (variants.containsKey(param))
{
variant = (String) variants.get(param);
}
}
UIManager.setLookAndFeel(variant);
}
}
/**
* Loads the GUI.
*
* @exception Exception Description of the Exception
*/
private void loadGUI() throws Exception
{
UIManager.put("OptionPane.yesButtonText", installdata.langpack.getString("installer.yes"));
UIManager.put("OptionPane.noButtonText", installdata.langpack.getString("installer.no"));
UIManager.put("OptionPane.cancelButtonText", installdata.langpack
.getString("installer.cancel"));
String title;
// Use a alternate message if defined.
final String key = "installer.reversetitle";
String message = installdata.langpack.getString(key);
// message equal to key -> no message defined.
if (message.indexOf(key) > -1)
title = installdata.langpack.getString("installer.title")
+ installdata.info.getAppName();
else
{ // Attention! The alternate message has to contain the hole message including
// $APP_NAME and may be $APP_VER.
VariableSubstitutor vs = new VariableSubstitutor(installdata.getVariables());
title = vs.substitute(message, null);
}
new InstallerFrame(title, this.installdata);
}
/**
* Returns whether flags should be used in the language selection dialog or not.
*
* @return whether flags should be used in the language selection dialog or not
*/
protected boolean useFlags()
{
if (installdata.guiPrefs.modifier.containsKey("useFlags")
&& "no".equalsIgnoreCase((String) installdata.guiPrefs.modifier.get("useFlags")))
return (false);
return (true);
}
/**
* Returns the type in which the language should be displayed in the language selction dialog.
* Possible are "iso3", "native" and "usingDefault".
*
* @return language display type
*/
protected String getLangType()
{
if (installdata.guiPrefs.modifier.containsKey("langDisplayType"))
{
String val = (String) installdata.guiPrefs.modifier.get("langDisplayType");
val = val.toLowerCase();
// Verify that the value is valid, else return the default.
for (int i = 0; i < LANGUAGE_DISPLAY_TYPES.length; ++i)
if (val.equalsIgnoreCase(LANGUAGE_DISPLAY_TYPES[i])) return (val);
Debug.trace("Value for language display type not valid; value: " + val);
}
return (LANGUAGE_DISPLAY_TYPES[0]);
}
/**
* Used to prompt the user for the language. Languages can be displayed in iso3 or the native
* notation or the notation of the default locale. Revising to native notation is based on code
* from Christian Murphy (patch #395).
*
* @author Julien Ponge
* @author Christian Murphy
* @author Klaus Bartz
*/
private final class LanguageDialog extends JDialog implements ActionListener
{
private static final long serialVersionUID = 3256443616359887667L;
/** The combo box. */
private JComboBox comboBox;
/** The ISO3 to ISO2 HashMap */
private HashMap iso3Toiso2 = null;
/** iso3Toiso2 expanded ? */
private boolean isoMapExpanded = false;
/**
* The constructor.
*
* @param items The items to display in the box.
*/
public LanguageDialog(JFrame frame, Object[] items)
{
super(frame);
try
{
loadLookAndFeel();
}
catch (Exception err)
{
err.printStackTrace();
}
// We build the GUI
addWindowListener(new WindowHandler());
JPanel contentPane = (JPanel) getContentPane();
setTitle("Language selection");
GridBagLayout layout = new GridBagLayout();
contentPane.setLayout(layout);
GridBagConstraints gbConstraints = new GridBagConstraints();
gbConstraints.anchor = GridBagConstraints.CENTER;
gbConstraints.insets = new Insets(5, 5, 5, 5);
gbConstraints.fill = GridBagConstraints.NONE;
gbConstraints.gridx = 0;
gbConstraints.weightx = 1.0;
gbConstraints.weighty = 1.0;
ImageIcon img = getImage();
JLabel imgLabel = new JLabel(img);
gbConstraints.gridy = 0;
contentPane.add(imgLabel);
gbConstraints.fill = GridBagConstraints.HORIZONTAL;
String firstMessage = "Please select your language";
if (getLangType().equals(LANGUAGE_DISPLAY_TYPES[0]))
// iso3
firstMessage = "Please select your language (ISO3 code)";
JLabel label1 = new JLabel(firstMessage, SwingConstants.CENTER);
gbConstraints.gridy = 1;
gbConstraints.insets = new Insets(5, 5, 0, 5);
layout.addLayoutComponent(label1, gbConstraints);
contentPane.add(label1);
JLabel label2 = new JLabel("for install instructions:", SwingConstants.CENTER);
gbConstraints.gridy = 2;
gbConstraints.insets = new Insets(0, 5, 5, 5);
layout.addLayoutComponent(label2, gbConstraints);
contentPane.add(label2);
gbConstraints.insets = new Insets(5, 5, 5, 5);
items = reviseItems(items);
comboBox = new JComboBox(items);
if (useFlags()) comboBox.setRenderer(new FlagRenderer());
gbConstraints.fill = GridBagConstraints.HORIZONTAL;
gbConstraints.gridy = 3;
layout.addLayoutComponent(comboBox, gbConstraints);
contentPane.add(comboBox);
JButton okButton = new JButton("OK");
okButton.addActionListener(this);
gbConstraints.fill = GridBagConstraints.NONE;
gbConstraints.gridy = 4;
gbConstraints.anchor = GridBagConstraints.CENTER;
layout.addLayoutComponent(okButton, gbConstraints);
contentPane.add(okButton);
getRootPane().setDefaultButton(okButton);
// Packs and centers
// Fix for bug "Installer won't show anything on OSX"
if (System.getProperty("mrj.version") == null)
pack();
else
setSize(getPreferredSize());
Dimension frameSize = getSize();
Point center = GraphicsEnvironment.getLocalGraphicsEnvironment().getCenterPoint();
setLocation(center.x - frameSize.width / 2, center.y - frameSize.height / 2 - 10);
setResizable(true);
}
/**
* Revises iso3 language items depending on the language display type.
*
* @param items item array to be revised
* @return the revised array
*/
private Object[] reviseItems(Object[] items)
{
String langType = getLangType();
// iso3: nothing todo.
if (langType.equals(LANGUAGE_DISPLAY_TYPES[0])) return (items);
// native: get the names as they are written in that language.
if (langType.equals(LANGUAGE_DISPLAY_TYPES[1]))
return (expandItems(items, (new JComboBox()).getFont()));
// default: get the names as they are written in the default
// language.
if (langType.equals(LANGUAGE_DISPLAY_TYPES[2])) return (expandItems(items, null));
// Should never be.
return (items);
}
/**
* Expands the given iso3 codes to language names. If a testFont is given, the codes are
* tested whether they can displayed or not. If not, or no font given, the language name
* will be returned as written in the default language of this VM.
*
* @param items item array to be expanded to the language name
* @param testFont font to test wheter a name is displayable
* @return aray of expanded items
*/
private Object[] expandItems(Object[] items, Font testFont)
{
int i;
if (iso3Toiso2 == null)
{ // Loasd predefined langs into HashMap.
iso3Toiso2 = new HashMap(32);
isoTable = new HashMap();
for (i = 0; i < LANG_CODES.length; ++i)
iso3Toiso2.put(LANG_CODES[i][0], LANG_CODES[i][1]);
}
for (i = 0; i < items.length; i++)
{
Object it = expandItem(items[i], testFont);
isoTable.put(it, items[i]);
items[i] = it;
}
return items;
}
/**
* Expands the given iso3 code to a language name. If a testFont is given, the code will be
* tested whether it is displayable or not. If not, or no font given, the language name will
* be returned as written in the default language of this VM.
*
* @param item item to be expanded to the language name
* @param testFont font to test wheter the name is displayable
* @return expanded item
*/
private Object expandItem(Object item, Font testFont)
{
Object iso2Str = iso3Toiso2.get(item);
int i;
if (iso2Str == null && !isoMapExpanded)
{ // Expand iso3toiso2 only if needed because it needs some time.
isoMapExpanded = true;
Locale[] loc = Locale.getAvailableLocales();
for (i = 0; i < loc.length; ++i)
iso3Toiso2.put(loc[i].getISO3Language(), loc[i].getLanguage());
iso2Str = iso3Toiso2.get(item);
}
if (iso2Str == null)
// Unknown item, return it self.
return (item);
Locale locale = new Locale((String) iso2Str);
if (testFont == null)
// Return the language name in the spelling of the default locale.
return (locale.getDisplayLanguage());
// Get the language name in the spelling of that language.
String str = locale.getDisplayLanguage(locale);
int cdut = testFont.canDisplayUpTo(str);
if (cdut > -1)
// Test font cannot render it;
// use language name in the spelling of the default locale.
str = locale.getDisplayLanguage();
return (str);
}
/**
* Loads an image.
*
* @return The image icon.
*/
public ImageIcon getImage()
{
ImageIcon img;
try
{
img = new ImageIcon(LanguageDialog.class.getResource("/res/installer.langsel.img"));
}
catch (NullPointerException err)
{
img = null;
}
return img;
}
/**
* Gets the selected object.
*
* @return The selected item.
*/
public Object getSelection()
{
Object retval = null;
if (isoTable != null) retval = isoTable.get(comboBox.getSelectedItem());
return (retval != null) ? retval : comboBox.getSelectedItem();
}
/**
* Sets the selection.
*
* @param item The item to be selected.
*/
public void setSelection(Object item)
{
Object mapped = null;
if (isoTable != null)
{
Iterator iter = isoTable.keySet().iterator();
while (iter.hasNext())
{
Object key = iter.next();
if (isoTable.get(key).equals(item))
{
mapped = key;
break;
}
}
}
if (mapped == null) mapped = item;
comboBox.setSelectedItem(mapped);
}
/**
* Closer.
*
* @param e The event.
*/
public void actionPerformed(ActionEvent e)
{
dispose();
}
/**
* The window events handler.
*
* @author Julien Ponge
*/
private class WindowHandler extends WindowAdapter
{
/**
* We can't avoid the exit here, so don't call exit anywhere else.
*
* @param e the event.
*/
public void windowClosing(WindowEvent e)
{
System.exit(0);
}
}
}
/**
* A list cell renderer that adds the flags on the display.
*
* @author Julien Ponge
*/
private static class FlagRenderer extends JLabel implements ListCellRenderer
{
private static final long serialVersionUID = 3832899961942782769L;
/** Icons cache. */
private TreeMap icons = new TreeMap();
/** Grayed icons cache. */
private TreeMap grayIcons = new TreeMap();
public FlagRenderer()
{
setOpaque(true);
}
/**
* Returns a suitable cell.
*
* @param list The list.
* @param value The object.
* @param index The index.
* @param isSelected true if it is selected.
* @param cellHasFocus Description of the Parameter
* @return The cell.
*/
public Component getListCellRendererComponent(JList list, Object value, int index,
boolean isSelected, boolean cellHasFocus)
{
// We put the label
String iso3 = (String) value;
setText(iso3);
if (isoTable != null) iso3 = (String) isoTable.get(iso3);
if (isSelected)
{
setForeground(list.getSelectionForeground());
setBackground(list.getSelectionBackground());
}
else
{
setForeground(list.getForeground());
setBackground(list.getBackground());
}
// We put the icon
if (!icons.containsKey(iso3))
{
ImageIcon icon;
icon = new ImageIcon(this.getClass().getResource("/res/flag." + iso3));
icons.put(iso3, icon);
icon = new ImageIcon(GrayFilter.createDisabledImage(icon.getImage()));
grayIcons.put(iso3, icon);
}
if (isSelected || index == -1)
setIcon((ImageIcon) icons.get(iso3));
else
setIcon((ImageIcon) grayIcons.get(iso3));
// We return
return this;
}
}
}
| true | true | protected void loadLookAndFeel() throws Exception
{
// Do we have any preference for this OS ?
String syskey = "unix";
if (OsVersion.IS_WINDOWS)
{
syskey = "windows";
}
else if (OsVersion.IS_OSX)
{
syskey = "mac";
}
String laf = null;
if (installdata.guiPrefs.lookAndFeelMapping.containsKey(syskey))
{
laf = (String) installdata.guiPrefs.lookAndFeelMapping.get(syskey);
}
// Let's use the system LAF
// Resolve whether button icons should be used or not.
boolean useButtonIcons = true;
if (installdata.guiPrefs.modifier.containsKey("useButtonIcons")
&& "no".equalsIgnoreCase((String) installdata.guiPrefs.modifier
.get("useButtonIcons"))) useButtonIcons = false;
ButtonFactory.useButtonIcons(useButtonIcons);
boolean useLabelIcons = true;
if (installdata.guiPrefs.modifier.containsKey("useLabelIcons")
&& "no".equalsIgnoreCase((String) installdata.guiPrefs.modifier
.get("useLabelIcons"))) useLabelIcons = false;
LabelFactory.setUseLabelIcons(useLabelIcons);
if (laf == null)
{
if (!"mac".equals(syskey))
{
// In Linux we will use the English locale, because of a bug in
// JRE6. In Korean, Persian, Chinese, japanese and some other
// locales the installer throws and exception and doesn't load
// at all. See http://jira.jboss.com/jira/browse/JBINSTALL-232.
// This is a workaround until this bug gets fixed.
Locale.setDefault(Locale.ENGLISH);
String syslaf = UIManager.getSystemLookAndFeelClassName();
UIManager.setLookAndFeel(syslaf);
if (UIManager.getLookAndFeel() instanceof MetalLookAndFeel)
{
MetalLookAndFeel.setCurrentTheme(new IzPackMetalTheme());
ButtonFactory.useHighlightButtons();
// Reset the use button icons state because
// useHighlightButtons
// make it always true.
ButtonFactory.useButtonIcons(useButtonIcons);
installdata.buttonsHColor = new Color(182, 182, 204);
}
}
lnf = "swing";
return;
}
// Kunststoff (http://www.incors.org/)
if ("kunststoff".equals(laf))
{
ButtonFactory.useHighlightButtons();
// Reset the use button icons state because useHighlightButtons
// make it always true.
ButtonFactory.useButtonIcons(useButtonIcons);
installdata.buttonsHColor = new Color(255, 255, 255);
Class lafClass = Class.forName("com.incors.plaf.kunststoff.KunststoffLookAndFeel");
Class mtheme = Class.forName("javax.swing.plaf.metal.MetalTheme");
Class[] params = { mtheme};
Class theme = Class.forName("com.izforge.izpack.gui.IzPackKMetalTheme");
Method setCurrentThemeMethod = lafClass.getMethod("setCurrentTheme", params);
// We invoke and place Kunststoff as our L&F
LookAndFeel kunststoff = (LookAndFeel) lafClass.newInstance();
MetalTheme ktheme = (MetalTheme) theme.newInstance();
Object[] kparams = { ktheme};
UIManager.setLookAndFeel(kunststoff);
setCurrentThemeMethod.invoke(kunststoff, kparams);
lnf = "kunststoff";
return;
}
// Liquid (http://liquidlnf.sourceforge.net/)
if ("liquid".equals(laf))
{
UIManager.setLookAndFeel("com.birosoft.liquid.LiquidLookAndFeel");
lnf = "liquid";
Map params = (Map) installdata.guiPrefs.lookAndFeelParams.get(laf);
if (params.containsKey("decorate.frames"))
{
String value = (String) params.get("decorate.frames");
if ("yes".equals(value))
{
JFrame.setDefaultLookAndFeelDecorated(true);
}
}
if (params.containsKey("decorate.dialogs"))
{
String value = (String) params.get("decorate.dialogs");
if ("yes".equals(value))
{
JDialog.setDefaultLookAndFeelDecorated(true);
}
}
return;
}
// Metouia (http://mlf.sourceforge.net/)
if ("metouia".equals(laf))
{
UIManager.setLookAndFeel("net.sourceforge.mlf.metouia.MetouiaLookAndFeel");
lnf = "metouia";
return;
}
// JGoodies Looks (http://looks.dev.java.net/)
if ("looks".equals(laf))
{
Map variants = new TreeMap();
variants.put("extwin", "com.jgoodies.plaf.windows.ExtWindowsLookAndFeel");
variants.put("plastic", "com.jgoodies.plaf.plastic.PlasticLookAndFeel");
variants.put("plastic3D", "com.jgoodies.plaf.plastic.Plastic3DLookAndFeel");
variants.put("plasticXP", "com.jgoodies.plaf.plastic.PlasticXPLookAndFeel");
String variant = (String) variants.get("plasticXP");
Map params = (Map) installdata.guiPrefs.lookAndFeelParams.get(laf);
if (params.containsKey("variant"))
{
String param = (String) params.get("variant");
if (variants.containsKey(param))
{
variant = (String) variants.get(param);
}
}
UIManager.setLookAndFeel(variant);
}
}
| protected void loadLookAndFeel() throws Exception
{
// Do we have any preference for this OS ?
String syskey = "unix";
if (OsVersion.IS_WINDOWS)
{
syskey = "windows";
}
else if (OsVersion.IS_OSX)
{
syskey = "mac";
}
String laf = null;
if (installdata.guiPrefs.lookAndFeelMapping.containsKey(syskey))
{
laf = (String) installdata.guiPrefs.lookAndFeelMapping.get(syskey);
}
// Let's use the system LAF
// Resolve whether button icons should be used or not.
boolean useButtonIcons = true;
if (installdata.guiPrefs.modifier.containsKey("useButtonIcons")
&& "no".equalsIgnoreCase((String) installdata.guiPrefs.modifier
.get("useButtonIcons"))) useButtonIcons = false;
ButtonFactory.useButtonIcons(useButtonIcons);
boolean useLabelIcons = true;
if (installdata.guiPrefs.modifier.containsKey("useLabelIcons")
&& "no".equalsIgnoreCase((String) installdata.guiPrefs.modifier
.get("useLabelIcons"))) useLabelIcons = false;
LabelFactory.setUseLabelIcons(useLabelIcons);
if (laf == null)
{
if (!"mac".equals(syskey))
{
// In Linux we will use the English locale, because of a bug in
// JRE6. In Korean, Persian, Chinese, japanese and some other
// locales the installer throws and exception and doesn't load
// at all. See http://jira.jboss.com/jira/browse/JBINSTALL-232.
// This is a workaround until this bug gets fixed.
if("unix".equals(syskey)) Locale.setDefault(Locale.ENGLISH);
String syslaf = UIManager.getSystemLookAndFeelClassName();
UIManager.setLookAndFeel(syslaf);
if (UIManager.getLookAndFeel() instanceof MetalLookAndFeel)
{
MetalLookAndFeel.setCurrentTheme(new IzPackMetalTheme());
ButtonFactory.useHighlightButtons();
// Reset the use button icons state because
// useHighlightButtons
// make it always true.
ButtonFactory.useButtonIcons(useButtonIcons);
installdata.buttonsHColor = new Color(182, 182, 204);
}
}
lnf = "swing";
return;
}
// Kunststoff (http://www.incors.org/)
if ("kunststoff".equals(laf))
{
ButtonFactory.useHighlightButtons();
// Reset the use button icons state because useHighlightButtons
// make it always true.
ButtonFactory.useButtonIcons(useButtonIcons);
installdata.buttonsHColor = new Color(255, 255, 255);
Class lafClass = Class.forName("com.incors.plaf.kunststoff.KunststoffLookAndFeel");
Class mtheme = Class.forName("javax.swing.plaf.metal.MetalTheme");
Class[] params = { mtheme};
Class theme = Class.forName("com.izforge.izpack.gui.IzPackKMetalTheme");
Method setCurrentThemeMethod = lafClass.getMethod("setCurrentTheme", params);
// We invoke and place Kunststoff as our L&F
LookAndFeel kunststoff = (LookAndFeel) lafClass.newInstance();
MetalTheme ktheme = (MetalTheme) theme.newInstance();
Object[] kparams = { ktheme};
UIManager.setLookAndFeel(kunststoff);
setCurrentThemeMethod.invoke(kunststoff, kparams);
lnf = "kunststoff";
return;
}
// Liquid (http://liquidlnf.sourceforge.net/)
if ("liquid".equals(laf))
{
UIManager.setLookAndFeel("com.birosoft.liquid.LiquidLookAndFeel");
lnf = "liquid";
Map params = (Map) installdata.guiPrefs.lookAndFeelParams.get(laf);
if (params.containsKey("decorate.frames"))
{
String value = (String) params.get("decorate.frames");
if ("yes".equals(value))
{
JFrame.setDefaultLookAndFeelDecorated(true);
}
}
if (params.containsKey("decorate.dialogs"))
{
String value = (String) params.get("decorate.dialogs");
if ("yes".equals(value))
{
JDialog.setDefaultLookAndFeelDecorated(true);
}
}
return;
}
// Metouia (http://mlf.sourceforge.net/)
if ("metouia".equals(laf))
{
UIManager.setLookAndFeel("net.sourceforge.mlf.metouia.MetouiaLookAndFeel");
lnf = "metouia";
return;
}
// JGoodies Looks (http://looks.dev.java.net/)
if ("looks".equals(laf))
{
Map variants = new TreeMap();
variants.put("extwin", "com.jgoodies.plaf.windows.ExtWindowsLookAndFeel");
variants.put("plastic", "com.jgoodies.plaf.plastic.PlasticLookAndFeel");
variants.put("plastic3D", "com.jgoodies.plaf.plastic.Plastic3DLookAndFeel");
variants.put("plasticXP", "com.jgoodies.plaf.plastic.PlasticXPLookAndFeel");
String variant = (String) variants.get("plasticXP");
Map params = (Map) installdata.guiPrefs.lookAndFeelParams.get(laf);
if (params.containsKey("variant"))
{
String param = (String) params.get("variant");
if (variants.containsKey(param))
{
variant = (String) variants.get(param);
}
}
UIManager.setLookAndFeel(variant);
}
}
|
diff --git a/servicemix-jsr181/src/main/java/org/apache/servicemix/jsr181/EndpointDeliveryChannel.java b/servicemix-jsr181/src/main/java/org/apache/servicemix/jsr181/EndpointDeliveryChannel.java
index c00141369..c20afcdb4 100644
--- a/servicemix-jsr181/src/main/java/org/apache/servicemix/jsr181/EndpointDeliveryChannel.java
+++ b/servicemix-jsr181/src/main/java/org/apache/servicemix/jsr181/EndpointDeliveryChannel.java
@@ -1,95 +1,92 @@
/*
* Copyright 2005-2006 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.servicemix.jsr181;
import javax.jbi.messaging.DeliveryChannel;
import javax.jbi.messaging.ExchangeStatus;
import javax.jbi.messaging.InOptionalOut;
import javax.jbi.messaging.InOut;
import javax.jbi.messaging.MessageExchange;
import javax.jbi.messaging.MessageExchangeFactory;
import javax.jbi.messaging.MessagingException;
import javax.jbi.servicedesc.ServiceEndpoint;
import javax.xml.namespace.QName;
import org.apache.servicemix.common.BaseLifeCycle;
import org.apache.servicemix.common.Endpoint;
/**
* This class is a wrapper around an existing DeliveryChannel
* that will be given to service engine endpoints so that
* they are able to send messages and to interact with the
* JBI container.
*
* @author gnodet
*/
public class EndpointDeliveryChannel implements DeliveryChannel {
private DeliveryChannel channel;
private Endpoint endpoint;
public EndpointDeliveryChannel(DeliveryChannel channel, Endpoint endpoint) {
this.channel = channel;
this.endpoint = endpoint;
}
public MessageExchange accept() throws MessagingException {
throw new UnsupportedOperationException();
}
public MessageExchange accept(long timeout) throws MessagingException {
throw new UnsupportedOperationException();
}
public void close() throws MessagingException {
throw new UnsupportedOperationException();
}
public MessageExchangeFactory createExchangeFactory() {
return channel.createExchangeFactory();
}
public MessageExchangeFactory createExchangeFactory(QName interfaceName) {
return channel.createExchangeFactory(interfaceName);
}
public MessageExchangeFactory createExchangeFactory(ServiceEndpoint endpoint) {
return channel.createExchangeFactory(endpoint);
}
public MessageExchangeFactory createExchangeFactoryForService(QName serviceName) {
return channel.createExchangeFactoryForService(serviceName);
}
public void send(MessageExchange exchange) throws MessagingException {
- if (exchange instanceof InOut || exchange instanceof InOptionalOut) {
- // Done status can only be send asynchronously
- if (exchange.getStatus() != ExchangeStatus.DONE) {
- throw new UnsupportedOperationException("Asynchonous in-out are not supported");
- }
+ if (exchange.getStatus() == ExchangeStatus.ACTIVE) {
+ throw new UnsupportedOperationException("Asynchonous send of active exchanges are not supported");
}
BaseLifeCycle lf = (BaseLifeCycle) endpoint.getServiceUnit().getComponent().getLifeCycle();
lf.sendConsumerExchange(exchange, endpoint);
}
public boolean sendSync(MessageExchange exchange, long timeout) throws MessagingException {
return channel.sendSync(exchange, timeout);
}
public boolean sendSync(MessageExchange exchange) throws MessagingException {
return channel.sendSync(exchange);
}
}
| true | true | public void send(MessageExchange exchange) throws MessagingException {
if (exchange instanceof InOut || exchange instanceof InOptionalOut) {
// Done status can only be send asynchronously
if (exchange.getStatus() != ExchangeStatus.DONE) {
throw new UnsupportedOperationException("Asynchonous in-out are not supported");
}
}
BaseLifeCycle lf = (BaseLifeCycle) endpoint.getServiceUnit().getComponent().getLifeCycle();
lf.sendConsumerExchange(exchange, endpoint);
}
| public void send(MessageExchange exchange) throws MessagingException {
if (exchange.getStatus() == ExchangeStatus.ACTIVE) {
throw new UnsupportedOperationException("Asynchonous send of active exchanges are not supported");
}
BaseLifeCycle lf = (BaseLifeCycle) endpoint.getServiceUnit().getComponent().getLifeCycle();
lf.sendConsumerExchange(exchange, endpoint);
}
|
diff --git a/src/main/java/com/pardot/rhombus/util/JsonUtil.java b/src/main/java/com/pardot/rhombus/util/JsonUtil.java
index 9f2856b..e9d6817 100644
--- a/src/main/java/com/pardot/rhombus/util/JsonUtil.java
+++ b/src/main/java/com/pardot/rhombus/util/JsonUtil.java
@@ -1,206 +1,206 @@
package com.pardot.rhombus.util;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.google.common.collect.Maps;
import com.google.common.primitives.*;
import com.pardot.rhombus.cobject.CDefinition;
import com.pardot.rhombus.cobject.CField;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.math.BigDecimal;
import java.math.BigInteger;
import java.util.*;
/**
* Pardot, an ExactTarget company
* User: Michael Frank
* Date: 4/23/13
*/
public class JsonUtil {
public static <T> T objectFromJsonResource(Class<T> objectClass, ClassLoader resourceClassLoader, String resourceLocation) throws IOException {
ObjectMapper om = new ObjectMapper();
InputStream inputStream = resourceClassLoader.getResourceAsStream(resourceLocation);
T returnObject = om.readValue(inputStream, objectClass);
inputStream.close();
return returnObject;
}
public static <T> T objectFromJsonFile(Class<T> objectClass, ClassLoader resourceClassLoader, String filename) throws IOException {
ObjectMapper om = new ObjectMapper();
File f = new File(filename);
T returnObject = om.readValue(f, objectClass);
return returnObject;
}
public static List<Map<String, Object>> rhombusMapFromResource(ClassLoader resourceClassLoader, String resourceLocation) throws IOException {
ObjectMapper om = new ObjectMapper();
InputStream inputStream = resourceClassLoader.getResourceAsStream(resourceLocation);
MapContainer mc = om.readValue(inputStream, MapContainer.class);
inputStream.close();
return mc.getValues();
}
public static SortedMap<String, Object> rhombusMapFromJsonMap(Map<String, Object> jsonMap, CDefinition definition) {
SortedMap<String, Object> rhombusMap = Maps.newTreeMap();
for(CField field : definition.getFields().values()) {
if(jsonMap.containsKey(field.getName())) {
rhombusMap.put(field.getName(), typedObjectFromValueAndField(jsonMap.get(field.getName()), field));
}
}
return rhombusMap;
}
public static Object typedObjectFromValueAndField(Object jsonValue, CField field) throws IllegalArgumentException {
if(jsonValue == null) {
return null;
}
try {
switch(field.getType()) {
case ASCII:
case VARCHAR:
case TEXT:
String parsedString = String.valueOf(jsonValue);
if (parsedString == null) {
throw new IllegalArgumentException();
} else {
return parsedString;
}
case BIGINT:
case COUNTER:
return longFromNumber(jsonValue);
case BLOB:
throw new IllegalArgumentException();
case BOOLEAN:
if (String.class.isAssignableFrom(jsonValue.getClass())) {
return Boolean.valueOf((String)jsonValue);
} else if(Boolean.class.isAssignableFrom(jsonValue.getClass())){
return jsonValue;
}else {
throw new IllegalArgumentException();
}
case DECIMAL:
if (String.class.isAssignableFrom(jsonValue.getClass())) {
return new BigDecimal((String)jsonValue);
} else if(Integer.class.isAssignableFrom(jsonValue.getClass())){
return BigDecimal.valueOf((Integer)jsonValue);
} else if(Long.class.isAssignableFrom(jsonValue.getClass())){
return BigDecimal.valueOf((Long)jsonValue);
} else if(Float.class.isAssignableFrom(jsonValue.getClass())){
return BigDecimal.valueOf((Float)jsonValue);
} else if(Double.class.isAssignableFrom(jsonValue.getClass())) {
return BigDecimal.valueOf((Double)jsonValue);
}else {
throw new IllegalArgumentException();
}
case DOUBLE:
if (String.class.isAssignableFrom(jsonValue.getClass())) {
Double parsedNumber = Doubles.tryParse((String) jsonValue);
if (parsedNumber != null) {
return parsedNumber;
}
} else if(Integer.class.isAssignableFrom(jsonValue.getClass())){
return Double.valueOf((Integer)jsonValue);
} else if(Long.class.isAssignableFrom(jsonValue.getClass())){
return Double.valueOf((Long)jsonValue);
} else if(Double.class.isAssignableFrom(jsonValue.getClass())){
return jsonValue;
}
else if(Float.class.isAssignableFrom(jsonValue.getClass())){
return Double.valueOf((Float)jsonValue);
}
throw new IllegalArgumentException();
case FLOAT:
if (String.class.isAssignableFrom(jsonValue.getClass())) {
Float parsedNumber = Floats.tryParse((String) jsonValue);
if (parsedNumber != null) {
return parsedNumber;
}
} else if(Integer.class.isAssignableFrom(jsonValue.getClass())){
return Float.valueOf((Integer)jsonValue);
} else if(Long.class.isAssignableFrom(jsonValue.getClass())){
return Float.valueOf((Long)jsonValue);
} else if(Double.class.isAssignableFrom(jsonValue.getClass())){
return ((Double)jsonValue).floatValue();
}
else if(Float.class.isAssignableFrom(jsonValue.getClass())){
return jsonValue;
}
throw new IllegalArgumentException();
case INT:
return intFromNumber(jsonValue);
case TIMESTAMP:
if(Date.class.isAssignableFrom(jsonValue.getClass())) {
return jsonValue;
} else if(Integer.class.isAssignableFrom(jsonValue.getClass())){
return new Date((Integer)jsonValue);
} else if(Long.class.isAssignableFrom(jsonValue.getClass())) {
return new Date((Long)jsonValue);
} else {
throw new IllegalArgumentException();
}
case UUID:
case TIMEUUID:
if(UUID.class.isAssignableFrom(jsonValue.getClass())) {
return jsonValue;
} else if(String.class.isAssignableFrom(jsonValue.getClass())){
return UUID.fromString((String)jsonValue);
} else {
throw new IllegalArgumentException();
}
case VARINT:
if(String.class.isAssignableFrom(jsonValue.getClass())) {
return new BigInteger((String)jsonValue);
}
return BigInteger.valueOf(longFromNumber(jsonValue));
default:
return null;
}
} catch (IllegalArgumentException e) {
- throw new IllegalArgumentException("Field" + field.getName() + ": Unable to convert "+ jsonValue + " of type "+jsonValue.getClass()+" to C* type " + field.getType().toString());
+ throw new IllegalArgumentException("Field " + field.getName() + ": Unable to convert "+ jsonValue + " of type "+jsonValue.getClass()+" to C* type " + field.getType().toString());
}
}
private static Long longFromNumber(Object number) {
if(Boolean.class.isAssignableFrom(number.getClass())) {
return ((Boolean)number ? 1L : 0L);
} else if(String.class.isAssignableFrom(number.getClass())) {
Long parsedNumber = Longs.tryParse((String) number);
if (parsedNumber != null) {
return parsedNumber;
}
} else if(Double.class.isAssignableFrom(number.getClass())) {
return ((Double)number).longValue();
} else if(Float.class.isAssignableFrom(number.getClass())) {
return ((Float)number).longValue();
} else if(Integer.class.isAssignableFrom(number.getClass())) {
return ((Integer)number).longValue();
} else if(Long.class.isAssignableFrom(number.getClass())) {
return (Long)number;
}
throw new IllegalArgumentException();
}
private static Integer intFromNumber(Object number) {
if(Boolean.class.isAssignableFrom(number.getClass())) {
return ((Boolean)number ? 1 : 0);
} else if(String.class.isAssignableFrom(number.getClass())) {
Integer parsedNumber = Ints.tryParse((String) number);
if (parsedNumber != null) {
return parsedNumber;
}
} else if(Double.class.isAssignableFrom(number.getClass())) {
return ((Double)number).intValue();
} else if(Float.class.isAssignableFrom(number.getClass())) {
return ((Float)number).intValue();
} else if(Long.class.isAssignableFrom(number.getClass())) {
return ((Long)number).intValue();
} else if(Integer.class.isAssignableFrom(number.getClass())) {
return (Integer)number;
}
throw new IllegalArgumentException();
}
}
| true | true | public static Object typedObjectFromValueAndField(Object jsonValue, CField field) throws IllegalArgumentException {
if(jsonValue == null) {
return null;
}
try {
switch(field.getType()) {
case ASCII:
case VARCHAR:
case TEXT:
String parsedString = String.valueOf(jsonValue);
if (parsedString == null) {
throw new IllegalArgumentException();
} else {
return parsedString;
}
case BIGINT:
case COUNTER:
return longFromNumber(jsonValue);
case BLOB:
throw new IllegalArgumentException();
case BOOLEAN:
if (String.class.isAssignableFrom(jsonValue.getClass())) {
return Boolean.valueOf((String)jsonValue);
} else if(Boolean.class.isAssignableFrom(jsonValue.getClass())){
return jsonValue;
}else {
throw new IllegalArgumentException();
}
case DECIMAL:
if (String.class.isAssignableFrom(jsonValue.getClass())) {
return new BigDecimal((String)jsonValue);
} else if(Integer.class.isAssignableFrom(jsonValue.getClass())){
return BigDecimal.valueOf((Integer)jsonValue);
} else if(Long.class.isAssignableFrom(jsonValue.getClass())){
return BigDecimal.valueOf((Long)jsonValue);
} else if(Float.class.isAssignableFrom(jsonValue.getClass())){
return BigDecimal.valueOf((Float)jsonValue);
} else if(Double.class.isAssignableFrom(jsonValue.getClass())) {
return BigDecimal.valueOf((Double)jsonValue);
}else {
throw new IllegalArgumentException();
}
case DOUBLE:
if (String.class.isAssignableFrom(jsonValue.getClass())) {
Double parsedNumber = Doubles.tryParse((String) jsonValue);
if (parsedNumber != null) {
return parsedNumber;
}
} else if(Integer.class.isAssignableFrom(jsonValue.getClass())){
return Double.valueOf((Integer)jsonValue);
} else if(Long.class.isAssignableFrom(jsonValue.getClass())){
return Double.valueOf((Long)jsonValue);
} else if(Double.class.isAssignableFrom(jsonValue.getClass())){
return jsonValue;
}
else if(Float.class.isAssignableFrom(jsonValue.getClass())){
return Double.valueOf((Float)jsonValue);
}
throw new IllegalArgumentException();
case FLOAT:
if (String.class.isAssignableFrom(jsonValue.getClass())) {
Float parsedNumber = Floats.tryParse((String) jsonValue);
if (parsedNumber != null) {
return parsedNumber;
}
} else if(Integer.class.isAssignableFrom(jsonValue.getClass())){
return Float.valueOf((Integer)jsonValue);
} else if(Long.class.isAssignableFrom(jsonValue.getClass())){
return Float.valueOf((Long)jsonValue);
} else if(Double.class.isAssignableFrom(jsonValue.getClass())){
return ((Double)jsonValue).floatValue();
}
else if(Float.class.isAssignableFrom(jsonValue.getClass())){
return jsonValue;
}
throw new IllegalArgumentException();
case INT:
return intFromNumber(jsonValue);
case TIMESTAMP:
if(Date.class.isAssignableFrom(jsonValue.getClass())) {
return jsonValue;
} else if(Integer.class.isAssignableFrom(jsonValue.getClass())){
return new Date((Integer)jsonValue);
} else if(Long.class.isAssignableFrom(jsonValue.getClass())) {
return new Date((Long)jsonValue);
} else {
throw new IllegalArgumentException();
}
case UUID:
case TIMEUUID:
if(UUID.class.isAssignableFrom(jsonValue.getClass())) {
return jsonValue;
} else if(String.class.isAssignableFrom(jsonValue.getClass())){
return UUID.fromString((String)jsonValue);
} else {
throw new IllegalArgumentException();
}
case VARINT:
if(String.class.isAssignableFrom(jsonValue.getClass())) {
return new BigInteger((String)jsonValue);
}
return BigInteger.valueOf(longFromNumber(jsonValue));
default:
return null;
}
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("Field" + field.getName() + ": Unable to convert "+ jsonValue + " of type "+jsonValue.getClass()+" to C* type " + field.getType().toString());
}
}
| public static Object typedObjectFromValueAndField(Object jsonValue, CField field) throws IllegalArgumentException {
if(jsonValue == null) {
return null;
}
try {
switch(field.getType()) {
case ASCII:
case VARCHAR:
case TEXT:
String parsedString = String.valueOf(jsonValue);
if (parsedString == null) {
throw new IllegalArgumentException();
} else {
return parsedString;
}
case BIGINT:
case COUNTER:
return longFromNumber(jsonValue);
case BLOB:
throw new IllegalArgumentException();
case BOOLEAN:
if (String.class.isAssignableFrom(jsonValue.getClass())) {
return Boolean.valueOf((String)jsonValue);
} else if(Boolean.class.isAssignableFrom(jsonValue.getClass())){
return jsonValue;
}else {
throw new IllegalArgumentException();
}
case DECIMAL:
if (String.class.isAssignableFrom(jsonValue.getClass())) {
return new BigDecimal((String)jsonValue);
} else if(Integer.class.isAssignableFrom(jsonValue.getClass())){
return BigDecimal.valueOf((Integer)jsonValue);
} else if(Long.class.isAssignableFrom(jsonValue.getClass())){
return BigDecimal.valueOf((Long)jsonValue);
} else if(Float.class.isAssignableFrom(jsonValue.getClass())){
return BigDecimal.valueOf((Float)jsonValue);
} else if(Double.class.isAssignableFrom(jsonValue.getClass())) {
return BigDecimal.valueOf((Double)jsonValue);
}else {
throw new IllegalArgumentException();
}
case DOUBLE:
if (String.class.isAssignableFrom(jsonValue.getClass())) {
Double parsedNumber = Doubles.tryParse((String) jsonValue);
if (parsedNumber != null) {
return parsedNumber;
}
} else if(Integer.class.isAssignableFrom(jsonValue.getClass())){
return Double.valueOf((Integer)jsonValue);
} else if(Long.class.isAssignableFrom(jsonValue.getClass())){
return Double.valueOf((Long)jsonValue);
} else if(Double.class.isAssignableFrom(jsonValue.getClass())){
return jsonValue;
}
else if(Float.class.isAssignableFrom(jsonValue.getClass())){
return Double.valueOf((Float)jsonValue);
}
throw new IllegalArgumentException();
case FLOAT:
if (String.class.isAssignableFrom(jsonValue.getClass())) {
Float parsedNumber = Floats.tryParse((String) jsonValue);
if (parsedNumber != null) {
return parsedNumber;
}
} else if(Integer.class.isAssignableFrom(jsonValue.getClass())){
return Float.valueOf((Integer)jsonValue);
} else if(Long.class.isAssignableFrom(jsonValue.getClass())){
return Float.valueOf((Long)jsonValue);
} else if(Double.class.isAssignableFrom(jsonValue.getClass())){
return ((Double)jsonValue).floatValue();
}
else if(Float.class.isAssignableFrom(jsonValue.getClass())){
return jsonValue;
}
throw new IllegalArgumentException();
case INT:
return intFromNumber(jsonValue);
case TIMESTAMP:
if(Date.class.isAssignableFrom(jsonValue.getClass())) {
return jsonValue;
} else if(Integer.class.isAssignableFrom(jsonValue.getClass())){
return new Date((Integer)jsonValue);
} else if(Long.class.isAssignableFrom(jsonValue.getClass())) {
return new Date((Long)jsonValue);
} else {
throw new IllegalArgumentException();
}
case UUID:
case TIMEUUID:
if(UUID.class.isAssignableFrom(jsonValue.getClass())) {
return jsonValue;
} else if(String.class.isAssignableFrom(jsonValue.getClass())){
return UUID.fromString((String)jsonValue);
} else {
throw new IllegalArgumentException();
}
case VARINT:
if(String.class.isAssignableFrom(jsonValue.getClass())) {
return new BigInteger((String)jsonValue);
}
return BigInteger.valueOf(longFromNumber(jsonValue));
default:
return null;
}
} catch (IllegalArgumentException e) {
throw new IllegalArgumentException("Field " + field.getName() + ": Unable to convert "+ jsonValue + " of type "+jsonValue.getClass()+" to C* type " + field.getType().toString());
}
}
|
diff --git a/src/org/pentaho/agilebi/pdi/wizard/EmbeddedWizard.java b/src/org/pentaho/agilebi/pdi/wizard/EmbeddedWizard.java
index 9f54bca..7797d98 100644
--- a/src/org/pentaho/agilebi/pdi/wizard/EmbeddedWizard.java
+++ b/src/org/pentaho/agilebi/pdi/wizard/EmbeddedWizard.java
@@ -1,198 +1,201 @@
/*
* This program is free software; you can redistribute it and/or modify it under the
* terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software
* Foundation.
*
* You should have received a copy of the GNU Lesser General Public License along with this
* program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
* or from the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* Copyright (c) 2009 Pentaho Corporation.. All rights reserved.
*/
package org.pentaho.agilebi.pdi.wizard;
//import java.awt.HeadlessException;
import java.beans.PropertyChangeEvent;
import java.beans.PropertyChangeListener;
import org.eclipse.swt.widgets.Display;
import org.pentaho.agilebi.pdi.modeler.ModelerWorkspace;
import org.pentaho.agilebi.pdi.wizard.ui.xul.DefaultWizardDesignTimeContext;
import org.pentaho.agilebi.pdi.wizard.ui.xul.steps.DataSourceAndQueryStep;
import org.pentaho.di.core.gui.SpoonFactory;
import org.pentaho.di.ui.spoon.Spoon;
import org.pentaho.reporting.engine.classic.core.AbstractReportDefinition;
import org.pentaho.reporting.engine.classic.core.CompoundDataFactory;
import org.pentaho.reporting.engine.classic.core.MasterReport;
import org.pentaho.reporting.engine.classic.core.ReportProcessingException;
import org.pentaho.reporting.engine.classic.core.SubReport;
import org.pentaho.reporting.engine.classic.core.designtime.DesignTimeContext;
import org.pentaho.reporting.engine.classic.wizard.WizardProcessor;
import org.pentaho.reporting.engine.classic.wizard.WizardProcessorUtil;
import org.pentaho.reporting.engine.classic.wizard.model.WizardSpecification;
import org.pentaho.reporting.engine.classic.wizard.ui.xul.WizardEditorModel;
import org.pentaho.reporting.engine.classic.wizard.ui.xul.components.WizardContentPanel;
import org.pentaho.reporting.engine.classic.wizard.ui.xul.components.WizardController;
import org.pentaho.reporting.engine.classic.wizard.ui.xul.steps.FormatStep;
import org.pentaho.reporting.engine.classic.wizard.ui.xul.steps.LayoutStep;
import org.pentaho.reporting.engine.classic.wizard.ui.xul.steps.LookAndFeelStep;
import org.pentaho.reporting.libraries.base.util.DebugLog;
import org.pentaho.ui.xul.XulComponent;
import org.pentaho.ui.xul.XulDomContainer;
import org.pentaho.ui.xul.XulException;
import org.pentaho.ui.xul.binding.DefaultBindingFactory;
import org.pentaho.ui.xul.containers.XulDialog;
import org.pentaho.ui.xul.dom.Document;
import org.pentaho.ui.xul.swt.SwtXulLoader;
/**
* Todo: A wizard entry point that instantiates an Xul-based swt report wizard.
*
* @author William E. Seyler
*/
public class EmbeddedWizard
{
private final static String MAIN_WIZARD_PANEL = "org/pentaho/reporting/engine/classic/wizard/ui/xul/res/main_wizard_panel.xul"; //$NON-NLS-1$
private ModelerWorkspace model;
private XulDialog dialog;
private PreviewWizardController wizardController;
public EmbeddedWizard() {
this(null);
}
public EmbeddedWizard(ModelerWorkspace model)
{
this.model = model;
init();
}
private void init()
{
wizardController = new PreviewWizardController(new WizardEditorModel(), new DefaultBindingFactory());
// add the steps ..
wizardController.addStep(new LookAndFeelStep());
wizardController.addStep(new DataSourceAndQueryStep());
wizardController.addStep(new LayoutStep());
wizardController.addStep(new FormatStep());
wizardController.addPropertyChangeListener(WizardController.CANCELLED_PROPERTY_NAME, new CancelHandler());
wizardController.addPropertyChangeListener(WizardController.FINISHED_PROPERTY_NAME, new FinishedHandler());
}
private AbstractReportDefinition retVal = null;
public AbstractReportDefinition run(final AbstractReportDefinition original) throws ReportProcessingException
{
if(Display.getDefault().getThread().equals(Thread.currentThread()) == false){
Display.getDefault().syncExec(new Runnable(){
public void run() {
try {
EmbeddedWizard.this.retVal = EmbeddedWizard.this.run(original);
} catch (ReportProcessingException e) {
e.printStackTrace();
}
}
});
return retVal;
}
// Set the report if we have one otherwise create a new one
if (original != null)
{
wizardController.getEditorModel().setReportDefinition(original, true);
}
else
{
final MasterReport report = new MasterReport();
CompoundDataFactory cdf = new CompoundDataFactory();
report.setDataFactory(cdf);
wizardController.getEditorModel().setReportDefinition(report, false);
((DataSourceAndQueryStep)wizardController.getStep(1)).setModel(model);
}
// Create the gui
try
{
final SwtXulLoader loader = new SwtXulLoader();
loader.setOuterContext(((Spoon) SpoonFactory.getInstance()).getShell());
loader.registerClassLoader(getClass().getClassLoader());
XulDomContainer mainWizardContainer = loader.loadXul(MAIN_WIZARD_PANEL);
new WizardContentPanel(wizardController).addContent(mainWizardContainer);
wizardController.registerMainXULContainer(mainWizardContainer);
wizardController.onLoad();
final Document documentRoot = mainWizardContainer.getDocumentRoot();
final XulComponent root = documentRoot.getRootElement();
if (!(root instanceof XulDialog))
{
throw new XulException("Root panel is not an instance of XulDialog: " + root);
}
dialog = (XulDialog) root;
// This is a hack to get the JDialog (this wizard) to become the parent window of windows/dialogs
// that the wizard creates.
final DesignTimeContext context = new DefaultWizardDesignTimeContext(wizardController.getEditorModel());
wizardController.setDesignTimeContext(context);
// if we're doing an edit drop into the layout step
if (wizardController.getEditorModel().isEditing())
{
wizardController.setActiveStep(0);
- ((LookAndFeelStep)wizardController.getStep(0)).setSelectedTemplateByPath(original.getAttribute("http://reporting.pentaho.org/namespaces/engine/attributes/wizard", "template").toString());
+ Object origTemp = original.getAttribute("http://reporting.pentaho.org/namespaces/engine/attributes/wizard", "template");
+ if(origTemp != null){
+ ((LookAndFeelStep)wizardController.getStep(0)).setSelectedTemplateByPath(origTemp.toString());
+ }
if (wizardController.getStep(0).isValid())
{
wizardController.setActiveStep(1); // initializes the data
if (wizardController.getStep(1).isValid())
{
wizardController.setActiveStep(2);
}
}
}
dialog.show();
}
catch (Exception e)
{
DebugLog.log("Failed to initialze the wizard", e);
return null;
}
return null;
}
private class CancelHandler implements PropertyChangeListener
{
public void propertyChange(final PropertyChangeEvent evt)
{
if (wizardController.isCancelled())
{
dialog.hide();
}
}
}
private class FinishedHandler implements PropertyChangeListener
{
public void propertyChange(final PropertyChangeEvent evt)
{
if (wizardController.isFinished())
{
dialog.hide();
}
}
}
}
| true | true | public AbstractReportDefinition run(final AbstractReportDefinition original) throws ReportProcessingException
{
if(Display.getDefault().getThread().equals(Thread.currentThread()) == false){
Display.getDefault().syncExec(new Runnable(){
public void run() {
try {
EmbeddedWizard.this.retVal = EmbeddedWizard.this.run(original);
} catch (ReportProcessingException e) {
e.printStackTrace();
}
}
});
return retVal;
}
// Set the report if we have one otherwise create a new one
if (original != null)
{
wizardController.getEditorModel().setReportDefinition(original, true);
}
else
{
final MasterReport report = new MasterReport();
CompoundDataFactory cdf = new CompoundDataFactory();
report.setDataFactory(cdf);
wizardController.getEditorModel().setReportDefinition(report, false);
((DataSourceAndQueryStep)wizardController.getStep(1)).setModel(model);
}
// Create the gui
try
{
final SwtXulLoader loader = new SwtXulLoader();
loader.setOuterContext(((Spoon) SpoonFactory.getInstance()).getShell());
loader.registerClassLoader(getClass().getClassLoader());
XulDomContainer mainWizardContainer = loader.loadXul(MAIN_WIZARD_PANEL);
new WizardContentPanel(wizardController).addContent(mainWizardContainer);
wizardController.registerMainXULContainer(mainWizardContainer);
wizardController.onLoad();
final Document documentRoot = mainWizardContainer.getDocumentRoot();
final XulComponent root = documentRoot.getRootElement();
if (!(root instanceof XulDialog))
{
throw new XulException("Root panel is not an instance of XulDialog: " + root);
}
dialog = (XulDialog) root;
// This is a hack to get the JDialog (this wizard) to become the parent window of windows/dialogs
// that the wizard creates.
final DesignTimeContext context = new DefaultWizardDesignTimeContext(wizardController.getEditorModel());
wizardController.setDesignTimeContext(context);
// if we're doing an edit drop into the layout step
if (wizardController.getEditorModel().isEditing())
{
wizardController.setActiveStep(0);
((LookAndFeelStep)wizardController.getStep(0)).setSelectedTemplateByPath(original.getAttribute("http://reporting.pentaho.org/namespaces/engine/attributes/wizard", "template").toString());
if (wizardController.getStep(0).isValid())
{
wizardController.setActiveStep(1); // initializes the data
if (wizardController.getStep(1).isValid())
{
wizardController.setActiveStep(2);
}
}
}
dialog.show();
}
catch (Exception e)
{
DebugLog.log("Failed to initialze the wizard", e);
return null;
}
return null;
}
| public AbstractReportDefinition run(final AbstractReportDefinition original) throws ReportProcessingException
{
if(Display.getDefault().getThread().equals(Thread.currentThread()) == false){
Display.getDefault().syncExec(new Runnable(){
public void run() {
try {
EmbeddedWizard.this.retVal = EmbeddedWizard.this.run(original);
} catch (ReportProcessingException e) {
e.printStackTrace();
}
}
});
return retVal;
}
// Set the report if we have one otherwise create a new one
if (original != null)
{
wizardController.getEditorModel().setReportDefinition(original, true);
}
else
{
final MasterReport report = new MasterReport();
CompoundDataFactory cdf = new CompoundDataFactory();
report.setDataFactory(cdf);
wizardController.getEditorModel().setReportDefinition(report, false);
((DataSourceAndQueryStep)wizardController.getStep(1)).setModel(model);
}
// Create the gui
try
{
final SwtXulLoader loader = new SwtXulLoader();
loader.setOuterContext(((Spoon) SpoonFactory.getInstance()).getShell());
loader.registerClassLoader(getClass().getClassLoader());
XulDomContainer mainWizardContainer = loader.loadXul(MAIN_WIZARD_PANEL);
new WizardContentPanel(wizardController).addContent(mainWizardContainer);
wizardController.registerMainXULContainer(mainWizardContainer);
wizardController.onLoad();
final Document documentRoot = mainWizardContainer.getDocumentRoot();
final XulComponent root = documentRoot.getRootElement();
if (!(root instanceof XulDialog))
{
throw new XulException("Root panel is not an instance of XulDialog: " + root);
}
dialog = (XulDialog) root;
// This is a hack to get the JDialog (this wizard) to become the parent window of windows/dialogs
// that the wizard creates.
final DesignTimeContext context = new DefaultWizardDesignTimeContext(wizardController.getEditorModel());
wizardController.setDesignTimeContext(context);
// if we're doing an edit drop into the layout step
if (wizardController.getEditorModel().isEditing())
{
wizardController.setActiveStep(0);
Object origTemp = original.getAttribute("http://reporting.pentaho.org/namespaces/engine/attributes/wizard", "template");
if(origTemp != null){
((LookAndFeelStep)wizardController.getStep(0)).setSelectedTemplateByPath(origTemp.toString());
}
if (wizardController.getStep(0).isValid())
{
wizardController.setActiveStep(1); // initializes the data
if (wizardController.getStep(1).isValid())
{
wizardController.setActiveStep(2);
}
}
}
dialog.show();
}
catch (Exception e)
{
DebugLog.log("Failed to initialze the wizard", e);
return null;
}
return null;
}
|
diff --git a/src/ui/MultiplayerGamePanel.java b/src/ui/MultiplayerGamePanel.java
index a8d11d5..9a650ac 100644
--- a/src/ui/MultiplayerGamePanel.java
+++ b/src/ui/MultiplayerGamePanel.java
@@ -1,65 +1,65 @@
package src.ui;
import java.awt.BorderLayout;
import javax.swing.JPanel;
import src.net.NetworkGame;
import src.net.NetworkGameController;
import src.ui.controller.GameController;
import src.ui.controller.MultiplayerController;
import src.ui.creepside.CreepSideBar;
import src.ui.side.Sidebar;
/**
* Handles setup of multiplayer display components.
*/
public class MultiplayerGamePanel extends JPanel {
private static final long serialVersionUID = 1L;
private MultiplayerController controller;
private MapComponent opponentMap;
private MapComponent localMap;
private Sidebar sidebar;
private JPanel gamePanel;
public MultiplayerGamePanel(GameController localController,
NetworkGameController networkController,
NetworkGame game,
MultiplayerController multiController) {
super(new BorderLayout());
gamePanel = new JPanel();
opponentMap = new MapComponent(true);
opponentMap.setGridOn(true);
opponentMap.setSize(375, 375);
localMap = new MapComponent(false);
localMap.setGridOn(true);
localMap.setSize(375, 375);
localController.setGame(game);
- localController.setMultiplayerController(controller);
+ localController.setMultiplayerController(multiController);
networkController.setGame(game);
sidebar = new Sidebar(localController, multiController);
localController.setSidebar(sidebar);
opponentMap.setGameController(networkController);
opponentMap.setMap(game.getMap());
localMap.setGameController(localController);
localMap.setMap(game.getMap());
gamePanel.add(opponentMap);
gamePanel.add(localMap);
gamePanel.add(sidebar);
add(gamePanel, BorderLayout.CENTER);
// setup side bar
CreepSideBar cs = new CreepSideBar(localController);
add(cs, BorderLayout.SOUTH);
}
}
| true | true | public MultiplayerGamePanel(GameController localController,
NetworkGameController networkController,
NetworkGame game,
MultiplayerController multiController) {
super(new BorderLayout());
gamePanel = new JPanel();
opponentMap = new MapComponent(true);
opponentMap.setGridOn(true);
opponentMap.setSize(375, 375);
localMap = new MapComponent(false);
localMap.setGridOn(true);
localMap.setSize(375, 375);
localController.setGame(game);
localController.setMultiplayerController(controller);
networkController.setGame(game);
sidebar = new Sidebar(localController, multiController);
localController.setSidebar(sidebar);
opponentMap.setGameController(networkController);
opponentMap.setMap(game.getMap());
localMap.setGameController(localController);
localMap.setMap(game.getMap());
gamePanel.add(opponentMap);
gamePanel.add(localMap);
gamePanel.add(sidebar);
add(gamePanel, BorderLayout.CENTER);
// setup side bar
CreepSideBar cs = new CreepSideBar(localController);
add(cs, BorderLayout.SOUTH);
}
| public MultiplayerGamePanel(GameController localController,
NetworkGameController networkController,
NetworkGame game,
MultiplayerController multiController) {
super(new BorderLayout());
gamePanel = new JPanel();
opponentMap = new MapComponent(true);
opponentMap.setGridOn(true);
opponentMap.setSize(375, 375);
localMap = new MapComponent(false);
localMap.setGridOn(true);
localMap.setSize(375, 375);
localController.setGame(game);
localController.setMultiplayerController(multiController);
networkController.setGame(game);
sidebar = new Sidebar(localController, multiController);
localController.setSidebar(sidebar);
opponentMap.setGameController(networkController);
opponentMap.setMap(game.getMap());
localMap.setGameController(localController);
localMap.setMap(game.getMap());
gamePanel.add(opponentMap);
gamePanel.add(localMap);
gamePanel.add(sidebar);
add(gamePanel, BorderLayout.CENTER);
// setup side bar
CreepSideBar cs = new CreepSideBar(localController);
add(cs, BorderLayout.SOUTH);
}
|
diff --git a/src/main/java/com/fasterxml/jackson/databind/node/BigIntegerNode.java b/src/main/java/com/fasterxml/jackson/databind/node/BigIntegerNode.java
index 044314d84..c29f7998e 100644
--- a/src/main/java/com/fasterxml/jackson/databind/node/BigIntegerNode.java
+++ b/src/main/java/com/fasterxml/jackson/databind/node/BigIntegerNode.java
@@ -1,116 +1,116 @@
package com.fasterxml.jackson.databind.node;
import java.io.IOException;
import java.math.BigDecimal;
import java.math.BigInteger;
import com.fasterxml.jackson.core.*;
import com.fasterxml.jackson.databind.SerializerProvider;
/**
* Numeric node that contains simple 64-bit integer values.
*/
public final class BigIntegerNode
extends NumericNode
{
private final static BigInteger MIN_INTEGER = BigInteger.valueOf(Integer.MIN_VALUE);
private final static BigInteger MAX_INTEGER = BigInteger.valueOf(Integer.MAX_VALUE);
private final static BigInteger MIN_LONG = BigInteger.valueOf(Long.MIN_VALUE);
private final static BigInteger MAX_LONG = BigInteger.valueOf(Long.MAX_VALUE);
final protected BigInteger _value;
/*
/**********************************************************
/* Construction
/**********************************************************
*/
public BigIntegerNode(BigInteger v) { _value = v; }
public static BigIntegerNode valueOf(BigInteger v) { return new BigIntegerNode(v); }
/*
/**********************************************************
/* Overrridden JsonNode methods
/**********************************************************
*/
@Override
public JsonToken asToken() { return JsonToken.VALUE_NUMBER_INT; }
@Override
public JsonParser.NumberType numberType() { return JsonParser.NumberType.BIG_INTEGER; }
@Override
public boolean isIntegralNumber() { return true; }
@Override
public boolean isBigInteger() { return true; }
@Override public boolean canConvertToInt() {
return (_value.compareTo(MIN_INTEGER) >= 0) && (_value.compareTo(MAX_INTEGER) <= 0);
}
@Override public boolean canConvertToLong() {
return (_value.compareTo(MIN_LONG) >= 0) && (_value.compareTo(MAX_LONG) <= 0);
}
@Override
public Number numberValue() {
return _value;
}
@Override
public int intValue() { return _value.intValue(); }
@Override
public long longValue() { return _value.longValue(); }
@Override
public BigInteger bigIntegerValue() { return _value; }
@Override
public double doubleValue() { return _value.doubleValue(); }
@Override
public BigDecimal decimalValue() { return new BigDecimal(_value); }
/*
/**********************************************************
/* General type coercions
/**********************************************************
*/
@Override
public String asText() {
return _value.toString();
}
@Override
public boolean asBoolean(boolean defaultValue) {
return !BigInteger.ZERO.equals(_value);
}
@Override
public final void serialize(JsonGenerator jg, SerializerProvider provider)
throws IOException, JsonProcessingException
{
jg.writeNumber(_value);
}
@Override
public boolean equals(Object o)
{
if (o == this) return true;
if (o == null) return false;
if (o.getClass() != getClass()) { // final class, can do this
return false;
}
- return ((BigIntegerNode) o)._value == _value;
+ return ((BigIntegerNode) o)._value.equals(_value);
}
@Override
public int hashCode() {
return _value.hashCode();
}
}
| true | true | public boolean equals(Object o)
{
if (o == this) return true;
if (o == null) return false;
if (o.getClass() != getClass()) { // final class, can do this
return false;
}
return ((BigIntegerNode) o)._value == _value;
}
| public boolean equals(Object o)
{
if (o == this) return true;
if (o == null) return false;
if (o.getClass() != getClass()) { // final class, can do this
return false;
}
return ((BigIntegerNode) o)._value.equals(_value);
}
|
diff --git a/samples/src/test/java/org/springframework/batch/sample/AbstractBatchLauncherTests.java b/samples/src/test/java/org/springframework/batch/sample/AbstractBatchLauncherTests.java
index 1a3957545..2ed136e3f 100644
--- a/samples/src/test/java/org/springframework/batch/sample/AbstractBatchLauncherTests.java
+++ b/samples/src/test/java/org/springframework/batch/sample/AbstractBatchLauncherTests.java
@@ -1,64 +1,64 @@
/*
* Copyright 2006-2007 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.springframework.batch.sample;
import org.springframework.batch.core.configuration.JobConfiguration;
import org.springframework.batch.execution.bootstrap.JobLauncher;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.test.AbstractDependencyInjectionSpringContextTests;
/**
* @author Dave Syer
*
*/
public abstract class AbstractBatchLauncherTests extends AbstractDependencyInjectionSpringContextTests {
protected JobLauncher launcher;
private JobConfiguration jobConfiguration;
protected ConfigurableApplicationContext createApplicationContext(
String[] locations) {
String[] allLocations = new String[locations.length+1];
- System.arraycopy(locations, 0, allLocations, 0, locations.length);
- allLocations[locations.length] = "simple-container-definition.xml";
+ System.arraycopy(locations, 0, allLocations, 1, locations.length);
+ allLocations[0] = "simple-container-definition.xml";
return super.createApplicationContext(allLocations);
}
/**
* Subclasses can provide name of job to run. We guess it by looking at the
* unique job configuration name.
*/
protected String getJobName() {
return jobConfiguration.getName();
}
/**
* @param jobConfiguration the jobConfiguration to set
*/
public void setJobConfiguration(JobConfiguration jobConfiguration) {
this.jobConfiguration = jobConfiguration;
}
/**
* Public setter for the {@link JobLauncher} property.
*
* @param launcher the launcher to set
*/
public void setLauncher(JobLauncher launcher) {
this.launcher = launcher;
}
}
| true | true | protected ConfigurableApplicationContext createApplicationContext(
String[] locations) {
String[] allLocations = new String[locations.length+1];
System.arraycopy(locations, 0, allLocations, 0, locations.length);
allLocations[locations.length] = "simple-container-definition.xml";
return super.createApplicationContext(allLocations);
}
| protected ConfigurableApplicationContext createApplicationContext(
String[] locations) {
String[] allLocations = new String[locations.length+1];
System.arraycopy(locations, 0, allLocations, 1, locations.length);
allLocations[0] = "simple-container-definition.xml";
return super.createApplicationContext(allLocations);
}
|
diff --git a/GraphicsSample.java b/GraphicsSample.java
index 2726170..fcbf474 100644
--- a/GraphicsSample.java
+++ b/GraphicsSample.java
@@ -1,66 +1,66 @@
import java.awt.*;
import java.awt.image.*;
class GraphicsSample
{
public static void main(String args[]) {
GraphicsDraw paper = new GraphicsDraw();
paper.setSize(640, 480);
paper.setTitle("Fractal");
paper.setVisible( true );
}
}
class GraphicsDraw extends Frame
{
public void paint(Graphics g) {
BufferedImage buf = new BufferedImage(640, 480, BufferedImage.TYPE_INT_ARGB);
Graphics bufg = buf.getGraphics();
drawTree(buf, 1, 100, 240, 0, 1);
g.drawImage(buf, 0, 0, Color.white, null);
}
private int radius(int n) {
return 100 / (int)(Math.sqrt(n));
}
private boolean canDraw(BufferedImage buf, int x, int y, int r) {
if (x < 0 || y < 0 || x >= 640 || y >= 480)
return false;
boolean res = buf.getRGB(x, y) == 0;
return res;
}
private void drawTree(BufferedImage buf, int n, int x, int y, double angle, int sign) {
if (n > 31) return;
int r = radius(n);
int c = (n % 15) * 16;
Graphics g = buf.getGraphics();
if (canDraw(buf, x, y, r / 2)) {
g.setColor(new Color(255, 255 - c, c));
g.fillOval(x - r / 2, y - r / 2, r, r);
} else {
return;
}
int r2 = (r + radius(n + 1)) / 2;
drawTree(buf, n + 1,
x + (int)(Math.cos(angle) * r2), y + (int)(Math.sin(angle) * r2),
angle + Math.PI * 0.1 * sign, sign);
- if (Math.random() < 0.5) {
+ if (Math.random() < 0.6) {
double a2 = angle - Math.PI * 0.5 * sign;
int x2 = x + (int)(Math.cos(a2) * r2);
int y2 = y + (int)(Math.sin(a2) * r2);
if (x2 >= 0 && y2 >= 0 && x2 < 640 && y2 < 480) {
drawTree(buf, n + 1, x2, y2, a2, -sign);
}
}
}
}
| true | true | private void drawTree(BufferedImage buf, int n, int x, int y, double angle, int sign) {
if (n > 31) return;
int r = radius(n);
int c = (n % 15) * 16;
Graphics g = buf.getGraphics();
if (canDraw(buf, x, y, r / 2)) {
g.setColor(new Color(255, 255 - c, c));
g.fillOval(x - r / 2, y - r / 2, r, r);
} else {
return;
}
int r2 = (r + radius(n + 1)) / 2;
drawTree(buf, n + 1,
x + (int)(Math.cos(angle) * r2), y + (int)(Math.sin(angle) * r2),
angle + Math.PI * 0.1 * sign, sign);
if (Math.random() < 0.5) {
double a2 = angle - Math.PI * 0.5 * sign;
int x2 = x + (int)(Math.cos(a2) * r2);
int y2 = y + (int)(Math.sin(a2) * r2);
if (x2 >= 0 && y2 >= 0 && x2 < 640 && y2 < 480) {
drawTree(buf, n + 1, x2, y2, a2, -sign);
}
}
}
| private void drawTree(BufferedImage buf, int n, int x, int y, double angle, int sign) {
if (n > 31) return;
int r = radius(n);
int c = (n % 15) * 16;
Graphics g = buf.getGraphics();
if (canDraw(buf, x, y, r / 2)) {
g.setColor(new Color(255, 255 - c, c));
g.fillOval(x - r / 2, y - r / 2, r, r);
} else {
return;
}
int r2 = (r + radius(n + 1)) / 2;
drawTree(buf, n + 1,
x + (int)(Math.cos(angle) * r2), y + (int)(Math.sin(angle) * r2),
angle + Math.PI * 0.1 * sign, sign);
if (Math.random() < 0.6) {
double a2 = angle - Math.PI * 0.5 * sign;
int x2 = x + (int)(Math.cos(a2) * r2);
int y2 = y + (int)(Math.sin(a2) * r2);
if (x2 >= 0 && y2 >= 0 && x2 < 640 && y2 < 480) {
drawTree(buf, n + 1, x2, y2, a2, -sign);
}
}
}
|
diff --git a/video/src/processing/video/Movie.java b/video/src/processing/video/Movie.java
index 67071b9c7..b1ee78aa2 100644
--- a/video/src/processing/video/Movie.java
+++ b/video/src/processing/video/Movie.java
@@ -1,712 +1,713 @@
/* -*- mode: java; c-basic-offset: 2; indent-tabs-mode: nil -*- */
/*
Part of the Processing project - http://processing.org
Copyright (c) 2004-07 Ben Fry and Casey Reas
The previous version of this code was developed by Hernando Barragan
This library is free software; you can redistribute it and/or
modify it under the terms of the GNU Lesser General Public
License as published by the Free Software Foundation; either
version 2.1 of the License, or (at your option) any later version.
This library is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General
Public License along with this library; if not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330,
Boston, MA 02111-1307 USA
*/
package processing.video;
import processing.core.*;
import java.io.*;
import java.lang.reflect.*;
import quicktime.*;
import quicktime.io.QTFile;
import quicktime.qd.*;
import quicktime.std.*;
import quicktime.std.movies.media.DataRef;
import quicktime.util.QTHandle;
import quicktime.util.RawEncodedImage;
public class Movie extends PImage implements PConstants, Runnable {
// no longer needing a reference to the parent because PImage has one
//PApplet parent;
Method movieEventMethod;
String filename;
Thread runner;
PImage borderImage;
boolean removeBorders = true;
boolean play;
boolean repeat;
boolean available;
int fps;
/**
* The QuickTime for Java "Movie" object, made public
* in case anyone wants to play with it.
*/
public quicktime.std.movies.Movie movie;
QDRect movieRect;
QDGraphics movieGraphics;
boolean firstFrame = true;
RawEncodedImage raw;
/*
static {
try {
//System.out.println("jlp = " + System.getProperty("java.library.path"));
QTSession.open();
} catch (QTException e) {
e.printStackTrace();
}
// shutting off for 0116, hoping for better exception handling
QTRuntimeException.registerHandler(new QTRuntimeHandler() {
public void exceptionOccurred(QTRuntimeException e,
Object obj, String s, boolean flag) {
System.err.println("Problem inside Movie");
e.printStackTrace();
}
});
}
*/
public Movie(PApplet parent, String filename) {
this(parent, filename, 30);
}
public Movie(PApplet parent, String filename, int ifps) {
// this creates a fake image so that the first time this
// attempts to draw, something happens that's not an exception
super(1, 1, RGB);
this.parent = parent;
try {
QTSession.open();
} catch (QTException e) {
e.printStackTrace();
return;
}
// first check to see if this can be read locally from a file.
// otherwise, will have to load the file into memory, which is
// gonna make people unhappy who are trying to play back 50 MB
// quicktime movies with a locally installed piece exported
// as an application.
try {
try {
// first try a local file using the dataPath. usually this will
// work ok, but sometimes the dataPath is inside a jar file,
// which is less fun, so this will crap out.
File file = new File(parent.dataPath(filename));
if (file.exists()) {
movie = fromDataRef(new DataRef(new QTFile(file)));
//init(parent, movie, ifps);
//return;
}
} catch (Exception e) { } // ignored
// read from a folder local to the current working dir
// called "data". presumably this might be the data folder,
// though that should be caught above, if such a folder exists.
/*
if (movie == null) {
try {
File file = new File("data", filename);
if (file.exists()) {
movie = fromDataRef(new DataRef(new QTFile(file)));
init(parent, movie, ifps);
return;
}
} catch (QTException e2) { }
}
*/
// read from a file just hanging out in the local folder.
// this might happen when the video library is used with some
// other application, or the person enters a full path name
if (movie == null) {
try {
File file = new File(filename);
if (file.exists()) {
movie = fromDataRef(new DataRef(new QTFile(file)));
//init(parent, movie, ifps);
//return;
}
} catch (QTException e1) { }
}
} catch (SecurityException se) {
// online, whups. catch the security exception out here rather than
// doing it three times (or whatever) for each of the cases above.
}
// if the movie can't be read from a local file, it has to be read
// into a byte array and passed to qtjava. it's annoying that apple
// doesn't have something in the api to read a movie from a friggin
// InputStream, but oh well. it's their api.
if (movie == null) {
byte data[] = parent.loadBytes(filename);
//int dot = filename.lastIndexOf(".");
// grab the extension from the file, use mov if there is none
//String extension = (dot == -1) ? "mov" :
// filename.substring(dot + 1).toLowerCase();
try {
movie = fromDataRef(new DataRef(new QTHandle(data)));
} catch (QTException e) {
e.printStackTrace();
}
}
/*
URL url = null;
this.filename = filename; // for error messages
if (filename.startsWith("http://")) {
try {
url = new URL(filename);
DataRef urlRef = new DataRef(url.toExternalForm());
movie = fromDataRef(urlRef);
init(parent, movie, ifps);
return;
} catch (QTException qte) {
qte.printStackTrace();
return;
} catch (MalformedURLException e) {
e.printStackTrace();
return;
}
}
// updated for new loading style of 0096
ClassLoader cl = parent.getClass().getClassLoader();
url = cl.getResource("data/" + filename);
if (url != null) {
init(parent, url, ifps);
return;
}
try {
try {
File file = new File(parent.dataPath(filename));
if (file.exists()) {
movie = fromDataRef(new DataRef(new QTFile(file)));
init(parent, movie, ifps);
return;
}
} catch (Exception e) { } // ignored
try {
File file = new File("data", filename);
if (file.exists()) {
movie = fromDataRef(new DataRef(new QTFile(file)));
init(parent, movie, ifps);
return;
}
} catch (QTException e2) { }
try {
File file = new File(filename);
if (file.exists()) {
movie = fromDataRef(new DataRef(new QTFile(file)));
init(parent, movie, ifps);
return;
}
} catch (QTException e1) { }
} catch (SecurityException se) { } // online, whups
*/
if (movie == null) {
parent.die("Could not find movie file " + filename, null);
}
// we've got a valid movie! let's rock.
try {
// this is probably causing the 2 seconds of audio
- movie.prePreroll(0, 1.0f);
+ // disabled pre-preroll on 0126 because of security problems
+ //movie.prePreroll(0, 1.0f);
movie.preroll(0, 1.0f);
// this has a possibility of running forever..
// should probably happen on the thread as well.
while (movie.maxLoadedTimeInMovie() == 0) {
movie.task(100);
// 0106: tried adding sleep time so this doesn't spin out of control
// works fine but doesn't really help anything
//try {
//Thread.sleep(5);
//} catch (InterruptedException e) { }
}
movie.setRate(1);
fps = ifps;
// register methods
parent.registerDispose(this);
try {
movieEventMethod =
parent.getClass().getMethod("movieEvent",
new Class[] { Movie.class });
} catch (Exception e) {
// no such method, or an error.. which is fine, just ignore
}
// and now, make the magic happen
runner = new Thread(this);
runner.start();
} catch (QTException qte) {
qte.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
/*
public Movie(PApplet parent, URL url) {
init(parent, url, 30);
}
public Movie(PApplet parent, URL url, int ifps) {
init(parent, url, ifps);
}
public void init(PApplet parent, URL url, int ifps) {
String externalized = url.toExternalForm();
System.out.println("externalized is " + externalized);
// qtjava likes file: urls to read file:/// not file:/
// so this changes them when appropriate
if (externalized.startsWith("file:/") &&
!externalized.startsWith("file:///")) {
externalized = "file:///" + url.getPath();
}
// the url version is the only available that can take
// an InputStream (indirectly) since it uses url syntax
//DataRef urlRef = new DataRef(requestFile);
try {
System.out.println(url);
System.out.println(externalized);
DataRef urlRef = new DataRef(externalized);
System.out.println(urlRef);
movie = fromDataRef(urlRef);
init(parent, movie, ifps);
} catch (QTException e) {
e.printStackTrace();
}
}
*/
/**
* Why does this function have to be so bizarre? i love the huge
* constants! i think they're neato. i feel like i'm coding for
* think pascal on my mac plus! those were happier times.
*/
private quicktime.std.movies.Movie fromDataRef(DataRef ref)
throws QTException {
return
quicktime.std.movies.Movie.fromDataRef(ref,
StdQTConstants4.newMovieAsyncOK |
StdQTConstants.newMovieActive);
}
/*
public void init(PApplet parent,
quicktime.std.movies.Movie movie, int ifps) {
this.parent = parent;
try {
// this is probably causing the 2 seconds of audio
movie.prePreroll(0, 1.0f);
movie.preroll(0, 1.0f);
// this has a possibility of running forever..
// should probably happen on the thread as well.
while (movie.maxLoadedTimeInMovie() == 0) {
movie.task(100);
// 0106: tried adding sleep time so this doesn't spin out of control
// works fine but doesn't really help anything
//try {
//Thread.sleep(5);
//} catch (InterruptedException e) { }
}
movie.setRate(1);
fps = ifps;
runner = new Thread(this);
runner.start();
// register methods
parent.registerDispose(this);
try {
movieEventMethod =
parent.getClass().getMethod("movieEvent",
new Class[] { Movie.class });
} catch (Exception e) {
// no such method, or an error.. which is fine, just ignore
}
} catch (QTException qte) {
qte.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
*/
public boolean available() {
return available;
}
public void read() {
try {
if (firstFrame) {
movieRect = movie.getBox();
//movieGraphics = new QDGraphics(movieRect);
if (quicktime.util.EndianOrder.isNativeLittleEndian()) {
movieGraphics =
new QDGraphics(QDConstants.k32BGRAPixelFormat, movieRect);
} else {
movieGraphics =
new QDGraphics(QDGraphics.kDefaultPixelFormat, movieRect);
}
}
Pict pict = movie.getPict(movie.getTime()); // returns an int
pict.draw(movieGraphics, movieRect);
PixMap pixmap = movieGraphics.getPixMap();
raw = pixmap.getPixelData();
// It needs to get at least a small part
// of the video to get the parameters
if (firstFrame) {
//int intsPerRow = pixmap.getRowBytes() / 4;
int movieWidth = movieRect.getWidth();
int movieHeight = movieRect.getHeight();
int j = raw.getRowBytes() - movieWidth*4;
// this doesn't round up.. does it need to?
int k = j / 4;
int dataWidth = movieWidth + k;
if (dataWidth != movieWidth) {
if (removeBorders) {
borderImage = new PImage(dataWidth, movieHeight, RGB);
} else {
movieWidth = dataWidth;
}
}
//int vpixels[] = new int[movieWidth * movieHeight];
//image = new PImage(vpixels, movieWidth, movieHeight, RGB);
super.init(movieWidth, movieHeight, RGB);
//parent.video = image;
firstFrame = false;
}
// this happens later (found by hernando)
//raw.copyToArray(0, image.pixels, 0, image.width * image.height);
loadPixels();
// this is identical to a chunk of code inside PCamera
// this might be a candidate to move up to PVideo or something
if (borderImage != null) { // need to remove borders
raw.copyToArray(0, borderImage.pixels,
0, borderImage.width * borderImage.height);
int borderIndex = 0;
int targetIndex = 0;
for (int i = 0; i < height; i++) {
System.arraycopy(borderImage.pixels, borderIndex,
pixels, targetIndex, width);
borderIndex += borderImage.width;
targetIndex += width;
}
} else { // just copy directly
raw.copyToArray(0, pixels, 0, width * height);
}
// ready to rock
//System.out.println("updating pixels");
//updatePixels(); // mark as modified
updatePixels();
} catch (QTException qte) {
qte.printStackTrace();
QTSession.close();
}
}
/**
* Begin playing the movie, with no repeat.
*/
public void play() {
play = true;
}
/**
* Begin playing the movie, with repeat.
*/
public void loop() {
play = true;
repeat = true;
}
/**
* Shut off the repeating loop.
*/
public void noLoop() {
repeat = false;
}
/**
* Pause the movie at its current time.
*/
public void pause() {
play = false;
//System.out.println("pause");
}
/**
* Stop the movie, and rewind.
*/
public void stop() {
play = false;
//System.out.println("stop");
try {
movie.setTimeValue(0);
} catch (StdQTException e) {
errorMessage("stop", e);
}
}
/**
* Set how often new frames are to be read from the movie.
* Does not actually set the speed of the movie playback,
* that's handled by the speed() method.
*/
public void frameRate(int ifps) {
if (ifps <= 0) {
System.err.println("Movie: ignoring bad frame rate of " +
ifps + " fps.");
} else {
fps = ifps;
}
}
/**
* Set a multiplier for how fast/slow the movie should be run.
* The default is 1.0.
* <UL>
* <LI>speed(2) will play the movie at double speed (2x).
* <LI>speed(0.5) will play at half speed.
* <LI>speed(-1) will play backwards at regular speed.
* </UL>
*/
public void speed(float rate) {
//rate = irate;
try {
movie.setRate(rate);
} catch (StdQTException e) {
errorMessage("speed", e);
}
}
/**
* Return the current time in seconds.
* The number is a float so fractions of seconds can be used.
*/
public float time() {
try {
return (float)movie.getTime() / (float)movie.getTimeScale();
} catch (StdQTException e) {
errorMessage("time", e);
}
return -1;
}
/**
* Jump to a specific location (in seconds).
* The number is a float so fractions of seconds can be used.
*/
public void jump(float where) {
try {
//movie.setTime(new TimeRecord(rate, where)); // scale, value
//movie.setTime(new TimeRecord(1, where)); // scale, value
int scaledTime = (int) (where * movie.getTimeScale());
movie.setTimeValue(scaledTime);
} catch (StdQTException e) {
errorMessage("jump", e);
}
}
/**
* Get the full length of this movie (in seconds).
*/
public float duration() {
try {
return (float)movie.getDuration() / (float)movie.getTimeScale();
} catch (StdQTException e) {
errorMessage("length", e);
}
return -1;
}
/*
public void play() {
if(!play) {
play = true;
}
start();
while( image == null) {
try {
Thread.sleep(5);
} catch (InterruptedException e) { }
}
pixels = image.pixels;
width = image.width;
height = image.height;
}
public void repeat() {
loop = true;
if(!play) {
play = true;
}
start();
while( image == null) {
try {
Thread.sleep(5);
} catch (InterruptedException e) { }
}
pixels = image.pixels;
width = image.width;
height = image.height;
}
public void pause() {
play = false;
}
*/
public void run() {
//System.out.println("entering thread");
while (Thread.currentThread() == runner) {
//System.out.print("<");
try {
//Thread.sleep(5);
Thread.sleep(1000 / fps);
} catch (InterruptedException e) { }
//System.out.print(">");
// this could be a lie, but..
if (play) {
//read();
//System.out.println("play");
available = true;
if (movieEventMethod != null) {
try {
movieEventMethod.invoke(parent, new Object[] { this });
} catch (Exception e) {
System.err.println("error, disabling movieEvent() for " +
filename);
e.printStackTrace();
movieEventMethod = null;
}
}
try {
if (movie.isDone() && repeat) {
movie.goToBeginning();
}
} catch (StdQTException e) {
play = false;
errorMessage("rewinding", e);
}
//} else {
//System.out.println("no play");
}
//try {
//read();
//if (movie.isDone() && loop) movie.goToBeginning();
//} catch (QTException e) {
//System.err.println("Movie exception");
//e.printStackTrace();
//QTSession.close(); ??
//}
}
}
public void dispose() {
//System.out.println("disposing");
stop();
runner = null;
QTSession.close();
}
/**
* General error reporting, all corraled here just in case
* I think of something slightly more intelligent to do.
*/
protected void errorMessage(String where, Exception e) {
parent.die("Error inside Movie." + where + "()", e);
}
}
| true | true | public Movie(PApplet parent, String filename, int ifps) {
// this creates a fake image so that the first time this
// attempts to draw, something happens that's not an exception
super(1, 1, RGB);
this.parent = parent;
try {
QTSession.open();
} catch (QTException e) {
e.printStackTrace();
return;
}
// first check to see if this can be read locally from a file.
// otherwise, will have to load the file into memory, which is
// gonna make people unhappy who are trying to play back 50 MB
// quicktime movies with a locally installed piece exported
// as an application.
try {
try {
// first try a local file using the dataPath. usually this will
// work ok, but sometimes the dataPath is inside a jar file,
// which is less fun, so this will crap out.
File file = new File(parent.dataPath(filename));
if (file.exists()) {
movie = fromDataRef(new DataRef(new QTFile(file)));
//init(parent, movie, ifps);
//return;
}
} catch (Exception e) { } // ignored
// read from a folder local to the current working dir
// called "data". presumably this might be the data folder,
// though that should be caught above, if such a folder exists.
/*
if (movie == null) {
try {
File file = new File("data", filename);
if (file.exists()) {
movie = fromDataRef(new DataRef(new QTFile(file)));
init(parent, movie, ifps);
return;
}
} catch (QTException e2) { }
}
*/
// read from a file just hanging out in the local folder.
// this might happen when the video library is used with some
// other application, or the person enters a full path name
if (movie == null) {
try {
File file = new File(filename);
if (file.exists()) {
movie = fromDataRef(new DataRef(new QTFile(file)));
//init(parent, movie, ifps);
//return;
}
} catch (QTException e1) { }
}
} catch (SecurityException se) {
// online, whups. catch the security exception out here rather than
// doing it three times (or whatever) for each of the cases above.
}
// if the movie can't be read from a local file, it has to be read
// into a byte array and passed to qtjava. it's annoying that apple
// doesn't have something in the api to read a movie from a friggin
// InputStream, but oh well. it's their api.
if (movie == null) {
byte data[] = parent.loadBytes(filename);
//int dot = filename.lastIndexOf(".");
// grab the extension from the file, use mov if there is none
//String extension = (dot == -1) ? "mov" :
// filename.substring(dot + 1).toLowerCase();
try {
movie = fromDataRef(new DataRef(new QTHandle(data)));
} catch (QTException e) {
e.printStackTrace();
}
}
/*
URL url = null;
this.filename = filename; // for error messages
if (filename.startsWith("http://")) {
try {
url = new URL(filename);
DataRef urlRef = new DataRef(url.toExternalForm());
movie = fromDataRef(urlRef);
init(parent, movie, ifps);
return;
} catch (QTException qte) {
qte.printStackTrace();
return;
} catch (MalformedURLException e) {
e.printStackTrace();
return;
}
}
// updated for new loading style of 0096
ClassLoader cl = parent.getClass().getClassLoader();
url = cl.getResource("data/" + filename);
if (url != null) {
init(parent, url, ifps);
return;
}
try {
try {
File file = new File(parent.dataPath(filename));
if (file.exists()) {
movie = fromDataRef(new DataRef(new QTFile(file)));
init(parent, movie, ifps);
return;
}
} catch (Exception e) { } // ignored
try {
File file = new File("data", filename);
if (file.exists()) {
movie = fromDataRef(new DataRef(new QTFile(file)));
init(parent, movie, ifps);
return;
}
} catch (QTException e2) { }
try {
File file = new File(filename);
if (file.exists()) {
movie = fromDataRef(new DataRef(new QTFile(file)));
init(parent, movie, ifps);
return;
}
} catch (QTException e1) { }
} catch (SecurityException se) { } // online, whups
*/
if (movie == null) {
parent.die("Could not find movie file " + filename, null);
}
// we've got a valid movie! let's rock.
try {
// this is probably causing the 2 seconds of audio
movie.prePreroll(0, 1.0f);
movie.preroll(0, 1.0f);
// this has a possibility of running forever..
// should probably happen on the thread as well.
while (movie.maxLoadedTimeInMovie() == 0) {
movie.task(100);
// 0106: tried adding sleep time so this doesn't spin out of control
// works fine but doesn't really help anything
//try {
//Thread.sleep(5);
//} catch (InterruptedException e) { }
}
movie.setRate(1);
fps = ifps;
// register methods
parent.registerDispose(this);
try {
movieEventMethod =
parent.getClass().getMethod("movieEvent",
new Class[] { Movie.class });
} catch (Exception e) {
// no such method, or an error.. which is fine, just ignore
}
// and now, make the magic happen
runner = new Thread(this);
runner.start();
} catch (QTException qte) {
qte.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
| public Movie(PApplet parent, String filename, int ifps) {
// this creates a fake image so that the first time this
// attempts to draw, something happens that's not an exception
super(1, 1, RGB);
this.parent = parent;
try {
QTSession.open();
} catch (QTException e) {
e.printStackTrace();
return;
}
// first check to see if this can be read locally from a file.
// otherwise, will have to load the file into memory, which is
// gonna make people unhappy who are trying to play back 50 MB
// quicktime movies with a locally installed piece exported
// as an application.
try {
try {
// first try a local file using the dataPath. usually this will
// work ok, but sometimes the dataPath is inside a jar file,
// which is less fun, so this will crap out.
File file = new File(parent.dataPath(filename));
if (file.exists()) {
movie = fromDataRef(new DataRef(new QTFile(file)));
//init(parent, movie, ifps);
//return;
}
} catch (Exception e) { } // ignored
// read from a folder local to the current working dir
// called "data". presumably this might be the data folder,
// though that should be caught above, if such a folder exists.
/*
if (movie == null) {
try {
File file = new File("data", filename);
if (file.exists()) {
movie = fromDataRef(new DataRef(new QTFile(file)));
init(parent, movie, ifps);
return;
}
} catch (QTException e2) { }
}
*/
// read from a file just hanging out in the local folder.
// this might happen when the video library is used with some
// other application, or the person enters a full path name
if (movie == null) {
try {
File file = new File(filename);
if (file.exists()) {
movie = fromDataRef(new DataRef(new QTFile(file)));
//init(parent, movie, ifps);
//return;
}
} catch (QTException e1) { }
}
} catch (SecurityException se) {
// online, whups. catch the security exception out here rather than
// doing it three times (or whatever) for each of the cases above.
}
// if the movie can't be read from a local file, it has to be read
// into a byte array and passed to qtjava. it's annoying that apple
// doesn't have something in the api to read a movie from a friggin
// InputStream, but oh well. it's their api.
if (movie == null) {
byte data[] = parent.loadBytes(filename);
//int dot = filename.lastIndexOf(".");
// grab the extension from the file, use mov if there is none
//String extension = (dot == -1) ? "mov" :
// filename.substring(dot + 1).toLowerCase();
try {
movie = fromDataRef(new DataRef(new QTHandle(data)));
} catch (QTException e) {
e.printStackTrace();
}
}
/*
URL url = null;
this.filename = filename; // for error messages
if (filename.startsWith("http://")) {
try {
url = new URL(filename);
DataRef urlRef = new DataRef(url.toExternalForm());
movie = fromDataRef(urlRef);
init(parent, movie, ifps);
return;
} catch (QTException qte) {
qte.printStackTrace();
return;
} catch (MalformedURLException e) {
e.printStackTrace();
return;
}
}
// updated for new loading style of 0096
ClassLoader cl = parent.getClass().getClassLoader();
url = cl.getResource("data/" + filename);
if (url != null) {
init(parent, url, ifps);
return;
}
try {
try {
File file = new File(parent.dataPath(filename));
if (file.exists()) {
movie = fromDataRef(new DataRef(new QTFile(file)));
init(parent, movie, ifps);
return;
}
} catch (Exception e) { } // ignored
try {
File file = new File("data", filename);
if (file.exists()) {
movie = fromDataRef(new DataRef(new QTFile(file)));
init(parent, movie, ifps);
return;
}
} catch (QTException e2) { }
try {
File file = new File(filename);
if (file.exists()) {
movie = fromDataRef(new DataRef(new QTFile(file)));
init(parent, movie, ifps);
return;
}
} catch (QTException e1) { }
} catch (SecurityException se) { } // online, whups
*/
if (movie == null) {
parent.die("Could not find movie file " + filename, null);
}
// we've got a valid movie! let's rock.
try {
// this is probably causing the 2 seconds of audio
// disabled pre-preroll on 0126 because of security problems
//movie.prePreroll(0, 1.0f);
movie.preroll(0, 1.0f);
// this has a possibility of running forever..
// should probably happen on the thread as well.
while (movie.maxLoadedTimeInMovie() == 0) {
movie.task(100);
// 0106: tried adding sleep time so this doesn't spin out of control
// works fine but doesn't really help anything
//try {
//Thread.sleep(5);
//} catch (InterruptedException e) { }
}
movie.setRate(1);
fps = ifps;
// register methods
parent.registerDispose(this);
try {
movieEventMethod =
parent.getClass().getMethod("movieEvent",
new Class[] { Movie.class });
} catch (Exception e) {
// no such method, or an error.. which is fine, just ignore
}
// and now, make the magic happen
runner = new Thread(this);
runner.start();
} catch (QTException qte) {
qte.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
|
diff --git a/src/main/java/water/fvec/Frame.java b/src/main/java/water/fvec/Frame.java
index e9cbf1595..992d3df55 100644
--- a/src/main/java/water/fvec/Frame.java
+++ b/src/main/java/water/fvec/Frame.java
@@ -1,779 +1,779 @@
package water.fvec;
import java.io.IOException;
import java.io.InputStream;
import java.util.*;
import water.*;
import water.H2O.H2OCountedCompleter;
import water.exec.Flow;
import water.fvec.Vec.VectorGroup;
/**
* A collection of named Vecs. Essentially an R-like data-frame. Multiple
* Frames can reference the same Vecs. A Frame is a lightweight object, it is
* meant to be cheaply created and discarded for data munging purposes.
* E.g. to exclude a Vec from a computation on a Frame, create a new Frame that
* references all the Vecs but this one.
*/
public class Frame extends Lockable<Frame> {
public String[] _names;
Key[] _keys; // Keys for the vectors
transient Vec[] _vecs;// The Vectors (transient to avoid network traffic)
private transient Vec _col0; // First readable vec; fast access to the VectorGroup's Chunk layout
public Frame( Frame fr ) { this(fr._key,fr._names.clone(), fr.vecs().clone()); _col0 = null; }
public Frame( Vec... vecs ){ this(null,vecs);}
public Frame( String[] names, Vec[] vecs ) { this(null,names,vecs); }
public Frame( Key key, String[] names, Vec[] vecs ) {
super(key);
// assert names==null || names.length == vecs.length : "Number of columns does not match to number of cols' names.";
_names=names;
_vecs=vecs;
_keys = new Key[vecs.length];
for( int i=0; i<vecs.length; i++ ) {
Key k = _keys[i] = vecs[i]._key;
if( DKV.get(k)==null ) // If not already in KV, put it there
DKV.put(k,vecs[i]);
}
Vec v0 = anyVec();
if( v0 == null ) return;
VectorGroup grp = v0.group();
for( int i=0; i<vecs.length; i++ )
assert grp.equals(vecs[i].group()) : "Vector " + vecs[i] + " has different vector group!";
}
public Vec vec(String name){
Vec [] vecs = vecs();
for(int i = 0; i < _names.length; ++i)
if(_names[i].equals(name))return vecs[i];
return null;
}
public Frame subframe(String [] names){
Vec [] vecs = new Vec[names.length];
vecs(); // Preload the vecs
HashMap<String, Integer> map = new HashMap<String, Integer>();
for(int i = 0; i < _names.length; ++i)map.put(_names[i], i);
for(int i = 0; i < names.length; ++i)
if(map.containsKey(names[i])) vecs[i] = _vecs[map.get(names[i])];
else throw new IllegalArgumentException("Missing column called "+names[i]);
return new Frame(names,vecs);
}
public final Vec[] vecs() {
if( _vecs != null ) return _vecs;
// Load all Vec headers; load them all in parallel by spawning F/J tasks.
final Vec [] vecs = new Vec[_keys.length];
Futures fs = new Futures();
for( int i=0; i<_keys.length; i++ ) {
final int ii = i;
final Key k = _keys[i];
H2OCountedCompleter t = new H2OCountedCompleter() {
// We need higher priority here as there is a danger of deadlock in
// case of many calls from MRTask2 at once (e.g. frame with many
// vectors invokes rollup tasks for all vectors in parallel). Should
// probably be done in CPS style in the future
@Override public byte priority(){return H2O.MIN_HI_PRIORITY;}
@Override public void compute2() {
vecs[ii] = DKV.get(k).get();
tryComplete();
}
};
H2O.submitTask(t);
fs.add(t);
}
fs.blockForPending();
return _vecs = vecs;
}
// Force a cache-flush & reload, assuming vec mappings were altered remotely
public final Vec[] reloadVecs() { _vecs=null; return vecs(); }
/** Finds the first column with a matching name. */
public int find( String name ) {
for( int i=0; i<_names.length; i++ )
if( name.equals(_names[i]) )
return i;
return -1;
}
public int find( Vec vec ) {
for( int i=0; i<_vecs.length; i++ )
if( vec.equals(_vecs[i]) )
return i;
return -1;
}
/** Appends a named column, keeping the last Vec as the response */
public void add( String name, Vec vec ) {
assert _vecs.length == 0 || anyVec().group().equals(vec.group());
if( find(name) != -1 ) throw new IllegalArgumentException("Duplicate name '"+name+"' in Frame");
final int len = _names.length;
_names = Arrays.copyOf(_names,len+1);
_vecs = Arrays.copyOf(_vecs ,len+1);
_keys = Arrays.copyOf(_keys ,len+1);
_names[len] = name;
_vecs [len] = vec ;
_keys [len] = vec._key;
}
/** Appends an entire Frame */
public Frame add( Frame fr, String names[] ) {
assert _vecs.length==0 || anyVec().group().equals(fr.anyVec().group());
for( String name : names )
if( find(name) != -1 ) throw new IllegalArgumentException("Duplicate name '"+name+"' in Frame");
final int len0= _names.length;
final int len1= names.length;
final int len = len0+len1;
_names = Arrays.copyOf(_names,len);
_vecs = Arrays.copyOf(_vecs ,len);
_keys = Arrays.copyOf(_keys ,len);
System.arraycopy( names,0,_names,len0,len1);
System.arraycopy(fr._vecs ,0,_vecs ,len0,len1);
System.arraycopy(fr._keys ,0,_keys ,len0,len1);
return this;
}
public Frame add( Frame fr, boolean rename ) {
if( !rename ) return add(fr,fr._names);
String names[] = new String[fr._names.length];
for( int i=0; i<names.length; i++ ) {
String name = fr._names[i];
int cnt=0;
while( find(name) != -1 )
name = fr._names[i]+(cnt++);
names[i] = name;
}
return add(fr,names);
}
/** Removes the first column with a matching name. */
public Vec remove( String name ) { return remove(find(name)); }
/** Removes a numbered column. */
public Vec [] remove( int [] idxs ) {
for(int i :idxs)if(i < 0 || i > _vecs.length)
throw new ArrayIndexOutOfBoundsException();
Arrays.sort(idxs);
Vec [] res = new Vec[idxs.length];
Vec [] rem = new Vec[_vecs.length-idxs.length];
String [] names = new String[rem.length];
Key [] keys = new Key [rem.length];
int j = 0;
int k = 0;
int l = 0;
for(int i = 0; i < _vecs.length; ++i)
if(j < idxs.length && i == idxs[j]){
++j;
res[k++] = _vecs[i];
} else {
rem [l] = _vecs [i];
names[l] = _names[i];
keys [l] = _keys [i];
++l;
}
_vecs = rem;
_names = names;
_keys = keys;
assert l == rem.length && k == idxs.length;
return res;
}
/** Removes a numbered column. */
public Vec remove( int idx ) {
int len = _names.length;
if( idx < 0 || idx >= len ) return null;
Vec v = vecs()[idx];
System.arraycopy(_names,idx+1,_names,idx,len-idx-1);
System.arraycopy(_vecs ,idx+1,_vecs ,idx,len-idx-1);
System.arraycopy(_keys ,idx+1,_keys ,idx,len-idx-1);
_names = Arrays.copyOf(_names,len-1);
_vecs = Arrays.copyOf(_vecs ,len-1);
_keys = Arrays.copyOf(_keys ,len-1);
if( v == _col0 ) _col0 = null;
return v;
}
/**
* Remove given interval of columns from frame. Motivated by R intervals.
* @param startIdx - start index of column (inclusive)
* @param endIdx - end index of column (exclusive)
* @return an array of remove columns
*/
public Vec[] remove(int startIdx, int endIdx) {
int len = _names.length;
int nlen = len - (endIdx-startIdx);
String[] names = new String[nlen];
Key[] keys = new Key[nlen];
Vec[] vecs = new Vec[nlen];
if (startIdx > 0) {
System.arraycopy(_names, 0, names, 0, startIdx);
System.arraycopy(_vecs, 0, vecs, 0, startIdx);
System.arraycopy(_keys, 0, keys, 0, startIdx);
}
nlen -= startIdx;
if (endIdx < _names.length+1) {
System.arraycopy(_names, endIdx, names, startIdx, nlen);
System.arraycopy(_vecs, endIdx, vecs, startIdx, nlen);
System.arraycopy(_keys, endIdx, keys, startIdx, nlen);
}
Vec[] vec = Arrays.copyOfRange(vecs(),startIdx,endIdx);
_names = names;
_vecs = vec;
_keys = keys;
_col0 = null;
return vec;
}
public Vec replace(int col, Vec nv) {
assert col < _names.length;
Vec rv = vecs()[col];
assert rv.group().equals(nv.group());
_vecs[col] = nv;
_keys[col] = nv._key;
if( DKV.get(nv._key)==null ) // If not already in KV, put it there
DKV.put(nv._key, nv);
return rv;
}
public Frame extractFrame(int startIdx, int endIdx) {
Frame f = subframe(startIdx, endIdx);
remove(startIdx, endIdx);
return f;
}
/** Create a subframe from given interval of columns.
*
* @param startIdx index of first column (inclusive)
* @param endIdx index of the last column (exclusive)
* @return a new frame containing specified interval of columns
*/
public Frame subframe(int startIdx, int endIdx) {
Frame result = new Frame(Arrays.copyOfRange(_names,startIdx,endIdx),Arrays.copyOfRange(vecs(),startIdx,endIdx));
return result;
}
public final String[] names() { return _names; }
public int numCols() { return vecs().length; }
public long numRows() { return anyVec()==null ? 0 : anyVec().length(); }
// Number of columns when categoricals expanded.
// Note: One level is dropped in each categorical col.
public int numExpCols() {
int ncols = 0;
for(int i = 0; i < vecs().length; i++)
ncols += vecs()[i].domain() == null ? 1 : (vecs()[i].domain().length - 1);
return ncols;
}
/** All the domains for enum columns; null for non-enum columns. */
public String[][] domains() {
String ds[][] = new String[vecs().length][];
for( int i=0; i<vecs().length; i++ )
ds[i] = vecs()[i].domain();
return ds;
}
private String[][] domains(int [] cols){
Vec [] vecs = vecs();
String [][] res = new String[cols.length][];
for(int i = 0; i < cols.length; ++i)
res[i] = vecs[cols[i]]._domain;
return res;
}
private String [] names(int [] cols){
if(_names == null)return null;
String [] res = new String[cols.length];
for(int i = 0; i < cols.length; ++i)
res[i] = _names[cols[i]];
return res;
}
public Vec lastVec() {
final Vec [] vecs = vecs();
return vecs[vecs.length-1];
}
/** Returns the first readable vector. */
public Vec anyVec() {
if( _col0 != null ) return _col0;
for( Vec v : vecs() )
if( v.readable() )
return (_col0 = v);
return null;
}
/* Returns the only Vector, or tosses IAE */
public final Vec theVec(String err) {
if( _keys.length != 1 ) throw new IllegalArgumentException(err);
if( _vecs == null ) _vecs = new Vec[]{_col0 = DKV.get(_keys[0]).get() };
return _vecs[0];
}
/** Check that the vectors are all compatible. All Vecs have their content
* sharded using same number of rows per chunk. */
public void checkCompatible( ) {
Vec v0 = anyVec();
int nchunks = v0.nChunks();
for( Vec vec : vecs() ) {
if( vec instanceof AppendableVec ) continue; // New Vectors are endlessly compatible
if( vec.nChunks() != nchunks )
throw new IllegalArgumentException("Vectors different numbers of chunks, "+nchunks+" and "+vec.nChunks());
}
// Also check each chunk has same rows
for( int i=0; i<nchunks; i++ ) {
long es = v0.chunk2StartElem(i);
for( Vec vec : vecs() )
if( !(vec instanceof AppendableVec) && vec.chunk2StartElem(i) != es )
throw new IllegalArgumentException("Vector chunks different numbers of rows, "+es+" and "+vec.chunk2StartElem(i));
}
}
public void closeAppendables() {closeAppendables(new Futures()).blockForPending(); }
// Close all AppendableVec
public Futures closeAppendables(Futures fs) {
_col0 = null; // Reset cache
int len = vecs().length;
for( int i=0; i<len; i++ ) {
Vec v = _vecs[i];
if( v instanceof AppendableVec )
DKV.put(_keys[i],_vecs[i] = ((AppendableVec)v).close(fs),fs);
}
return fs;
}
/** Actually remove/delete all Vecs from memory, not just from the Frame. */
@Override public Futures delete_impl(Futures fs) {
for( Key k : _keys ) UKV.remove(k,fs);
_names = new String[0];
_vecs = new Vec[0];
_keys = new Key[0];
return fs;
}
@Override public String errStr() { return "Dataset"; }
public long byteSize() {
long sum=0;
for( int i=0; i<vecs().length; i++ )
sum += _vecs[i].byteSize();
return sum;
}
@Override public String toString() {
// Across
Vec vecs[] = vecs();
if( vecs.length==0 ) return "{}";
String s="{"+_names[0];
long bs=vecs[0].byteSize();
for( int i=1; i<vecs.length; i++ ) {
s += ","+_names[i];
bs+= vecs[i].byteSize();
}
s += "}, "+PrettyPrint.bytes(bs)+"\n";
// Down
Vec v0 = anyVec();
if( v0 == null ) return s;
int nc = v0.nChunks();
s += "Chunk starts: {";
for( int i=0; i<nc; i++ ) s += v0.elem2BV(i)._start+",";
s += "}";
return s;
}
// Print a row with headers inlined
private String toStr( long idx, int col ) {
return _names[col]+"="+(_vecs[col].isNA(idx) ? "NA" : _vecs[col].at(idx));
}
public String toString( long idx ) {
String s="{"+toStr(idx,0);
for( int i=1; i<_names.length; i++ )
s += ","+toStr(idx,i);
return s+"}";
}
// Print fixed-width row & fixed-width headers (more compressed print
// format). Returns the column formats.
public String[] toStringHdr( StringBuilder sb ) {
String[] fs = new String[numCols()];
for( int c=0; c<fs.length; c++ ) {
String n = (c < _names.length) ? _names[c] : ("C"+c);
if( numRows()==0 ) { sb.append(n).append(' '); continue; }
int w=0;
if( _vecs[c].isEnum() ) {
String ss[] = _vecs[c]._domain;
for( int i=0; i<ss.length; i++ )
w = Math.max(w,ss[i].length());
w = Math.min(w,10);
fs[c] = "%"+w+"."+w+"s";
} else {
Chunk C = _vecs[c].elem2BV(0); // 1st Chunk
String f = fs[c] = C.pformat(); // Printable width
for( int x=0; x<f.length(); x++ )// Get printable width from format
if( Character.isDigit(f.charAt(x)) ) w = w*10+(f.charAt(x)-'0');
else if( w>0 ) break;
if( f.charAt(1)==' ' ) w++; // Leading blank is not in print-width
}
int len = sb.length();
if( n.length() <= w ) { // Short name, big digits
sb.append(n);
for( int i=n.length(); i<w; i++ ) sb.append(' ');
} else if( w==1 ) { // First char only
sb.append(n.charAt(0));
} else if( w==2 ) { // First 2 chars only
sb.append(n.charAt(0)).append(n.charAt(1));
} else { // First char dot lastchars; e.g. Compress "Interval" to "I.val"
sb.append(n.charAt(0)).append('.');
for( int i=n.length()-(w-2); i<n.length(); i++ )
sb.append(n.charAt(i));
}
assert len+w==sb.length();
sb.append(' '); // Column seperator
}
sb.append('\n');
return fs;
}
public StringBuilder toString( StringBuilder sb, String[] fs, long idx ) {
Vec vecs[] = vecs();
for( int c=0; c<fs.length; c++ ) {
Vec vec = vecs[c];
if( vec.isEnum() ) {
String s = "----------";
if( !vec.isNA(idx) ) {
int x = (int)vec.at8(idx);
if( x >= 0 && x < vec._domain.length ) s = vec._domain[x];
}
sb.append(String.format(fs[c],s));
} else if( vec.isInt() ) {
if( vec.isNA(idx) ) {
Chunk C = vec.elem2BV(0); // 1st Chunk
int len = C.pformat_len0(); // Printable width
for( int i=0; i<len; i++ ) sb.append('-');
} else {
try {
sb.append(String.format(fs[c],vec.at8(idx)));
} catch( IllegalFormatException ife ) {
System.out.println("Format: "+fs[c]+" col="+c+" not for ints");
ife.printStackTrace();
}
}
} else {
sb.append(String.format(fs[c],vec.at (idx)));
if( vec.isNA(idx) ) sb.append(' ');
}
sb.append(' '); // Column seperator
}
sb.append('\n');
return sb;
}
public String toStringAll() {
StringBuilder sb = new StringBuilder();
String[] fs = toStringHdr(sb);
for( int i=0; i<numRows(); i++ )
toString(sb,fs,i);
return sb.toString();
}
// Return the entire Frame as a CSV stream
public InputStream toCSV(boolean headers) {
return new CSVStream(headers);
}
private class CSVStream extends InputStream {
byte[] _line;
int _position;
long _row;
CSVStream(boolean headers) {
StringBuilder sb = new StringBuilder();
if( headers ) {
sb.append('"' + _names[0] + '"');
for(int i = 1; i < _vecs.length; i++)
sb.append(',').append('"' + _names[i] + '"');
sb.append('\n');
}
_line = sb.toString().getBytes();
}
@Override public int available() throws IOException {
if(_position == _line.length) {
if(_row == numRows())
return 0;
StringBuilder sb = new StringBuilder();
for( int i = 0; i < _vecs.length; i++ ) {
if(i > 0) sb.append(',');
if(!_vecs[i].isNA(_row)) {
if(_vecs[i].isEnum()) sb.append('"' + _vecs[i]._domain[(int) _vecs[i].at8(_row)] + '"');
else if(_vecs[i].isInt()) sb.append(_vecs[i].at8(_row));
else sb.append(_vecs[i].at(_row));
}
}
sb.append('\n');
_line = sb.toString().getBytes();
_position = 0;
_row++;
}
return _line.length - _position;
}
@Override public void close() throws IOException {
super.close();
_line = null;
}
@Override public int read() throws IOException {
return available() == 0 ? -1 : _line[_position++];
}
@Override public int read(byte[] b, int off, int len) throws IOException {
int n = available();
if(n > 0) {
n = Math.min(n, len);
System.arraycopy(_line, _position, b, off, n);
_position += n;
}
return n;
}
}
// --------------------------------------------------------------------------
// In support of R, a generic Deep Copy & Slice.
// Semantics are a little odd, to match R's.
// Each dimension spec can be:
// null - all of them
// a sorted list of negative numbers (no dups) - all BUT these
// an unordered list of positive - just these, allowing dups
// The numbering is 1-based; zero's are not allowed in the lists, nor are out-of-range.
final int MAX_EQ2_COLS = 100000; // FIXME. Put this in a better spot.
public Frame deepSlice( Object orows, Object ocols ) {
// ocols is either a long[] or a Frame-of-1-Vec
long[] cols;
if( ocols == null ) {
cols = (long[])ocols;
assert cols == null;
}
else {
if (ocols instanceof long[]) {
cols = (long[])ocols;
}
else if (ocols instanceof Frame) {
Frame fr = (Frame) ocols;
if (fr.numCols() != 1) {
throw new IllegalArgumentException("Columns Frame must have only one column (actually has " + fr.numCols() + " columns)");
}
long n = fr.anyVec().length();
if (n > MAX_EQ2_COLS) {
throw new IllegalArgumentException("Too many requested columns (requested " + n +", max " + MAX_EQ2_COLS + ")");
}
cols = new long[(int)n];
Vec v = fr._vecs[0];
for (long i = 0; i < v.length(); i++) {
cols[(int)i] = v.at8(i);
}
}
else {
throw new IllegalArgumentException("Columns is specified by an unsupported data type (" + ocols.getClass().getName() + ")");
}
}
// Since cols is probably short convert to a positive list.
int c2[] = null;
if( cols==null ) {
c2 = new int[numCols()];
for( int i=0; i<c2.length; i++ ) c2[i]=i;
} else if( cols.length==0 ) {
c2 = new int[0];
} else if( cols[0] > 0 ) {
c2 = new int[cols.length];
for( int i=0; i<cols.length; i++ )
c2[i] = (int)cols[i]-1; // Convert 1-based cols to zero-based
} else {
c2 = new int[numCols()-cols.length];
int j=0;
for( int i=0; i<numCols(); i++ ) {
if( j >= cols.length || i < (-cols[j]-1) ) c2[i-j] = i;
else j++;
}
}
for( int i=0; i<c2.length; i++ )
if( c2[i] >= numCols() )
- throw new IllegalArgumentException("Trying to select column "+c2[i]+" but only "+numCols()+" present.");
+ throw new IllegalArgumentException("Trying to select column "+(c2[i]+1)+" but only "+numCols()+" present.");
if( c2.length==0 )
throw new IllegalArgumentException("No columns selected (did you try to select column 0 instead of column 1?)");
// Do Da Slice
// orows is either a long[] or a Vec
if (orows == null)
return new DeepSlice((long[])orows,c2).doAll(c2.length,this).outputFrame(names(c2),domains(c2));
else if (orows instanceof long[]) {
final long CHK_ROWS=1000000;
long[] rows = (long[])orows;
if( rows.length==0 || rows[0] < 0 )
return new DeepSlice(rows,c2).doAll(c2.length, this).outputFrame(names(c2), domains(c2));
// Vec'ize the index array
Futures fs = new Futures();
AppendableVec av = new AppendableVec("rownames");
int r = 0;
int c = 0;
while (r < rows.length) {
NewChunk nc = new NewChunk(av, c);
long end = Math.min(r+CHK_ROWS, rows.length);
for (; r < end; r++) {
nc.addNum(rows[r]);
}
nc.close(c++, fs);
}
Vec c0 = av.close(fs); // c0 is the row index vec
fs.blockForPending();
Frame fr2 = new Slice(c2, this).doAll(c2.length,new Frame(new String[]{"rownames"}, new Vec[]{c0}))
.outputFrame(names(c2), domains(c2));
UKV.remove(c0._key); // Remove hidden vector
return fr2;
}
Frame frows = (Frame)orows;
Vec vrows = frows.anyVec();
// It's a compatible Vec; use it as boolean selector.
// Build column names for the result.
Vec [] vecs = new Vec[c2.length+1];
String [] names = new String[c2.length+1];
for(int i = 0; i < c2.length; ++i){
vecs[i] = _vecs[c2[i]];
names[i] = _names[c2[i]];
}
vecs[c2.length] = vrows;
names[c2.length] = "predicate";
return new DeepSelect().doAll(c2.length,new Frame(names,vecs)).outputFrame(names(c2),domains(c2));
}
// Slice and return in the form of new chunks.
private static class Slice extends MRTask2<Slice> {
final Frame _base; // the base frame to slice from
final int[] _cols;
Slice(int[] cols, Frame base) { _cols = cols; _base = base; }
@Override public void map(Chunk[] ix, NewChunk[] ncs) {
final Vec[] vecs = new Vec[_cols.length];
final Vec anyv = _base.anyVec();
final long nrow = anyv.length();
long r = ix[0].at80(0);
int last_ci = anyv.elem2ChunkIdx(r<nrow?r:0); // memoize the last chunk index
long last_c0 = anyv._espc[last_ci]; // ... last chunk start
long last_c1 = anyv._espc[last_ci + 1]; // ... last chunk end
Chunk[] last_cs = new Chunk[vecs.length]; // ... last chunks
for (int c = 0; c < _cols.length; c++) {
vecs[c] = _base.vecs()[_cols[c]];
last_cs[c] = vecs[c].elem2BV(last_ci);
}
for (int i = 0; i < ix[0]._len; i++) {
// select one row
r = ix[0].at80(i) - 1; // next row to select
if (r < 0) continue;
if (r >= nrow) {
for (int c = 0; c < vecs.length; c++) ncs[c].addNum(Double.NaN);
} else {
if (r < last_c0 || r >= last_c1) {
last_ci = anyv.elem2ChunkIdx(r);
last_c0 = anyv._espc[last_ci];
last_c1 = anyv._espc[last_ci + 1];
for (int c = 0; c < vecs.length; c++)
last_cs[c] = vecs[c].elem2BV(last_ci);
}
for (int c = 0; c < vecs.length; c++)
ncs[c].addNum(last_cs[c].at(r));
}
}
}
}
// Bulk (expensive) copy from 2nd cols into 1st cols.
// Sliced by the given cols & rows
private static class DeepSlice extends MRTask2<DeepSlice> {
final int _cols[];
final long _rows[];
boolean _ex = true;
DeepSlice( long rows[], int cols[]) { _cols=cols; _rows=rows;}
@Override public void map( Chunk chks[], NewChunk nchks[] ) {
long rstart = chks[0]._start;
int rlen = chks[0]._len; // Total row count
int rx = 0; // Which row to in/ex-clude
int rlo = 0; // Lo/Hi for this block of rows
int rhi = rlen;
while( true ) { // Still got rows to include?
if( _rows != null ) { // Got a row selector?
if( rx >= _rows.length ) break; // All done with row selections
long r = _rows[rx++]-1;// Next row selector
if( r < 0 ) { // Row exclusion
if(rx > 0 && _rows[rx - 1] < _rows[rx]) throw H2O.unimpl();
long er = Math.abs(r) - 2;
if ( er < rstart) continue;
//scoop up all of the rows before the first exclusion
if (rx == 1 && ( (int)(er + 1 - rstart)) > 0 && _ex) {
rlo = (int)rstart;
rhi = (int)(er - rstart);
_ex = false;
rx--;
} else {
rlo = (int)(er + 1 - rstart);
//TODO: handle jumbled row indices ( e.g. -c(1,5,3) )
while(rx < _rows.length && (_rows[rx] + 1 == _rows[rx - 1] && rlo < rlen)) {
if(rx < _rows.length - 1 && _rows[rx] < _rows[rx + 1]) throw H2O.unimpl();
rx++; rlo++; //Exclude consecutive rows
}
rhi = rx >= _rows.length ? rlen : (int)Math.abs(_rows[rx] - 1) - 2;
if(rx < _rows.length - 1 && _rows[rx] < _rows[rx + 1]) throw H2O.unimpl();
}
} else { // Positive row list?
if( r < rstart ) continue;
rlo = (int)(r-rstart);
rhi = rlo+1; // Stop at the next row
while( rx < _rows.length && (_rows[rx]-1-rstart)==rhi && rhi < rlen ) {
rx++; rhi++; // Grab sequential rows
}
}
}
// Process this next set of rows
// For all cols in the new set
for( int i=0; i<_cols.length; i++ ) {
Chunk oc = chks[_cols[i]];
NewChunk nc = nchks[ i ];
if( oc._vec.isInt() ) { // Slice on integer columns
for( int j=rlo; j<rhi; j++ )
if( oc.isNA0(j) ) nc.addNA();
else nc.addNum(oc.at80(j),0);
} else { // Slice on double columns
for( int j=rlo; j<rhi; j++ )
nc.addNum(oc.at0(j));
}
}
rlo=rhi;
if( _rows==null ) break;
}
}
}
private static class DeepSelect extends MRTask2<DeepSelect> {
@Override public void map( Chunk chks[], NewChunk nchks[] ) {
Chunk pred = chks[chks.length-1];
for(int i = 0; i < pred._len; ++i){
if(pred.at0(i) != 0)
for(int j = 0; j < chks.length-1; ++j)
nchks[j].addNum(chks[j].at0(i));
}
}
}
// ------------------------------------------------------------------------------
public
<Y extends Flow.PerRow<Y>> // Type parameter
Flow.FlowPerRow<Y> // Return type of with()
with // The method name
( Flow.PerRow<Y> pr ) // Arguments for with()
{
return new Flow.FlowPerRow<Y>(pr,new Flow.FlowFrame(this));
}
public Flow.FlowFilter with( Flow.Filter fr ) {
return new Flow.FlowFilter(fr,new Flow.FlowFrame(this));
}
public Flow.FlowGroupBy with( Flow.GroupBy fr ) {
return new Flow.FlowGroupBy(fr,new Flow.FlowFrame(this));
}
}
| true | true | public Frame deepSlice( Object orows, Object ocols ) {
// ocols is either a long[] or a Frame-of-1-Vec
long[] cols;
if( ocols == null ) {
cols = (long[])ocols;
assert cols == null;
}
else {
if (ocols instanceof long[]) {
cols = (long[])ocols;
}
else if (ocols instanceof Frame) {
Frame fr = (Frame) ocols;
if (fr.numCols() != 1) {
throw new IllegalArgumentException("Columns Frame must have only one column (actually has " + fr.numCols() + " columns)");
}
long n = fr.anyVec().length();
if (n > MAX_EQ2_COLS) {
throw new IllegalArgumentException("Too many requested columns (requested " + n +", max " + MAX_EQ2_COLS + ")");
}
cols = new long[(int)n];
Vec v = fr._vecs[0];
for (long i = 0; i < v.length(); i++) {
cols[(int)i] = v.at8(i);
}
}
else {
throw new IllegalArgumentException("Columns is specified by an unsupported data type (" + ocols.getClass().getName() + ")");
}
}
// Since cols is probably short convert to a positive list.
int c2[] = null;
if( cols==null ) {
c2 = new int[numCols()];
for( int i=0; i<c2.length; i++ ) c2[i]=i;
} else if( cols.length==0 ) {
c2 = new int[0];
} else if( cols[0] > 0 ) {
c2 = new int[cols.length];
for( int i=0; i<cols.length; i++ )
c2[i] = (int)cols[i]-1; // Convert 1-based cols to zero-based
} else {
c2 = new int[numCols()-cols.length];
int j=0;
for( int i=0; i<numCols(); i++ ) {
if( j >= cols.length || i < (-cols[j]-1) ) c2[i-j] = i;
else j++;
}
}
for( int i=0; i<c2.length; i++ )
if( c2[i] >= numCols() )
throw new IllegalArgumentException("Trying to select column "+c2[i]+" but only "+numCols()+" present.");
if( c2.length==0 )
throw new IllegalArgumentException("No columns selected (did you try to select column 0 instead of column 1?)");
// Do Da Slice
// orows is either a long[] or a Vec
if (orows == null)
return new DeepSlice((long[])orows,c2).doAll(c2.length,this).outputFrame(names(c2),domains(c2));
else if (orows instanceof long[]) {
final long CHK_ROWS=1000000;
long[] rows = (long[])orows;
if( rows.length==0 || rows[0] < 0 )
return new DeepSlice(rows,c2).doAll(c2.length, this).outputFrame(names(c2), domains(c2));
// Vec'ize the index array
Futures fs = new Futures();
AppendableVec av = new AppendableVec("rownames");
int r = 0;
int c = 0;
while (r < rows.length) {
NewChunk nc = new NewChunk(av, c);
long end = Math.min(r+CHK_ROWS, rows.length);
for (; r < end; r++) {
nc.addNum(rows[r]);
}
nc.close(c++, fs);
}
Vec c0 = av.close(fs); // c0 is the row index vec
fs.blockForPending();
Frame fr2 = new Slice(c2, this).doAll(c2.length,new Frame(new String[]{"rownames"}, new Vec[]{c0}))
.outputFrame(names(c2), domains(c2));
UKV.remove(c0._key); // Remove hidden vector
return fr2;
}
Frame frows = (Frame)orows;
Vec vrows = frows.anyVec();
// It's a compatible Vec; use it as boolean selector.
// Build column names for the result.
Vec [] vecs = new Vec[c2.length+1];
String [] names = new String[c2.length+1];
for(int i = 0; i < c2.length; ++i){
vecs[i] = _vecs[c2[i]];
names[i] = _names[c2[i]];
}
vecs[c2.length] = vrows;
names[c2.length] = "predicate";
return new DeepSelect().doAll(c2.length,new Frame(names,vecs)).outputFrame(names(c2),domains(c2));
}
| public Frame deepSlice( Object orows, Object ocols ) {
// ocols is either a long[] or a Frame-of-1-Vec
long[] cols;
if( ocols == null ) {
cols = (long[])ocols;
assert cols == null;
}
else {
if (ocols instanceof long[]) {
cols = (long[])ocols;
}
else if (ocols instanceof Frame) {
Frame fr = (Frame) ocols;
if (fr.numCols() != 1) {
throw new IllegalArgumentException("Columns Frame must have only one column (actually has " + fr.numCols() + " columns)");
}
long n = fr.anyVec().length();
if (n > MAX_EQ2_COLS) {
throw new IllegalArgumentException("Too many requested columns (requested " + n +", max " + MAX_EQ2_COLS + ")");
}
cols = new long[(int)n];
Vec v = fr._vecs[0];
for (long i = 0; i < v.length(); i++) {
cols[(int)i] = v.at8(i);
}
}
else {
throw new IllegalArgumentException("Columns is specified by an unsupported data type (" + ocols.getClass().getName() + ")");
}
}
// Since cols is probably short convert to a positive list.
int c2[] = null;
if( cols==null ) {
c2 = new int[numCols()];
for( int i=0; i<c2.length; i++ ) c2[i]=i;
} else if( cols.length==0 ) {
c2 = new int[0];
} else if( cols[0] > 0 ) {
c2 = new int[cols.length];
for( int i=0; i<cols.length; i++ )
c2[i] = (int)cols[i]-1; // Convert 1-based cols to zero-based
} else {
c2 = new int[numCols()-cols.length];
int j=0;
for( int i=0; i<numCols(); i++ ) {
if( j >= cols.length || i < (-cols[j]-1) ) c2[i-j] = i;
else j++;
}
}
for( int i=0; i<c2.length; i++ )
if( c2[i] >= numCols() )
throw new IllegalArgumentException("Trying to select column "+(c2[i]+1)+" but only "+numCols()+" present.");
if( c2.length==0 )
throw new IllegalArgumentException("No columns selected (did you try to select column 0 instead of column 1?)");
// Do Da Slice
// orows is either a long[] or a Vec
if (orows == null)
return new DeepSlice((long[])orows,c2).doAll(c2.length,this).outputFrame(names(c2),domains(c2));
else if (orows instanceof long[]) {
final long CHK_ROWS=1000000;
long[] rows = (long[])orows;
if( rows.length==0 || rows[0] < 0 )
return new DeepSlice(rows,c2).doAll(c2.length, this).outputFrame(names(c2), domains(c2));
// Vec'ize the index array
Futures fs = new Futures();
AppendableVec av = new AppendableVec("rownames");
int r = 0;
int c = 0;
while (r < rows.length) {
NewChunk nc = new NewChunk(av, c);
long end = Math.min(r+CHK_ROWS, rows.length);
for (; r < end; r++) {
nc.addNum(rows[r]);
}
nc.close(c++, fs);
}
Vec c0 = av.close(fs); // c0 is the row index vec
fs.blockForPending();
Frame fr2 = new Slice(c2, this).doAll(c2.length,new Frame(new String[]{"rownames"}, new Vec[]{c0}))
.outputFrame(names(c2), domains(c2));
UKV.remove(c0._key); // Remove hidden vector
return fr2;
}
Frame frows = (Frame)orows;
Vec vrows = frows.anyVec();
// It's a compatible Vec; use it as boolean selector.
// Build column names for the result.
Vec [] vecs = new Vec[c2.length+1];
String [] names = new String[c2.length+1];
for(int i = 0; i < c2.length; ++i){
vecs[i] = _vecs[c2[i]];
names[i] = _names[c2[i]];
}
vecs[c2.length] = vrows;
names[c2.length] = "predicate";
return new DeepSelect().doAll(c2.length,new Frame(names,vecs)).outputFrame(names(c2),domains(c2));
}
|
diff --git a/core/src/main/java/org/mule/galaxy/impl/link/LinkDaoImpl.java b/core/src/main/java/org/mule/galaxy/impl/link/LinkDaoImpl.java
index e939cf10..28274bd2 100644
--- a/core/src/main/java/org/mule/galaxy/impl/link/LinkDaoImpl.java
+++ b/core/src/main/java/org/mule/galaxy/impl/link/LinkDaoImpl.java
@@ -1,461 +1,461 @@
package org.mule.galaxy.impl.link;
import static org.mule.galaxy.event.DefaultEvents.ENTRY_CREATED;
import static org.mule.galaxy.event.DefaultEvents.ENTRY_DELETED;
import static org.mule.galaxy.event.DefaultEvents.ENTRY_MOVED;
import static org.mule.galaxy.event.DefaultEvents.ENTRY_VERSION_DELETED;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import javax.jcr.Node;
import javax.jcr.NodeIterator;
import javax.jcr.RepositoryException;
import javax.jcr.Session;
import javax.jcr.query.Query;
import javax.jcr.query.QueryManager;
import javax.jcr.query.QueryResult;
import org.mule.galaxy.ArtifactVersion;
import org.mule.galaxy.Entry;
import org.mule.galaxy.EntryVersion;
import org.mule.galaxy.Item;
import org.mule.galaxy.Link;
import org.mule.galaxy.NotFoundException;
import org.mule.galaxy.Registry;
import org.mule.galaxy.RegistryException;
import org.mule.galaxy.event.EntryCreatedEvent;
import org.mule.galaxy.event.EntryDeletedEvent;
import org.mule.galaxy.event.EntryMovedEvent;
import org.mule.galaxy.event.EntryVersionDeletedEvent;
import org.mule.galaxy.event.annotation.BindToEvents;
import org.mule.galaxy.event.annotation.OnEvent;
import org.mule.galaxy.impl.jcr.JcrUtil;
import org.mule.galaxy.impl.jcr.onm.AbstractReflectionDao;
import org.mule.galaxy.query.OpRestriction;
import org.mule.galaxy.query.QueryException;
import org.mule.galaxy.query.SearchResults;
import org.mule.galaxy.security.AccessException;
import org.mule.galaxy.util.SecurityUtils;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springmodules.jcr.JcrCallback;
@BindToEvents({ENTRY_CREATED, ENTRY_MOVED, ENTRY_DELETED, ENTRY_VERSION_DELETED})
public class LinkDaoImpl extends AbstractReflectionDao<Link> implements LinkDao, ApplicationContextAware {
private Registry registry;
private ApplicationContext context;
public LinkDaoImpl() throws Exception {
super(Link.class, "links", true);
}
/**
* Checks for 1) Links which were not resolved and see if this new entry matches them
* 2) Links which are associated with this ID and tries to resolve them
*
* @param id
* @param session
* @throws IOException
* @throws RepositoryException
*/
protected void addLinks(String id, Session session) throws IOException, RepositoryException {
try {
// First, see if this item which was moved matches any outstanding unmatched links
Item item = getRegistry().getItemById(id);
List<String> versionIds = getVersionIds(id);
StringBuilder stmt = new StringBuilder();
stmt.append("//").append(rootNode)
.append("/*[not(@linkedTo) and jcr:like(@linkedToPath, '%")
.append(item.getName())
.append("%')]");
QueryManager qm = getQueryManager(session);
Query q = qm.createQuery(stmt.toString(), Query.XPATH);
QueryResult qr = q.execute();
for (NodeIterator nodes = qr.getNodes(); nodes.hasNext();) {
Node node = nodes.nextNode();
Item linkItem = getRegistry().getItemById(JcrUtil.getStringOrNull(node, "item"));
String path = JcrUtil.getStringOrNull(node, "linkedToPath");
Item resolve = registry.resolve(linkItem, path);
if (resolve != null) {
node.setProperty("linkedTo", resolve.getId());
}
}
// Now try to resolve links which are associated with this item
stmt = new StringBuilder();
stmt.append("//").append(rootNode)
.append("/*[not(@linkedTo) and (@item = '")
.append(id);
// Find the children of this node....
for (String childId : versionIds) {
stmt.append("' or @item = '")
.append(childId);
}
stmt.append("')]");
q = qm.createQuery(stmt.toString(), Query.XPATH);
for (NodeIterator nodes = q.execute().getNodes(); nodes.hasNext();) {
Node node = nodes.nextNode();
Item linkItem = getRegistry().getItemById(JcrUtil.getStringOrNull(node, "item"));
String path = JcrUtil.getStringOrNull(node, "linkedToPath");
Item resolve = registry.resolve(linkItem, path);
if (resolve != null) {
node.setProperty("linkedTo", resolve.getId());
}
}
} catch (NotFoundException e) {
- throw new RuntimeException(e);
+ // this was deleted before we could tie together links... forget about it
} catch (RegistryException e) {
throw new RuntimeException(e);
} catch (AccessException e) {
throw new RuntimeException(e);
}
}
protected void deleteAssociatedLinks(String id, Session session) throws IOException, RepositoryException {
StringBuilder stmt = new StringBuilder();
stmt.append("//").append(rootNode)
.append("/*[@item = '")
.append(id)
.append("' or linkedTo = '")
.append(id)
.append("']");
QueryManager qm = getQueryManager(session);
Query q = qm.createQuery(stmt.toString(), Query.XPATH);
QueryResult qr = q.execute();
for (NodeIterator nodes = qr.getNodes(); nodes.hasNext();) {
Node node = nodes.nextNode();
Boolean auto = JcrUtil.getBooleanOrNull(node, "autoDetected");
String linkedTo = JcrUtil.getStringOrNull(node, "linkedTo");
if (auto != null && auto && id.equals(linkedTo)) {
// we may want to auto resolve this again in the future
node.setProperty("linkedTo", (String) null);
} else {
node.remove();
}
}
}
protected void clearDetectedLinks(final String id, Session session) throws IOException, RepositoryException {
final StringBuilder stmt = new StringBuilder();
stmt.append("//").append(rootNode)
.append("/*[@item = '")
.append(id)
.append("' or linkedTo = '")
.append(id);
// Find the children of this node....
for (String childId : getVersionIds(id)) {
stmt.append("' or @item = '")
.append(childId)
.append("' or linkedTo = '")
.append(childId);
}
stmt.append("']");
QueryManager qm = getQueryManager(session);
Query q = qm.createQuery(stmt.toString(), Query.XPATH);
QueryResult qr = q.execute();
for (NodeIterator nodes = qr.getNodes(); nodes.hasNext();) {
Node node = nodes.nextNode();
Boolean auto = JcrUtil.getBooleanOrNull(node, "autoDetected");
if (auto != null && auto) {
// we may want to auto resolve this again in the future
node.setProperty("linkedTo", (String) null);
}
}
}
private List<String> getVersionIds(final String id) {
final List<String> versionIds = new ArrayList<String>();
try {
Item item = registry.getItemById(id);
if (item instanceof Entry) {
for (EntryVersion ev : ((Entry) item).getVersions()) {
versionIds.add(ev.getId());
}
}
} catch (NotFoundException e) {
throw new RuntimeException(e);
} catch (RegistryException e) {
throw new RuntimeException(e);
} catch (AccessException e) {
throw new RuntimeException(e);
}
return versionIds;
}
public List<Link> getReciprocalLinks(Item item, final String property) {
StringBuilder q = new StringBuilder();
String path;
String name;
if (item instanceof EntryVersion) {
EntryVersion ev = (EntryVersion) item;
path = item.getParent().getPath() + "?version=" + ev.getVersionLabel();
name = item.getParent().getName() + "?version=" + ev.getVersionLabel();
} else {
path = item.getPath();
name = item.getName();
}
q.append("//").append(rootNode).append("/*[(@")
.append("linkedToPath = '").append(name).append("' or @linkedToPath = '")
.append(path).append("' or @linkedTo = '").append(item.getId());
q.append("') and property = '").append(property);
q.append("']");
return (List<Link>) doQuery(q.toString());
}
public List<Link> getLinks(final Item item, final String property) {
StringBuilder q = new StringBuilder();
q.append("//").append(rootNode)
.append("/*[@item = '")
.append(item.getId())
.append("' and property = '")
.append(property)
.append("']");
return (List<Link>) doQuery(q.toString());
}
public void deleteLinks(final Item item, final String property) {
execute(new JcrCallback() {
public Object doInJcr(Session session) throws IOException, RepositoryException {
deleteLinks(item, property, session);
return null;
}
});
}
protected void deleteLinks(Item item, String property, Session session) throws IOException, RepositoryException {
StringBuilder stmt = new StringBuilder();
stmt.append("//").append(rootNode)
.append("/*[@item = '")
.append(item.getId())
.append("' and property = '")
.append(property)
.append("']");
QueryManager qm = getQueryManager(session);
Query q = qm.createQuery(stmt.toString(), Query.XPATH);
QueryResult qr = q.execute();
for (NodeIterator nodes = qr.getNodes(); nodes.hasNext();) {
Node node = nodes.nextNode();
node.remove();
}
}
public Collection<Item> getReciprocalItems(final String property,
final boolean like,
final Object value) {
Collection<Link> links = getLinks(property, "item", like, value);
Set<Item> items = new HashSet<Item>();
for (Link l : links) {
Item linkedTo = l.getLinkedTo();
items.add(linkedTo);
}
return items;
}
public List<Link> getLinks(final String property,
String linkProperty,
final boolean like,
final Object value) {
// Find the Items which we'll use for the next part of the query
Set<Item> linkToItems = new HashSet<Item>();
try {
if (value instanceof Collection) {
Collection values = (Collection) value;
for (Object v : values) {
findItemsForPath(linkToItems, v.toString(), like);
}
} else {
findItemsForPath(linkToItems, value.toString(), like);
}
} catch (QueryException e) {
throw new RuntimeException(e);
} catch (RegistryException e) {
throw new RuntimeException(e);
}
if (linkToItems.size() == 0) return Collections.emptyList();
// Now find all the links where the linkedTo property is equal to one of the above items
StringBuilder stmt = new StringBuilder();
stmt.append("//").append(rootNode).append("/*[(@");
boolean first = true;
for (Item i : linkToItems) {
if (first) first = false;
else stmt.append("' or ");
stmt.append(linkProperty).append(" = '").append(i.getId());
}
stmt.append("') and property = '").append(property);
stmt.append("']");
return doQuery(stmt.toString());
}
/**
* Find all the items which match the given path
* @param items
* @param path
* @param like
* @throws RegistryException
* @throws QueryException
*/
private void findItemsForPath(Set<Item> items, String path, final boolean like)
throws RegistryException, QueryException {
org.mule.galaxy.query.Query q =
new org.mule.galaxy.query.Query();
int idx = path.lastIndexOf('/');
if (idx != -1) {
q.fromPath(path.substring(0, idx));
path = path.substring(idx+1);
}
String version = null;
idx = path.lastIndexOf('?');
if (idx != -1) {
int vidx = path.lastIndexOf("version=");
if (vidx != -1) {
version = path.substring(vidx + "version=".length());
}
path = path.substring(0, idx);
q.setSelectTypes(EntryVersion.class, ArtifactVersion.class);
}
if (!like) {
q.add(OpRestriction.eq("name", path));
} else {
q.add(OpRestriction.like("name", path));
}
if (version != null) {
q.add(OpRestriction.eq("version", version));
}
SearchResults results = registry.search(q);
items.addAll(results.getResults());
if (like && version == null) {
q.setSelectTypes(EntryVersion.class, ArtifactVersion.class);
results = registry.search(q);
items.addAll(results.getResults());
}
}
public List<Link> getLinks(final String property, final boolean like, final Object path) {
return getLinks(property, "linkedTo", like, path);
}
@OnEvent
public void onEvent(final EntryDeletedEvent deleted) {
SecurityUtils.doPriveleged(new Runnable() {
public void run() {
execute(new JcrCallback() {
public Object doInJcr(final Session session) throws IOException, RepositoryException {
deleteAssociatedLinks(deleted.getItemId(), session);
return null;
}
});
}
});
}
@OnEvent
public void onEvent(final EntryVersionDeletedEvent deleted) {
SecurityUtils.doPriveleged(new Runnable() {
public void run() {
execute(new JcrCallback() {
public Object doInJcr(final Session session) throws IOException, RepositoryException {
deleteAssociatedLinks(deleted.getItemId(), session);
return null;
}
});
}
});
}
@OnEvent
public void onEvent(final EntryCreatedEvent created) {
SecurityUtils.doPriveleged(new Runnable() {
public void run() {
execute(new JcrCallback() {
public Object doInJcr(final Session session) throws IOException, RepositoryException {
addLinks(created.getItemId(), session);
return null;
}
});
}
});
}
@OnEvent
public void onEvent(final EntryMovedEvent created) {
SecurityUtils.doPriveleged(new Runnable() {
public void run() {
execute(new JcrCallback() {
public Object doInJcr(final Session session) throws IOException, RepositoryException {
clearDetectedLinks(created.getItemId(), session);
addLinks(created.getItemId(), session);
return null;
}
});
}
});
}
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
this.context = applicationContext;
}
public Registry getRegistry() {
if (registry == null) {
registry = (Registry) context.getBean("registry");
}
return registry;
}
}
| true | true | protected void addLinks(String id, Session session) throws IOException, RepositoryException {
try {
// First, see if this item which was moved matches any outstanding unmatched links
Item item = getRegistry().getItemById(id);
List<String> versionIds = getVersionIds(id);
StringBuilder stmt = new StringBuilder();
stmt.append("//").append(rootNode)
.append("/*[not(@linkedTo) and jcr:like(@linkedToPath, '%")
.append(item.getName())
.append("%')]");
QueryManager qm = getQueryManager(session);
Query q = qm.createQuery(stmt.toString(), Query.XPATH);
QueryResult qr = q.execute();
for (NodeIterator nodes = qr.getNodes(); nodes.hasNext();) {
Node node = nodes.nextNode();
Item linkItem = getRegistry().getItemById(JcrUtil.getStringOrNull(node, "item"));
String path = JcrUtil.getStringOrNull(node, "linkedToPath");
Item resolve = registry.resolve(linkItem, path);
if (resolve != null) {
node.setProperty("linkedTo", resolve.getId());
}
}
// Now try to resolve links which are associated with this item
stmt = new StringBuilder();
stmt.append("//").append(rootNode)
.append("/*[not(@linkedTo) and (@item = '")
.append(id);
// Find the children of this node....
for (String childId : versionIds) {
stmt.append("' or @item = '")
.append(childId);
}
stmt.append("')]");
q = qm.createQuery(stmt.toString(), Query.XPATH);
for (NodeIterator nodes = q.execute().getNodes(); nodes.hasNext();) {
Node node = nodes.nextNode();
Item linkItem = getRegistry().getItemById(JcrUtil.getStringOrNull(node, "item"));
String path = JcrUtil.getStringOrNull(node, "linkedToPath");
Item resolve = registry.resolve(linkItem, path);
if (resolve != null) {
node.setProperty("linkedTo", resolve.getId());
}
}
} catch (NotFoundException e) {
throw new RuntimeException(e);
} catch (RegistryException e) {
throw new RuntimeException(e);
} catch (AccessException e) {
throw new RuntimeException(e);
}
}
| protected void addLinks(String id, Session session) throws IOException, RepositoryException {
try {
// First, see if this item which was moved matches any outstanding unmatched links
Item item = getRegistry().getItemById(id);
List<String> versionIds = getVersionIds(id);
StringBuilder stmt = new StringBuilder();
stmt.append("//").append(rootNode)
.append("/*[not(@linkedTo) and jcr:like(@linkedToPath, '%")
.append(item.getName())
.append("%')]");
QueryManager qm = getQueryManager(session);
Query q = qm.createQuery(stmt.toString(), Query.XPATH);
QueryResult qr = q.execute();
for (NodeIterator nodes = qr.getNodes(); nodes.hasNext();) {
Node node = nodes.nextNode();
Item linkItem = getRegistry().getItemById(JcrUtil.getStringOrNull(node, "item"));
String path = JcrUtil.getStringOrNull(node, "linkedToPath");
Item resolve = registry.resolve(linkItem, path);
if (resolve != null) {
node.setProperty("linkedTo", resolve.getId());
}
}
// Now try to resolve links which are associated with this item
stmt = new StringBuilder();
stmt.append("//").append(rootNode)
.append("/*[not(@linkedTo) and (@item = '")
.append(id);
// Find the children of this node....
for (String childId : versionIds) {
stmt.append("' or @item = '")
.append(childId);
}
stmt.append("')]");
q = qm.createQuery(stmt.toString(), Query.XPATH);
for (NodeIterator nodes = q.execute().getNodes(); nodes.hasNext();) {
Node node = nodes.nextNode();
Item linkItem = getRegistry().getItemById(JcrUtil.getStringOrNull(node, "item"));
String path = JcrUtil.getStringOrNull(node, "linkedToPath");
Item resolve = registry.resolve(linkItem, path);
if (resolve != null) {
node.setProperty("linkedTo", resolve.getId());
}
}
} catch (NotFoundException e) {
// this was deleted before we could tie together links... forget about it
} catch (RegistryException e) {
throw new RuntimeException(e);
} catch (AccessException e) {
throw new RuntimeException(e);
}
}
|
diff --git a/lib/com/coldsteelstudios/irc/client/Channel.java b/lib/com/coldsteelstudios/irc/client/Channel.java
index 2bbd9b8..ef8ffd5 100644
--- a/lib/com/coldsteelstudios/irc/client/Channel.java
+++ b/lib/com/coldsteelstudios/irc/client/Channel.java
@@ -1,281 +1,281 @@
package com.coldsteelstudios.irc.client;
import java.util.List;
import java.util.LinkedList;
import java.util.Iterator;
import com.coldsteelstudios.util.ListSorter;
//reflection
import java.lang.reflect.Method;
import java.lang.reflect.InvocationTargetException;
/**
* Synchs basic information about a channel.
*/
public class Channel implements Iterable<User> {
/**
* This is necessarily set via the constructor.
*/
private String name;
/**
* Channel topic
*/
private String topic = null;
/**
* list of users on the channel
* ChannelUser encapsulates User...
*/
private List<ChannelUser> users;
/**
* List of ChannelListeners wanting
* to receive updats when this channel's state changes
* (user list, topic, etc)
*/
private List<ChannelListener> subs;
/**
* Create an empty channel with a name...
*/
public Channel(String name) {
this.name = name;
//pre-instantiate this as it should always contain
//at least one element: the current client...
// users = new LinkedList<ChannelUser>();
users = java.util.Collections.synchronizedList( new LinkedList<ChannelUser>());
}
/**
* Get the channel's name.
*
* Note there is no setter for name:
* It must be set on instantiation,
* and cannot be changed.
*
* @return the channel's name.
*/
public String getName() {
return name;
}
/**
* Get the channel's topic, if it is synched.
*
* @return the topic if it is synched, or "" if it is not.
*/
public String getTopic() {
if (topic == null) return "";
return topic;
}
/**
* Intended to be called by SyncManager when the topic is
* received/changed.
*
* @string topic the new topic.
*/
void setTopic(String topic) {
this.topic = topic;
topicChanged();
}
/**
* Get a channel user given a user.
*
* @param u a User
*
* @return a ChannelUser encapsulating u, or null if there isn't one on this channel.
*/
private ChannelUser getChannelUser(User u) {
//if the user is on the channel, return the user...
for (ChannelUser user : users) if ( user.equals(u) ) return user;
return null;
}
/**
* Handle the dirty work of adding a user to a channel...
* This is for internal use: it Does*Not*Fire*usersChanged*
*/
void addUserToList(User user) {
if ( getChannelUser(user) != null )
return;
users.add( new ChannelUser(user) );
}
public void join(User u) {
addUser(u);
notifyListeners("join", this, u);
}
public void part(User u) {
delUser(u);
notifyListeners("part", this, u);
}
public void kick(User u) {
delUser(u);
notifyListeners("kick", this, u);
}
//New user, old nick.
public void nick(User user, String nick) {
notifyListeners("nick", this, user, nick);
notifyListeners("usersChanged");
}
//Add a single user.
public void addUser(User u) {
addUserToList( u );
usersChanged();
}
public void delUser(User user) {
ChannelUser cuser = getChannelUser( user );
//if the user was found on the channel,
//remove from the list and fire a change...
if ( cuser != null ) {
users.remove( cuser );
usersChanged();
}
}
public void setUserMode(User user, ChannelUser.Mode mode) {
ChannelUser cuser = getChannelUser(user);
///@TODO
if (cuser == null)
throw new RuntimeException("Trying to set mode on a user who isn't in the channel!!!!");
cuser.setMode(mode);
}
public void destroy() {
users.clear();
subs.clear();
name = "";
}
public int numUsers() {
return (users == null) ? 0 : users.size();
}
public ChannelUser getUser(int idx) {
return users.get(idx);
}
public Iterator<ChannelUser> iterChannelUsers() {
return users.iterator();
}
public Iterator<User> iterator() {
return new Iterator<User>() {
private Iterator<ChannelUser> it;
{ it = users.iterator(); }
public boolean hasNext() {
return it.hasNext();
}
public User next() {
return it.next().getUser();
}
public void remove() throws UnsupportedOperationException {
throw new UnsupportedOperationException("Remove not supported.");
}
};
}
public boolean equals(Channel c) {
return c.name.equals(name);
}
//////NOTIFICATION STUFF BELOW ///////
void usersChanged() {
//@TODO make this better :/
ListSorter.sort(users );
notifyListeners("usersChanged", this);
}
void topicChanged() {
notifyListeners("topicChanged", this);
}
private void notifyListeners(String event, Object ... params) {
if ( subs == null ) return;
Class[] paramtypes = {this.getClass()};
// Object[] params = {this};
for (ChannelListener l : subs) {
try {
//FIND the method (or exception if not defined)
- Method command = Class.forName("client.ChannelListener").getDeclaredMethod(event,paramtypes);
+ Method command = Class.forName("ChannelListener").getDeclaredMethod(event,paramtypes);
//invoke the method
command.invoke(l,params);
} catch (NoSuchMethodException e) {
//won't happen.
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
} catch (ClassNotFoundException e) {
}
}
}
public void addChannelListener(ChannelListener c) {
if (subs == null)
subs = java.util.Collections.synchronizedList( new LinkedList<ChannelListener>());
// subs = new LinkedList<ChannelListener>();
subs.add(c);
}
public void removeChannelListener(ChannelListener c) {
if (subs == null) return;
subs.remove(c);
}
/**
* @TODO remove listener
* VERY important: ChannelWindows need to void the subscription when they go away...
*/
}
| true | true | private void notifyListeners(String event, Object ... params) {
if ( subs == null ) return;
Class[] paramtypes = {this.getClass()};
// Object[] params = {this};
for (ChannelListener l : subs) {
try {
//FIND the method (or exception if not defined)
Method command = Class.forName("client.ChannelListener").getDeclaredMethod(event,paramtypes);
//invoke the method
command.invoke(l,params);
} catch (NoSuchMethodException e) {
//won't happen.
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
} catch (ClassNotFoundException e) {
}
}
}
| private void notifyListeners(String event, Object ... params) {
if ( subs == null ) return;
Class[] paramtypes = {this.getClass()};
// Object[] params = {this};
for (ChannelListener l : subs) {
try {
//FIND the method (or exception if not defined)
Method command = Class.forName("ChannelListener").getDeclaredMethod(event,paramtypes);
//invoke the method
command.invoke(l,params);
} catch (NoSuchMethodException e) {
//won't happen.
} catch (IllegalAccessException e) {
} catch (InvocationTargetException e) {
} catch (ClassNotFoundException e) {
}
}
}
|
diff --git a/farrago/src/org/eigenbase/oj/rel/IterCalcRel.java b/farrago/src/org/eigenbase/oj/rel/IterCalcRel.java
index 960568745..a92d28bf0 100644
--- a/farrago/src/org/eigenbase/oj/rel/IterCalcRel.java
+++ b/farrago/src/org/eigenbase/oj/rel/IterCalcRel.java
@@ -1,590 +1,590 @@
/*
// $Id$
// Package org.eigenbase is a class library of data management components.
// Copyright (C) 2005-2006 The Eigenbase Project
// Copyright (C) 2002-2006 Disruptive Tech
// Copyright (C) 2005-2006 LucidEra, Inc.
// Portions Copyright (C) 2003-2006 John V. Sichi
//
// 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 approved by The Eigenbase Project.
//
// 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 org.eigenbase.oj.rel;
import java.util.*;
import java.util.List;
import java.util.logging.*;
import openjava.mop.*;
import openjava.ptree.*;
import org.eigenbase.oj.rex.*;
import org.eigenbase.oj.util.*;
import org.eigenbase.rel.*;
import org.eigenbase.rel.metadata.*;
import org.eigenbase.relopt.*;
import org.eigenbase.reltype.*;
import org.eigenbase.rex.*;
import org.eigenbase.runtime.*;
import org.eigenbase.sql.fun.*;
import org.eigenbase.trace.*;
import org.eigenbase.util.*;
/**
* <code>IterCalcRel</code> is an iterator implementation of a combination of
* {@link ProjectRel} above an optional {@link FilterRel}. It takes a {@link
* TupleIter iterator} as input, and for each row applies the filter condition
* if defined. Rows passing the filter expression are transformed via projection
* and returned. Note that the same object is always returned (with different
* values), so parents must not buffer the result.
*
* <p>Rules:
*
* <ul>
* <li>{@link org.eigenbase.oj.rel.IterRules.IterCalcRule} creates an
* IterCalcRel from a {@link org.eigenbase.rel.CalcRel}</li>
* </ul>
*/
public class IterCalcRel
extends SingleRel
implements JavaRel
{
//~ Static fields/initializers ---------------------------------------------
private static boolean abortOnError = true;
private static boolean errorBuffering = false;
//~ Instance fields --------------------------------------------------------
private final RexProgram program;
/**
* Values defined in {@link ProjectRelBase.Flags}.
*/
protected int flags;
private String tag;
//~ Constructors -----------------------------------------------------------
public IterCalcRel(
RelOptCluster cluster,
RelNode child,
RexProgram program,
int flags)
{
this(cluster, child, program, flags, null);
}
public IterCalcRel(
RelOptCluster cluster,
RelNode child,
RexProgram program,
int flags,
String tag)
{
super(
cluster,
new RelTraitSet(CallingConvention.ITERATOR),
child);
this.flags = flags;
this.program = program;
this.rowType = program.getOutputRowType();
this.tag = tag;
}
//~ Methods ----------------------------------------------------------------
// TODO jvs 10-May-2004: need a computeSelfCost which takes condition into
// account; maybe inherit from CalcRelBase?
public void explain(RelOptPlanWriter pw)
{
program.explainCalc(this, pw);
}
protected String computeDigest()
{
String tempDigest = super.computeDigest();
if (tag != null) {
// append logger type to digest
int lastParen = tempDigest.lastIndexOf(')');
tempDigest =
tempDigest.substring(0, lastParen)
+ ",type=" + tag
+ tempDigest.substring(lastParen);
}
return tempDigest;
}
public double getRows()
{
return
FilterRel.estimateFilteredRows(
getChild(),
program.getCondition());
}
public RelOptCost computeSelfCost(RelOptPlanner planner)
{
double dRows = RelMetadataQuery.getRowCount(this);
double dCpu =
RelMetadataQuery.getRowCount(getChild())
* program.getExprCount();
double dIo = 0;
return planner.makeCost(dRows, dCpu, dIo);
}
public Object clone()
{
IterCalcRel clone =
new IterCalcRel(
getCluster(),
RelOptUtil.clone(getChild()),
program.copy(),
getFlags(),
tag);
clone.inheritTraitsFrom(this);
return clone;
}
public int getFlags()
{
return flags;
}
public boolean isBoxed()
{
return
(flags & ProjectRelBase.Flags.Boxed) == ProjectRelBase.Flags.Boxed;
}
/**
* Burrows into a synthetic record and returns the underlying relation which
* provides the field called <code>fieldName</code>.
*/
public JavaRel implementFieldAccess(
JavaRelImplementor implementor,
String fieldName)
{
if (!isBoxed()) {
return
implementor.implementFieldAccess((JavaRel) getChild(),
fieldName);
}
RelDataType type = getRowType();
int field = type.getFieldOrdinal(fieldName);
RexLocalRef ref = program.getProjectList().get(field);
final int index = ref.getIndex();
return
implementor.findRel(
(JavaRel) this,
program.getExprList().get(index));
}
/**
* Disables throwing of exceptions on error. Do not set this false without a
* very good reason! Doing so will prevent type cast, overflow/underflow,
* etc. errors in Farrago.
*/
public static void setAbortOnError(boolean abortOnError)
{
IterCalcRel.abortOnError = abortOnError;
}
/**
* Allows errors to be buffered, in the event that they overflow the
* error handler.
*
* @param errorBuffering whether to buffer errors
*/
public static void setErrorBuffering(boolean errorBuffering)
{
IterCalcRel.errorBuffering = errorBuffering;
}
public static Expression implementAbstract(
JavaRelImplementor implementor,
JavaRel rel,
Expression childExp,
Variable varInputRow,
final RelDataType inputRowType,
final RelDataType outputRowType,
RexProgram program,
String tag)
{
return
implementAbstractTupleIter(
implementor,
rel,
childExp,
varInputRow,
inputRowType,
outputRowType,
program,
tag);
}
/**
* Generates code for a Java expression satisfying the
* {@link org.eigenbase.runtime.TupleIter} interface. The generated
* code allocates a {@link org.eigenbase.runtime.CalcTupleIter}
* with a dynamic {@link org.eigenbase.runtime.TupleIter#fetchNext()}
* method. If the "abort on error" flag is false, or an error handling
* tag is specified, then fetchNext is written to handle row errors.
*
* <p>
*
* Row errors are handled by wrapping expressions that can fail
* with a try/catch block. A caught RuntimeException is then published
* to an "connection variable." In the event that errors can overflow,
* an "error buffering" flag allows them to be posted again on the next
* iteration of fetchNext.
*
* @param implementor an object that implements relations as Java code
* @param rel the relation to be implemented
* @param childExp the implemented child of the relation
* @param varInputRow the Java variable to use for the input row
* @param inputRowType the rel data type of the input row
* @param outputRowType the rel data type of the output row
* @param program the rex program to implemented by the relation
* @param tag an error handling tag
* @return a Java expression satisfying the TupleIter interface
*/
public static Expression implementAbstractTupleIter(
JavaRelImplementor implementor,
JavaRel rel,
Expression childExp,
Variable varInputRow,
final RelDataType inputRowType,
final RelDataType outputRowType,
RexProgram program,
String tag)
{
// Perform error recovery if continuing on errors or if
// an error handling tag has been specified
- boolean errorRecovery = false; //(abortOnError == false || tag != null);
+ boolean errorRecovery = (abortOnError == false || tag != null);
// Error buffering should not be enabled unless error recovery is
assert (errorBuffering == false || errorRecovery == true);
// Allow backwards compatibility until all Farrago extensions are
// satisfied with the new error handling semantics. The new semantics
// include:
// (1) cast input object to input row object outside of try block,
// should be fine, at least for base Farrago
// (2) maintain a columnIndex counter to better locate of error,
// at the cost of a few cycles
// (3) publish errors to the runtime context. FarragoRuntimeContext
// now supports this API
boolean backwardsCompatible = true;
if (tag != null) {
backwardsCompatible = false;
}
RelDataTypeFactory typeFactory = implementor.getTypeFactory();
OJClass outputRowClass =
OJUtil.typeToOJClass(
outputRowType,
typeFactory);
OJClass inputRowClass = OJUtil.typeToOJClass(
inputRowType,
typeFactory);
Variable varOutputRow = implementor.newVariable();
FieldDeclaration rowVarDecl =
new FieldDeclaration(
new ModifierList(ModifierList.PRIVATE),
TypeName.forOJClass(outputRowClass),
varOutputRow.toString(),
new AllocationExpression(
outputRowClass,
new ExpressionList()));
// The method body for fetchNext, a main target of code generation
StatementList nextMethodBody = new StatementList();
// First, post an error if it overflowed the previous time
// if (pendingError) {
// rc = handleRowError(...);
// if (rc instanceof NoDataReason) {
// return rc;
// }
// pendingError = false;
// }
if (errorBuffering) {
// add to next method body...
}
// Most of fetchNext falls within a while() block. The while block
// allows us to try multiple input rows against a filter condition
// before returning a single row.
// while (true) {
// Object varInputObj = inputIterator.fetchNext();
// if (varInputObj instanceof TupleIter.NoDataReason) {
// return varInputObj;
// }
// InputRowClass varInputRow = (InputRowClass) varInputObj;
// int columnIndex = 0;
// [calculation statements]
// }
StatementList whileBody = new StatementList();
Variable varInputObj = implementor.newVariable();
whileBody.add(
new VariableDeclaration(
OJUtil.typeNameForClass(Object.class),
varInputObj.toString(),
new MethodCall(
new FieldAccess("inputIterator"),
"fetchNext",
new ExpressionList())));
StatementList ifNoDataReasonBody = new StatementList();
whileBody.add(
new IfStatement(
new InstanceofExpression(
varInputObj,
OJUtil.typeNameForClass(TupleIter.NoDataReason.class)),
ifNoDataReasonBody));
ifNoDataReasonBody.add(new ReturnStatement(varInputObj));
// Push up the row declaration for new error handling so that the
// input row is available to the error handler
if (! backwardsCompatible) {
whileBody.add(
declareInputRow(inputRowClass, varInputRow, varInputObj));
}
Variable varColumnIndex = null;
if (errorRecovery && backwardsCompatible == false) {
varColumnIndex = implementor.newVariable();
whileBody.add(
new VariableDeclaration(
OJUtil.typeNameForClass(int.class),
varColumnIndex.toString(),
Literal.makeLiteral(0)));
}
// Calculator (projection, filtering) statements are later appended
// to calcStmts. Typically, this target will be the while list itself.
StatementList calcStmts;
if (errorRecovery == false) {
calcStmts = whileBody;
} else {
// For error recovery, we wrap the calc statements
// (e.g., everything but the code that reads rows from the
// inputIterator) in a try/catch that publishes exceptions.
calcStmts = new StatementList();
// try { /* calcStmts */ }
// catch(RuntimeException ex) {
// Object rc = connection.handleRowError(...);
// [buffer error if necessary]
// }
StatementList catchStmts = new StatementList();
if (backwardsCompatible) {
catchStmts.add(
new ExpressionStatement(
new MethodCall(
new MethodCall(
OJUtil.typeNameForClass(EigenbaseTrace.class),
"getStatementTracer",
null),
"log",
new ExpressionList(
new FieldAccess(
OJUtil.typeNameForClass(Level.class),
"WARNING"),
Literal.makeLiteral("java calc exception"),
new FieldAccess("ex")))));
} else {
Variable varRc = implementor.newVariable();
ExpressionList handleRowErrorArgs =
new ExpressionList(
varInputRow,
new FieldAccess("ex"),
varColumnIndex);
handleRowErrorArgs.add(Literal.makeLiteral(tag));
catchStmts.add(
new VariableDeclaration(
OJUtil.typeNameForClass(Object.class),
varRc.toString(),
new MethodCall(
implementor.getConnectionVariable(),
"handleRowError",
handleRowErrorArgs)));
// Buffer an error if it overflowed
// if (rc instanceof NoDataReason) {
// pendingError = true;
// [save error state]
// return rc;
// }
if (errorBuffering) {
// add to catch statements...
}
}
CatchList catchList =
new CatchList(
new CatchBlock(
new Parameter(
OJUtil.typeNameForClass(RuntimeException.class),
"ex"),
catchStmts));
TryStatement tryStmt = new TryStatement(calcStmts, catchList);
whileBody.add(tryStmt);
}
if (backwardsCompatible) {
whileBody.add(
declareInputRow(inputRowClass, varInputRow, varInputObj));
}
MemberDeclarationList memberList = new MemberDeclarationList();
StatementList condBody;
RexToOJTranslator translator =
implementor.newStmtTranslator(rel, calcStmts, memberList);
try {
translator.pushProgram(program);
if (program.getCondition() != null) {
condBody = new StatementList();
RexNode rexIsTrue =
rel.getCluster().getRexBuilder().makeCall(
SqlStdOperatorTable.isTrueOperator,
new RexNode[] { program.getCondition() });
Expression conditionExp =
translator.translateRexNode(rexIsTrue);
calcStmts.add(new IfStatement(conditionExp, condBody));
} else {
condBody = calcStmts;
}
RexToOJTranslator condTranslator = translator.push(condBody);
RelDataTypeField [] fields = outputRowType.getFields();
final List<RexLocalRef> projectRefList = program.getProjectList();
int i = -1;
for (RexLocalRef rhs : projectRefList) {
if (errorRecovery && backwardsCompatible == false) {
condBody.add(
new ExpressionStatement(
new UnaryExpression(
varColumnIndex,
UnaryExpression.POST_INCREMENT)));
}
++i;
String javaFieldName = Util.toJavaId(
fields[i].getName(),
i);
Expression lhs = new FieldAccess(varOutputRow, javaFieldName);
condTranslator.translateAssignment(fields[i], lhs, rhs);
}
} finally {
translator.popProgram(program);
}
condBody.add(new ReturnStatement(varOutputRow));
WhileStatement whileStmt =
new WhileStatement(
Literal.makeLiteral(true),
whileBody);
nextMethodBody.add(whileStmt);
MemberDeclaration fetchNextMethodDecl =
new MethodDeclaration(
new ModifierList(ModifierList.PUBLIC),
OJUtil.typeNameForClass(Object.class),
"fetchNext",
new ParameterList(),
null,
nextMethodBody);
// The restart() method should reset variables used to buffer errors
// pendingError = false
if (errorBuffering) {
// declare refinement of restart() and add to member list...
}
memberList.add(rowVarDecl);
memberList.add(fetchNextMethodDecl);
Expression newTupleIterExp =
new AllocationExpression(
OJUtil.typeNameForClass(CalcTupleIter.class),
new ExpressionList(childExp),
memberList);
return newTupleIterExp;
}
public ParseTree implement(JavaRelImplementor implementor)
{
Expression childExp =
implementor.visitJavaChild(this, 0, (JavaRel) getChild());
RelDataType outputRowType = getRowType();
RelDataType inputRowType = getChild().getRowType();
Variable varInputRow = implementor.newVariable();
implementor.bind(
getChild(),
varInputRow);
return
implementAbstract(
implementor,
this,
childExp,
varInputRow,
inputRowType,
outputRowType,
program,
tag);
}
public RexProgram getProgram()
{
return program;
}
public String getTag()
{
return tag;
}
private static Statement declareInputRow(
OJClass inputRowClass, Variable varInputRow, Variable varInputObj)
{
return new VariableDeclaration(
TypeName.forOJClass(inputRowClass),
varInputRow.toString(),
new CastExpression(
TypeName.forOJClass(inputRowClass),
varInputObj));
}
}
// End IterCalcRel.java
| true | true | public static Expression implementAbstractTupleIter(
JavaRelImplementor implementor,
JavaRel rel,
Expression childExp,
Variable varInputRow,
final RelDataType inputRowType,
final RelDataType outputRowType,
RexProgram program,
String tag)
{
// Perform error recovery if continuing on errors or if
// an error handling tag has been specified
boolean errorRecovery = false; //(abortOnError == false || tag != null);
// Error buffering should not be enabled unless error recovery is
assert (errorBuffering == false || errorRecovery == true);
// Allow backwards compatibility until all Farrago extensions are
// satisfied with the new error handling semantics. The new semantics
// include:
// (1) cast input object to input row object outside of try block,
// should be fine, at least for base Farrago
// (2) maintain a columnIndex counter to better locate of error,
// at the cost of a few cycles
// (3) publish errors to the runtime context. FarragoRuntimeContext
// now supports this API
boolean backwardsCompatible = true;
if (tag != null) {
backwardsCompatible = false;
}
RelDataTypeFactory typeFactory = implementor.getTypeFactory();
OJClass outputRowClass =
OJUtil.typeToOJClass(
outputRowType,
typeFactory);
OJClass inputRowClass = OJUtil.typeToOJClass(
inputRowType,
typeFactory);
Variable varOutputRow = implementor.newVariable();
FieldDeclaration rowVarDecl =
new FieldDeclaration(
new ModifierList(ModifierList.PRIVATE),
TypeName.forOJClass(outputRowClass),
varOutputRow.toString(),
new AllocationExpression(
outputRowClass,
new ExpressionList()));
// The method body for fetchNext, a main target of code generation
StatementList nextMethodBody = new StatementList();
// First, post an error if it overflowed the previous time
// if (pendingError) {
// rc = handleRowError(...);
// if (rc instanceof NoDataReason) {
// return rc;
// }
// pendingError = false;
// }
if (errorBuffering) {
// add to next method body...
}
// Most of fetchNext falls within a while() block. The while block
// allows us to try multiple input rows against a filter condition
// before returning a single row.
// while (true) {
// Object varInputObj = inputIterator.fetchNext();
// if (varInputObj instanceof TupleIter.NoDataReason) {
// return varInputObj;
// }
// InputRowClass varInputRow = (InputRowClass) varInputObj;
// int columnIndex = 0;
// [calculation statements]
// }
StatementList whileBody = new StatementList();
Variable varInputObj = implementor.newVariable();
whileBody.add(
new VariableDeclaration(
OJUtil.typeNameForClass(Object.class),
varInputObj.toString(),
new MethodCall(
new FieldAccess("inputIterator"),
"fetchNext",
new ExpressionList())));
StatementList ifNoDataReasonBody = new StatementList();
whileBody.add(
new IfStatement(
new InstanceofExpression(
varInputObj,
OJUtil.typeNameForClass(TupleIter.NoDataReason.class)),
ifNoDataReasonBody));
ifNoDataReasonBody.add(new ReturnStatement(varInputObj));
// Push up the row declaration for new error handling so that the
// input row is available to the error handler
if (! backwardsCompatible) {
whileBody.add(
declareInputRow(inputRowClass, varInputRow, varInputObj));
}
Variable varColumnIndex = null;
if (errorRecovery && backwardsCompatible == false) {
varColumnIndex = implementor.newVariable();
whileBody.add(
new VariableDeclaration(
OJUtil.typeNameForClass(int.class),
varColumnIndex.toString(),
Literal.makeLiteral(0)));
}
// Calculator (projection, filtering) statements are later appended
// to calcStmts. Typically, this target will be the while list itself.
StatementList calcStmts;
if (errorRecovery == false) {
calcStmts = whileBody;
} else {
// For error recovery, we wrap the calc statements
// (e.g., everything but the code that reads rows from the
// inputIterator) in a try/catch that publishes exceptions.
calcStmts = new StatementList();
// try { /* calcStmts */ }
// catch(RuntimeException ex) {
// Object rc = connection.handleRowError(...);
// [buffer error if necessary]
// }
StatementList catchStmts = new StatementList();
if (backwardsCompatible) {
catchStmts.add(
new ExpressionStatement(
new MethodCall(
new MethodCall(
OJUtil.typeNameForClass(EigenbaseTrace.class),
"getStatementTracer",
null),
"log",
new ExpressionList(
new FieldAccess(
OJUtil.typeNameForClass(Level.class),
"WARNING"),
Literal.makeLiteral("java calc exception"),
new FieldAccess("ex")))));
} else {
Variable varRc = implementor.newVariable();
ExpressionList handleRowErrorArgs =
new ExpressionList(
varInputRow,
new FieldAccess("ex"),
varColumnIndex);
handleRowErrorArgs.add(Literal.makeLiteral(tag));
catchStmts.add(
new VariableDeclaration(
OJUtil.typeNameForClass(Object.class),
varRc.toString(),
new MethodCall(
implementor.getConnectionVariable(),
"handleRowError",
handleRowErrorArgs)));
// Buffer an error if it overflowed
// if (rc instanceof NoDataReason) {
// pendingError = true;
// [save error state]
// return rc;
// }
if (errorBuffering) {
// add to catch statements...
}
}
CatchList catchList =
new CatchList(
new CatchBlock(
new Parameter(
OJUtil.typeNameForClass(RuntimeException.class),
"ex"),
catchStmts));
TryStatement tryStmt = new TryStatement(calcStmts, catchList);
whileBody.add(tryStmt);
}
if (backwardsCompatible) {
whileBody.add(
declareInputRow(inputRowClass, varInputRow, varInputObj));
}
MemberDeclarationList memberList = new MemberDeclarationList();
StatementList condBody;
RexToOJTranslator translator =
implementor.newStmtTranslator(rel, calcStmts, memberList);
try {
translator.pushProgram(program);
if (program.getCondition() != null) {
condBody = new StatementList();
RexNode rexIsTrue =
rel.getCluster().getRexBuilder().makeCall(
SqlStdOperatorTable.isTrueOperator,
new RexNode[] { program.getCondition() });
Expression conditionExp =
translator.translateRexNode(rexIsTrue);
calcStmts.add(new IfStatement(conditionExp, condBody));
} else {
condBody = calcStmts;
}
RexToOJTranslator condTranslator = translator.push(condBody);
RelDataTypeField [] fields = outputRowType.getFields();
final List<RexLocalRef> projectRefList = program.getProjectList();
int i = -1;
for (RexLocalRef rhs : projectRefList) {
if (errorRecovery && backwardsCompatible == false) {
condBody.add(
new ExpressionStatement(
new UnaryExpression(
varColumnIndex,
UnaryExpression.POST_INCREMENT)));
}
++i;
String javaFieldName = Util.toJavaId(
fields[i].getName(),
i);
Expression lhs = new FieldAccess(varOutputRow, javaFieldName);
condTranslator.translateAssignment(fields[i], lhs, rhs);
}
} finally {
translator.popProgram(program);
}
condBody.add(new ReturnStatement(varOutputRow));
WhileStatement whileStmt =
new WhileStatement(
Literal.makeLiteral(true),
whileBody);
nextMethodBody.add(whileStmt);
MemberDeclaration fetchNextMethodDecl =
new MethodDeclaration(
new ModifierList(ModifierList.PUBLIC),
OJUtil.typeNameForClass(Object.class),
"fetchNext",
new ParameterList(),
null,
nextMethodBody);
// The restart() method should reset variables used to buffer errors
// pendingError = false
if (errorBuffering) {
// declare refinement of restart() and add to member list...
}
memberList.add(rowVarDecl);
memberList.add(fetchNextMethodDecl);
Expression newTupleIterExp =
new AllocationExpression(
OJUtil.typeNameForClass(CalcTupleIter.class),
new ExpressionList(childExp),
memberList);
return newTupleIterExp;
}
| public static Expression implementAbstractTupleIter(
JavaRelImplementor implementor,
JavaRel rel,
Expression childExp,
Variable varInputRow,
final RelDataType inputRowType,
final RelDataType outputRowType,
RexProgram program,
String tag)
{
// Perform error recovery if continuing on errors or if
// an error handling tag has been specified
boolean errorRecovery = (abortOnError == false || tag != null);
// Error buffering should not be enabled unless error recovery is
assert (errorBuffering == false || errorRecovery == true);
// Allow backwards compatibility until all Farrago extensions are
// satisfied with the new error handling semantics. The new semantics
// include:
// (1) cast input object to input row object outside of try block,
// should be fine, at least for base Farrago
// (2) maintain a columnIndex counter to better locate of error,
// at the cost of a few cycles
// (3) publish errors to the runtime context. FarragoRuntimeContext
// now supports this API
boolean backwardsCompatible = true;
if (tag != null) {
backwardsCompatible = false;
}
RelDataTypeFactory typeFactory = implementor.getTypeFactory();
OJClass outputRowClass =
OJUtil.typeToOJClass(
outputRowType,
typeFactory);
OJClass inputRowClass = OJUtil.typeToOJClass(
inputRowType,
typeFactory);
Variable varOutputRow = implementor.newVariable();
FieldDeclaration rowVarDecl =
new FieldDeclaration(
new ModifierList(ModifierList.PRIVATE),
TypeName.forOJClass(outputRowClass),
varOutputRow.toString(),
new AllocationExpression(
outputRowClass,
new ExpressionList()));
// The method body for fetchNext, a main target of code generation
StatementList nextMethodBody = new StatementList();
// First, post an error if it overflowed the previous time
// if (pendingError) {
// rc = handleRowError(...);
// if (rc instanceof NoDataReason) {
// return rc;
// }
// pendingError = false;
// }
if (errorBuffering) {
// add to next method body...
}
// Most of fetchNext falls within a while() block. The while block
// allows us to try multiple input rows against a filter condition
// before returning a single row.
// while (true) {
// Object varInputObj = inputIterator.fetchNext();
// if (varInputObj instanceof TupleIter.NoDataReason) {
// return varInputObj;
// }
// InputRowClass varInputRow = (InputRowClass) varInputObj;
// int columnIndex = 0;
// [calculation statements]
// }
StatementList whileBody = new StatementList();
Variable varInputObj = implementor.newVariable();
whileBody.add(
new VariableDeclaration(
OJUtil.typeNameForClass(Object.class),
varInputObj.toString(),
new MethodCall(
new FieldAccess("inputIterator"),
"fetchNext",
new ExpressionList())));
StatementList ifNoDataReasonBody = new StatementList();
whileBody.add(
new IfStatement(
new InstanceofExpression(
varInputObj,
OJUtil.typeNameForClass(TupleIter.NoDataReason.class)),
ifNoDataReasonBody));
ifNoDataReasonBody.add(new ReturnStatement(varInputObj));
// Push up the row declaration for new error handling so that the
// input row is available to the error handler
if (! backwardsCompatible) {
whileBody.add(
declareInputRow(inputRowClass, varInputRow, varInputObj));
}
Variable varColumnIndex = null;
if (errorRecovery && backwardsCompatible == false) {
varColumnIndex = implementor.newVariable();
whileBody.add(
new VariableDeclaration(
OJUtil.typeNameForClass(int.class),
varColumnIndex.toString(),
Literal.makeLiteral(0)));
}
// Calculator (projection, filtering) statements are later appended
// to calcStmts. Typically, this target will be the while list itself.
StatementList calcStmts;
if (errorRecovery == false) {
calcStmts = whileBody;
} else {
// For error recovery, we wrap the calc statements
// (e.g., everything but the code that reads rows from the
// inputIterator) in a try/catch that publishes exceptions.
calcStmts = new StatementList();
// try { /* calcStmts */ }
// catch(RuntimeException ex) {
// Object rc = connection.handleRowError(...);
// [buffer error if necessary]
// }
StatementList catchStmts = new StatementList();
if (backwardsCompatible) {
catchStmts.add(
new ExpressionStatement(
new MethodCall(
new MethodCall(
OJUtil.typeNameForClass(EigenbaseTrace.class),
"getStatementTracer",
null),
"log",
new ExpressionList(
new FieldAccess(
OJUtil.typeNameForClass(Level.class),
"WARNING"),
Literal.makeLiteral("java calc exception"),
new FieldAccess("ex")))));
} else {
Variable varRc = implementor.newVariable();
ExpressionList handleRowErrorArgs =
new ExpressionList(
varInputRow,
new FieldAccess("ex"),
varColumnIndex);
handleRowErrorArgs.add(Literal.makeLiteral(tag));
catchStmts.add(
new VariableDeclaration(
OJUtil.typeNameForClass(Object.class),
varRc.toString(),
new MethodCall(
implementor.getConnectionVariable(),
"handleRowError",
handleRowErrorArgs)));
// Buffer an error if it overflowed
// if (rc instanceof NoDataReason) {
// pendingError = true;
// [save error state]
// return rc;
// }
if (errorBuffering) {
// add to catch statements...
}
}
CatchList catchList =
new CatchList(
new CatchBlock(
new Parameter(
OJUtil.typeNameForClass(RuntimeException.class),
"ex"),
catchStmts));
TryStatement tryStmt = new TryStatement(calcStmts, catchList);
whileBody.add(tryStmt);
}
if (backwardsCompatible) {
whileBody.add(
declareInputRow(inputRowClass, varInputRow, varInputObj));
}
MemberDeclarationList memberList = new MemberDeclarationList();
StatementList condBody;
RexToOJTranslator translator =
implementor.newStmtTranslator(rel, calcStmts, memberList);
try {
translator.pushProgram(program);
if (program.getCondition() != null) {
condBody = new StatementList();
RexNode rexIsTrue =
rel.getCluster().getRexBuilder().makeCall(
SqlStdOperatorTable.isTrueOperator,
new RexNode[] { program.getCondition() });
Expression conditionExp =
translator.translateRexNode(rexIsTrue);
calcStmts.add(new IfStatement(conditionExp, condBody));
} else {
condBody = calcStmts;
}
RexToOJTranslator condTranslator = translator.push(condBody);
RelDataTypeField [] fields = outputRowType.getFields();
final List<RexLocalRef> projectRefList = program.getProjectList();
int i = -1;
for (RexLocalRef rhs : projectRefList) {
if (errorRecovery && backwardsCompatible == false) {
condBody.add(
new ExpressionStatement(
new UnaryExpression(
varColumnIndex,
UnaryExpression.POST_INCREMENT)));
}
++i;
String javaFieldName = Util.toJavaId(
fields[i].getName(),
i);
Expression lhs = new FieldAccess(varOutputRow, javaFieldName);
condTranslator.translateAssignment(fields[i], lhs, rhs);
}
} finally {
translator.popProgram(program);
}
condBody.add(new ReturnStatement(varOutputRow));
WhileStatement whileStmt =
new WhileStatement(
Literal.makeLiteral(true),
whileBody);
nextMethodBody.add(whileStmt);
MemberDeclaration fetchNextMethodDecl =
new MethodDeclaration(
new ModifierList(ModifierList.PUBLIC),
OJUtil.typeNameForClass(Object.class),
"fetchNext",
new ParameterList(),
null,
nextMethodBody);
// The restart() method should reset variables used to buffer errors
// pendingError = false
if (errorBuffering) {
// declare refinement of restart() and add to member list...
}
memberList.add(rowVarDecl);
memberList.add(fetchNextMethodDecl);
Expression newTupleIterExp =
new AllocationExpression(
OJUtil.typeNameForClass(CalcTupleIter.class),
new ExpressionList(childExp),
memberList);
return newTupleIterExp;
}
|
diff --git a/maven-plugin-tools-annotations/src/main/java/org/apache/maven/tools/plugin/annotations/JavaAnnotationsMojoDescriptorExtractor.java b/maven-plugin-tools-annotations/src/main/java/org/apache/maven/tools/plugin/annotations/JavaAnnotationsMojoDescriptorExtractor.java
index d75bda0..b81c8fb 100644
--- a/maven-plugin-tools-annotations/src/main/java/org/apache/maven/tools/plugin/annotations/JavaAnnotationsMojoDescriptorExtractor.java
+++ b/maven-plugin-tools-annotations/src/main/java/org/apache/maven/tools/plugin/annotations/JavaAnnotationsMojoDescriptorExtractor.java
@@ -1,648 +1,648 @@
package org.apache.maven.tools.plugin.annotations;
/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*/
import com.thoughtworks.qdox.JavaDocBuilder;
import com.thoughtworks.qdox.model.DocletTag;
import com.thoughtworks.qdox.model.JavaClass;
import com.thoughtworks.qdox.model.JavaField;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.artifact.factory.ArtifactFactory;
import org.apache.maven.artifact.resolver.ArtifactNotFoundException;
import org.apache.maven.artifact.resolver.ArtifactResolutionException;
import org.apache.maven.artifact.resolver.ArtifactResolver;
import org.apache.maven.plugin.descriptor.DuplicateParameterException;
import org.apache.maven.plugin.descriptor.InvalidPluginDescriptorException;
import org.apache.maven.plugin.descriptor.MojoDescriptor;
import org.apache.maven.plugin.descriptor.PluginDescriptor;
import org.apache.maven.plugin.descriptor.Requirement;
import org.apache.maven.project.MavenProject;
import org.apache.maven.tools.plugin.DefaultPluginToolsRequest;
import org.apache.maven.tools.plugin.ExtendedMojoDescriptor;
import org.apache.maven.tools.plugin.PluginToolsRequest;
import org.apache.maven.tools.plugin.annotations.datamodel.ComponentAnnotationContent;
import org.apache.maven.tools.plugin.annotations.datamodel.ExecuteAnnotationContent;
import org.apache.maven.tools.plugin.annotations.datamodel.MojoAnnotationContent;
import org.apache.maven.tools.plugin.annotations.datamodel.ParameterAnnotationContent;
import org.apache.maven.tools.plugin.annotations.scanner.MojoAnnotatedClass;
import org.apache.maven.tools.plugin.annotations.scanner.MojoAnnotationsScanner;
import org.apache.maven.tools.plugin.annotations.scanner.MojoAnnotationsScannerRequest;
import org.apache.maven.tools.plugin.extractor.ExtractionException;
import org.apache.maven.tools.plugin.extractor.MojoDescriptorExtractor;
import org.codehaus.plexus.archiver.UnArchiver;
import org.codehaus.plexus.archiver.manager.ArchiverManager;
import org.codehaus.plexus.archiver.manager.NoSuchArchiverException;
import org.codehaus.plexus.logging.AbstractLogEnabled;
import org.codehaus.plexus.util.StringUtils;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
/**
* @author Olivier Lamy
* @since 3.0
*/
public class JavaAnnotationsMojoDescriptorExtractor
extends AbstractLogEnabled
implements MojoDescriptorExtractor
{
/**
* @requirement
*/
private MojoAnnotationsScanner mojoAnnotationsScanner;
/**
* @requirement
*/
private ArtifactResolver artifactResolver;
/**
* @requirement
*/
private ArtifactFactory artifactFactory;
/**
* @requirement
*/
private ArchiverManager archiverManager;
public List<MojoDescriptor> execute( MavenProject project, PluginDescriptor pluginDescriptor )
throws ExtractionException, InvalidPluginDescriptorException
{
return execute( new DefaultPluginToolsRequest( project, pluginDescriptor ) );
}
public List<MojoDescriptor> execute( PluginToolsRequest request )
throws ExtractionException, InvalidPluginDescriptorException
{
MojoAnnotationsScannerRequest mojoAnnotationsScannerRequest = new MojoAnnotationsScannerRequest();
mojoAnnotationsScannerRequest.setClassesDirectories(
Arrays.asList( new File( request.getProject().getBuild().getOutputDirectory() ) ) );
mojoAnnotationsScannerRequest.setDependencies( request.getDependencies() );
mojoAnnotationsScannerRequest.setProject( request.getProject() );
Map<String, MojoAnnotatedClass> mojoAnnotatedClasses =
mojoAnnotationsScanner.scan( mojoAnnotationsScannerRequest );
// found artifact from reactors to scan sources
// we currently only scan sources from reactors
List<MavenProject> mavenProjects = new ArrayList<MavenProject>();
// if we need to scan sources from external artifacts
Set<Artifact> externalArtifacts = new HashSet<Artifact>();
for ( MojoAnnotatedClass mojoAnnotatedClass : mojoAnnotatedClasses.values() )
{
if ( !StringUtils.equals( mojoAnnotatedClass.getArtifact().getArtifactId(),
request.getProject().getArtifact().getArtifactId() ) )
{
MavenProject mavenProject =
getFromProjectReferences( mojoAnnotatedClass.getArtifact(), request.getProject() );
if ( mavenProject != null )
{
mavenProjects.add( mavenProject );
}
else
{
externalArtifacts.add( mojoAnnotatedClass.getArtifact() );
}
}
}
Map<String, JavaClass> javaClassesMap = new HashMap<String, JavaClass>();
// try to get artifact with classifier sources
// extract somewhere then scan doclet for @since, @deprecated
for ( Artifact artifact : externalArtifacts )
{
// parameter for test-sources too ?? olamy I need that for it test only
if ( StringUtils.equalsIgnoreCase( "tests", artifact.getClassifier() ) )
{
javaClassesMap.putAll( discoverClassesFromSourcesJar( artifact, request, "test-sources" ) );
}
else
{
javaClassesMap.putAll( discoverClassesFromSourcesJar( artifact, request, "sources" ) );
}
}
for ( MavenProject mavenProject : mavenProjects )
{
javaClassesMap.putAll( discoverClasses( request.getEncoding(), mavenProject ) );
}
javaClassesMap.putAll( discoverClasses( request ) );
populateDataFromJavadoc( mojoAnnotatedClasses, javaClassesMap );
return toMojoDescriptors( mojoAnnotatedClasses, request, javaClassesMap );
}
protected Map<String, JavaClass> discoverClassesFromSourcesJar( Artifact artifact, PluginToolsRequest request,
String classifier )
throws ExtractionException
{
try
{
Artifact sourcesArtifact =
artifactFactory.createArtifactWithClassifier( artifact.getGroupId(), artifact.getArtifactId(),
artifact.getVersion(), artifact.getType(), classifier );
artifactResolver.resolve( sourcesArtifact, request.getRemoteRepos(), request.getLocal() );
if ( sourcesArtifact.getFile() != null && sourcesArtifact.getFile().exists() )
{
File extractDirectory = new File( request.getProject().getBuild().getDirectory(),
"maven-plugin-plugin-sources/" + sourcesArtifact.getGroupId() + "/"
+ sourcesArtifact.getArtifactId() + "/"
+ sourcesArtifact.getVersion() + "/"
+ sourcesArtifact.getClassifier() );
if ( !extractDirectory.exists() )
{
extractDirectory.mkdirs();
}
// extract sources in a directory
//target/maven-plugin-plugin/${groupId}/${artifact}/sources
UnArchiver unArchiver = archiverManager.getUnArchiver( "jar" );
unArchiver.setSourceFile( sourcesArtifact.getFile() );
unArchiver.setDestDirectory( extractDirectory );
unArchiver.extract();
return discoverClasses( request.getEncoding(), Arrays.asList( extractDirectory ) );
}
}
catch ( ArtifactResolutionException e )
{
throw new ExtractionException( e.getMessage(), e );
}
catch ( ArtifactNotFoundException e )
{
//throw new ExtractionException( e.getMessage(), e );
getLogger().debug( "skip ArtifactNotFoundException:" + e.getMessage() );
getLogger().warn(
"Impossible to get sources artifact for " + artifact.getGroupId() + ":" + artifact.getArtifactId() + ":"
+ artifact.getVersion() + ". Some javadoc tags (@since, @deprecated and comments) won't be used" );
}
catch ( NoSuchArchiverException e )
{
throw new ExtractionException( e.getMessage(), e );
}
return Collections.emptyMap();
}
/**
* from sources scan to get @since and @deprecated and description of classes and fields.
*
* @param mojoAnnotatedClasses
* @param javaClassesMap
*/
protected void populateDataFromJavadoc( Map<String, MojoAnnotatedClass> mojoAnnotatedClasses,
Map<String, JavaClass> javaClassesMap )
{
for ( Map.Entry<String, MojoAnnotatedClass> entry : mojoAnnotatedClasses.entrySet() )
{
JavaClass javaClass = javaClassesMap.get( entry.getKey() );
if ( javaClass != null )
{
MojoAnnotationContent mojoAnnotationContent = entry.getValue().getMojo();
if ( mojoAnnotationContent != null )
{
mojoAnnotationContent.setDescription( javaClass.getComment() );
DocletTag since = findInClassHierarchy( javaClass, "since" );
if ( since != null )
{
mojoAnnotationContent.setSince( since.getValue() );
}
DocletTag deprecated = findInClassHierarchy( javaClass, "deprecated" );
if ( deprecated != null )
{
mojoAnnotationContent.setDeprecated( deprecated.getValue() );
}
}
Map<String, JavaField> fieldsMap =
extractFieldParameterTags( javaClass, javaClassesMap, mojoAnnotatedClasses );
Map<String, ParameterAnnotationContent> parameters =
getParametersParentHierarchy( entry.getValue(), new HashMap<String, ParameterAnnotationContent>(),
mojoAnnotatedClasses );
for ( Map.Entry<String, ParameterAnnotationContent> parameter : new TreeMap<String, ParameterAnnotationContent>(
parameters ).entrySet() )
{
JavaField javaField = fieldsMap.get( parameter.getKey() );
if ( javaField != null )
{
ParameterAnnotationContent parameterAnnotationContent = parameter.getValue();
DocletTag deprecated = javaField.getTagByName( "deprecated" );
if ( deprecated != null )
{
parameterAnnotationContent.setDeprecated( deprecated.getValue() );
}
DocletTag since = javaField.getTagByName( "since" );
if ( since != null )
{
parameterAnnotationContent.setSince( since.getValue() );
}
parameterAnnotationContent.setDescription( javaField.getComment() );
}
}
for ( Map.Entry<String, ComponentAnnotationContent> component : entry.getValue().getComponents().entrySet() )
{
JavaField javaField = fieldsMap.get( component.getKey() );
if ( javaField != null )
{
ComponentAnnotationContent componentAnnotationContent = component.getValue();
DocletTag deprecated = javaField.getTagByName( "deprecated" );
if ( deprecated != null )
{
componentAnnotationContent.setDeprecated( deprecated.getValue() );
}
DocletTag since = javaField.getTagByName( "since" );
if ( since != null )
{
componentAnnotationContent.setSince( since.getValue() );
}
componentAnnotationContent.setDescription( javaField.getComment() );
}
}
}
}
}
/**
* @param javaClass not null
* @param tagName not null
* @return docletTag instance
*/
private DocletTag findInClassHierarchy( JavaClass javaClass, String tagName )
{
DocletTag tag = javaClass.getTagByName( tagName );
if ( tag == null )
{
JavaClass superClass = javaClass.getSuperJavaClass();
if ( superClass != null )
{
tag = findInClassHierarchy( superClass, tagName );
}
}
return tag;
}
/**
* extract fields that are either parameters or components.
*
* @param javaClass not null
* @return map with Mojo parameters names as keys
*/
private Map<String, JavaField> extractFieldParameterTags( JavaClass javaClass,
Map<String, JavaClass> javaClassesMap,
Map<String, MojoAnnotatedClass> mojoAnnotatedClasses )
{
Map<String, JavaField> rawParams = new TreeMap<String, com.thoughtworks.qdox.model.JavaField>();
// we have to add the parent fields first, so that they will be overwritten by the local fields if
// that actually happens...
JavaClass superClass = javaClass.getSuperJavaClass();
if ( superClass != null )
{
if ( superClass.getFields().length > 0 )
{
rawParams = extractFieldParameterTags( superClass, javaClassesMap, mojoAnnotatedClasses );
}
// maybe sources comes from scan of sources artifact
superClass = javaClassesMap.get( superClass.getFullyQualifiedName() );
if ( superClass != null )
{
rawParams = extractFieldParameterTags( superClass, javaClassesMap, mojoAnnotatedClasses );
}
}
else
{
rawParams = new TreeMap<String, JavaField>();
}
JavaField[] classFields = javaClass.getFields();
if ( classFields != null )
{
for ( JavaField field : classFields )
{
rawParams.put( field.getName(), field );
}
}
return rawParams;
}
protected Map<String, JavaClass> discoverClasses( final PluginToolsRequest request )
{
return discoverClasses( request.getEncoding(), request.getProject() );
}
protected Map<String, JavaClass> discoverClasses( final String encoding, final MavenProject project )
{
List<File> sources = new ArrayList<File>();
for ( String source : (List<String>) project.getCompileSourceRoots() )
{
sources.add( new File( source ) );
}
// TODO be more dynamic
File generatedPlugin = new File( project.getBasedir(), "target/generated-sources/plugin" );
if ( !project.getCompileSourceRoots().contains( generatedPlugin.getAbsolutePath() )
&& generatedPlugin.exists() )
{
sources.add( generatedPlugin );
}
return discoverClasses( encoding, sources );
}
protected Map<String, JavaClass> discoverClasses( final String encoding, List<File> sourceDirectories )
{
JavaDocBuilder builder = new JavaDocBuilder();
builder.setEncoding( encoding );
for ( File source : sourceDirectories )
{
builder.addSourceTree( source );
}
JavaClass[] javaClasses = builder.getClasses();
if ( javaClasses == null || javaClasses.length < 1 )
{
return Collections.emptyMap();
}
Map<String, JavaClass> javaClassMap = new HashMap<String, JavaClass>( javaClasses.length );
for ( JavaClass javaClass : javaClasses )
{
javaClassMap.put( javaClass.getFullyQualifiedName(), javaClass );
}
return javaClassMap;
}
private List<MojoDescriptor> toMojoDescriptors( Map<String, MojoAnnotatedClass> mojoAnnotatedClasses,
PluginToolsRequest request, Map<String, JavaClass> javaClassesMap )
throws DuplicateParameterException
{
List<MojoDescriptor> mojoDescriptors = new ArrayList<MojoDescriptor>( mojoAnnotatedClasses.size() );
for ( MojoAnnotatedClass mojoAnnotatedClass : mojoAnnotatedClasses.values() )
{
// no mojo so skip it
if ( mojoAnnotatedClass.getMojo() == null )
{
continue;
}
ExtendedMojoDescriptor mojoDescriptor = new ExtendedMojoDescriptor();
//mojoDescriptor.setRole( mojoAnnotatedClass.getClassName() );
//mojoDescriptor.setRoleHint( "default" );
mojoDescriptor.setImplementation( mojoAnnotatedClass.getClassName() );
mojoDescriptor.setLanguage( "java" );
MojoAnnotationContent mojo = mojoAnnotatedClass.getMojo();
mojoDescriptor.setDescription( mojo.getDescription() );
mojoDescriptor.setSince( mojo.getSince() );
mojo.setDeprecated( mojo.getDeprecated() );
mojoDescriptor.setAggregator( mojo.aggregator() );
- mojoDescriptor.setDependencyResolutionRequired( mojo.requiresDependencyResolution().toString() );
- mojoDescriptor.setDependencyCollectionRequired( mojo.requiresDependencyCollection().toString() );
+ mojoDescriptor.setDependencyResolutionRequired( mojo.requiresDependencyResolution().id() );
+ mojoDescriptor.setDependencyCollectionRequired( mojo.requiresDependencyCollection().id() );
mojoDescriptor.setDirectInvocationOnly( mojo.requiresDirectInvocation() );
mojoDescriptor.setDeprecated( mojo.getDeprecated() );
mojoDescriptor.setThreadSafe( mojo.threadSafe() );
ExecuteAnnotationContent execute = findExecuteInParentHierarchy( mojoAnnotatedClass, mojoAnnotatedClasses );
if ( execute != null )
{
mojoDescriptor.setExecuteGoal( execute.goal() );
mojoDescriptor.setExecuteLifecycle( execute.lifecycle() );
mojoDescriptor.setExecutePhase( execute.phase().id() );
}
mojoDescriptor.setExecutionStrategy( mojo.executionStrategy() );
// ???
//mojoDescriptor.alwaysExecute(mojo.a)
mojoDescriptor.setGoal( mojo.name() );
mojoDescriptor.setOnlineRequired( mojo.requiresOnline() );
mojoDescriptor.setPhase( mojo.defaultPhase().id() );
Map<String, ParameterAnnotationContent> parameters =
getParametersParentHierarchy( mojoAnnotatedClass, new HashMap<String, ParameterAnnotationContent>(),
mojoAnnotatedClasses );
for ( ParameterAnnotationContent parameterAnnotationContent : new TreeSet<ParameterAnnotationContent>(
parameters.values() ) )
{
org.apache.maven.plugin.descriptor.Parameter parameter =
new org.apache.maven.plugin.descriptor.Parameter();
parameter.setName( parameterAnnotationContent.getFieldName() );
parameter.setAlias( parameterAnnotationContent.alias() );
parameter.setDefaultValue( parameterAnnotationContent.defaultValue() );
parameter.setDeprecated( parameterAnnotationContent.getDeprecated() );
parameter.setDescription( parameterAnnotationContent.getDescription() );
parameter.setEditable( !parameterAnnotationContent.readonly() );
parameter.setExpression( parameterAnnotationContent.expression() );
parameter.setType( parameterAnnotationContent.getClassName() );
parameter.setSince( parameterAnnotationContent.getSince() );
parameter.setRequired( parameterAnnotationContent.required() );
mojoDescriptor.addParameter( parameter );
}
Map<String, ComponentAnnotationContent> components =
getComponentsParentHierarchy( mojoAnnotatedClass, new HashMap<String, ComponentAnnotationContent>(),
mojoAnnotatedClasses );
for ( ComponentAnnotationContent componentAnnotationContent : new TreeSet<ComponentAnnotationContent>(
components.values() ) )
{
org.apache.maven.plugin.descriptor.Parameter parameter =
new org.apache.maven.plugin.descriptor.Parameter();
parameter.setName( componentAnnotationContent.getFieldName() );
parameter.setRequirement(
new Requirement( componentAnnotationContent.role(), componentAnnotationContent.roleHint() ) );
parameter.setEditable( false );
parameter.setDeprecated( componentAnnotationContent.getDeprecated() );
parameter.setSince( componentAnnotationContent.getSince() );
mojoDescriptor.addParameter( parameter );
}
mojoDescriptor.setPluginDescriptor( request.getPluginDescriptor() );
mojoDescriptors.add( mojoDescriptor );
}
return mojoDescriptors;
}
protected ExecuteAnnotationContent findExecuteInParentHierarchy( MojoAnnotatedClass mojoAnnotatedClass,
Map<String, MojoAnnotatedClass> mojoAnnotatedClasses )
{
if ( mojoAnnotatedClass.getExecute() != null )
{
return mojoAnnotatedClass.getExecute();
}
String parentClassName = mojoAnnotatedClass.getParentClassName();
if ( StringUtils.isEmpty( parentClassName ) )
{
return null;
}
MojoAnnotatedClass parent = mojoAnnotatedClasses.get( parentClassName );
if ( parent == null )
{
return null;
}
return findExecuteInParentHierarchy( parent, mojoAnnotatedClasses );
}
protected Map<String, ParameterAnnotationContent> getParametersParentHierarchy(
MojoAnnotatedClass mojoAnnotatedClass, Map<String, ParameterAnnotationContent> parameters,
Map<String, MojoAnnotatedClass> mojoAnnotatedClasses )
{
List<ParameterAnnotationContent> parameterAnnotationContents = new ArrayList<ParameterAnnotationContent>();
parameterAnnotationContents =
getParametersParent( mojoAnnotatedClass, parameterAnnotationContents, mojoAnnotatedClasses );
// move to parent first to build the Map
Collections.reverse( parameterAnnotationContents );
Map<String, ParameterAnnotationContent> map =
new HashMap<String, ParameterAnnotationContent>( parameterAnnotationContents.size() );
for ( ParameterAnnotationContent parameterAnnotationContent : parameterAnnotationContents )
{
map.put( parameterAnnotationContent.getFieldName(), parameterAnnotationContent );
}
return map;
}
protected List<ParameterAnnotationContent> getParametersParent( MojoAnnotatedClass mojoAnnotatedClass,
List<ParameterAnnotationContent> parameterAnnotationContents,
Map<String, MojoAnnotatedClass> mojoAnnotatedClasses )
{
parameterAnnotationContents.addAll( mojoAnnotatedClass.getParameters().values() );
String parentClassName = mojoAnnotatedClass.getParentClassName();
if ( parentClassName != null )
{
MojoAnnotatedClass parent = mojoAnnotatedClasses.get( parentClassName );
if ( parent != null )
{
return getParametersParent( parent, parameterAnnotationContents, mojoAnnotatedClasses );
}
}
return parameterAnnotationContents;
}
protected Map<String, ComponentAnnotationContent> getComponentsParentHierarchy(
MojoAnnotatedClass mojoAnnotatedClass, Map<String, ComponentAnnotationContent> components,
Map<String, MojoAnnotatedClass> mojoAnnotatedClasses )
{
List<ComponentAnnotationContent> componentAnnotationContents = new ArrayList<ComponentAnnotationContent>();
componentAnnotationContents =
getComponentParent( mojoAnnotatedClass, componentAnnotationContents, mojoAnnotatedClasses );
// move to parent first to build the Map
Collections.reverse( componentAnnotationContents );
Map<String, ComponentAnnotationContent> map =
new HashMap<String, ComponentAnnotationContent>( componentAnnotationContents.size() );
for ( ComponentAnnotationContent componentAnnotationContent : componentAnnotationContents )
{
map.put( componentAnnotationContent.getFieldName(), componentAnnotationContent );
}
return map;
}
protected List<ComponentAnnotationContent> getComponentParent( MojoAnnotatedClass mojoAnnotatedClass,
List<ComponentAnnotationContent> componentAnnotationContents,
Map<String, MojoAnnotatedClass> mojoAnnotatedClasses )
{
componentAnnotationContents.addAll( mojoAnnotatedClass.getComponents().values() );
String parentClassName = mojoAnnotatedClass.getParentClassName();
if ( parentClassName != null )
{
MojoAnnotatedClass parent = mojoAnnotatedClasses.get( parentClassName );
if ( parent != null )
{
return getComponentParent( parent, componentAnnotationContents, mojoAnnotatedClasses );
}
}
return componentAnnotationContents;
}
protected MavenProject getFromProjectReferences( Artifact artifact, MavenProject project )
{
if ( project.getProjectReferences() == null || project.getProjectReferences().isEmpty() )
{
return null;
}
Collection<MavenProject> mavenProjects = project.getProjectReferences().values();
for ( MavenProject mavenProject : mavenProjects )
{
if ( StringUtils.equals( mavenProject.getId(), artifact.getId() ) )
{
return mavenProject;
}
}
return null;
}
}
| true | true | private List<MojoDescriptor> toMojoDescriptors( Map<String, MojoAnnotatedClass> mojoAnnotatedClasses,
PluginToolsRequest request, Map<String, JavaClass> javaClassesMap )
throws DuplicateParameterException
{
List<MojoDescriptor> mojoDescriptors = new ArrayList<MojoDescriptor>( mojoAnnotatedClasses.size() );
for ( MojoAnnotatedClass mojoAnnotatedClass : mojoAnnotatedClasses.values() )
{
// no mojo so skip it
if ( mojoAnnotatedClass.getMojo() == null )
{
continue;
}
ExtendedMojoDescriptor mojoDescriptor = new ExtendedMojoDescriptor();
//mojoDescriptor.setRole( mojoAnnotatedClass.getClassName() );
//mojoDescriptor.setRoleHint( "default" );
mojoDescriptor.setImplementation( mojoAnnotatedClass.getClassName() );
mojoDescriptor.setLanguage( "java" );
MojoAnnotationContent mojo = mojoAnnotatedClass.getMojo();
mojoDescriptor.setDescription( mojo.getDescription() );
mojoDescriptor.setSince( mojo.getSince() );
mojo.setDeprecated( mojo.getDeprecated() );
mojoDescriptor.setAggregator( mojo.aggregator() );
mojoDescriptor.setDependencyResolutionRequired( mojo.requiresDependencyResolution().toString() );
mojoDescriptor.setDependencyCollectionRequired( mojo.requiresDependencyCollection().toString() );
mojoDescriptor.setDirectInvocationOnly( mojo.requiresDirectInvocation() );
mojoDescriptor.setDeprecated( mojo.getDeprecated() );
mojoDescriptor.setThreadSafe( mojo.threadSafe() );
ExecuteAnnotationContent execute = findExecuteInParentHierarchy( mojoAnnotatedClass, mojoAnnotatedClasses );
if ( execute != null )
{
mojoDescriptor.setExecuteGoal( execute.goal() );
mojoDescriptor.setExecuteLifecycle( execute.lifecycle() );
mojoDescriptor.setExecutePhase( execute.phase().id() );
}
mojoDescriptor.setExecutionStrategy( mojo.executionStrategy() );
// ???
//mojoDescriptor.alwaysExecute(mojo.a)
mojoDescriptor.setGoal( mojo.name() );
mojoDescriptor.setOnlineRequired( mojo.requiresOnline() );
mojoDescriptor.setPhase( mojo.defaultPhase().id() );
Map<String, ParameterAnnotationContent> parameters =
getParametersParentHierarchy( mojoAnnotatedClass, new HashMap<String, ParameterAnnotationContent>(),
mojoAnnotatedClasses );
for ( ParameterAnnotationContent parameterAnnotationContent : new TreeSet<ParameterAnnotationContent>(
parameters.values() ) )
{
org.apache.maven.plugin.descriptor.Parameter parameter =
new org.apache.maven.plugin.descriptor.Parameter();
parameter.setName( parameterAnnotationContent.getFieldName() );
parameter.setAlias( parameterAnnotationContent.alias() );
parameter.setDefaultValue( parameterAnnotationContent.defaultValue() );
parameter.setDeprecated( parameterAnnotationContent.getDeprecated() );
parameter.setDescription( parameterAnnotationContent.getDescription() );
parameter.setEditable( !parameterAnnotationContent.readonly() );
parameter.setExpression( parameterAnnotationContent.expression() );
parameter.setType( parameterAnnotationContent.getClassName() );
parameter.setSince( parameterAnnotationContent.getSince() );
parameter.setRequired( parameterAnnotationContent.required() );
mojoDescriptor.addParameter( parameter );
}
Map<String, ComponentAnnotationContent> components =
getComponentsParentHierarchy( mojoAnnotatedClass, new HashMap<String, ComponentAnnotationContent>(),
mojoAnnotatedClasses );
for ( ComponentAnnotationContent componentAnnotationContent : new TreeSet<ComponentAnnotationContent>(
components.values() ) )
{
org.apache.maven.plugin.descriptor.Parameter parameter =
new org.apache.maven.plugin.descriptor.Parameter();
parameter.setName( componentAnnotationContent.getFieldName() );
parameter.setRequirement(
new Requirement( componentAnnotationContent.role(), componentAnnotationContent.roleHint() ) );
parameter.setEditable( false );
parameter.setDeprecated( componentAnnotationContent.getDeprecated() );
parameter.setSince( componentAnnotationContent.getSince() );
mojoDescriptor.addParameter( parameter );
}
mojoDescriptor.setPluginDescriptor( request.getPluginDescriptor() );
mojoDescriptors.add( mojoDescriptor );
}
return mojoDescriptors;
}
| private List<MojoDescriptor> toMojoDescriptors( Map<String, MojoAnnotatedClass> mojoAnnotatedClasses,
PluginToolsRequest request, Map<String, JavaClass> javaClassesMap )
throws DuplicateParameterException
{
List<MojoDescriptor> mojoDescriptors = new ArrayList<MojoDescriptor>( mojoAnnotatedClasses.size() );
for ( MojoAnnotatedClass mojoAnnotatedClass : mojoAnnotatedClasses.values() )
{
// no mojo so skip it
if ( mojoAnnotatedClass.getMojo() == null )
{
continue;
}
ExtendedMojoDescriptor mojoDescriptor = new ExtendedMojoDescriptor();
//mojoDescriptor.setRole( mojoAnnotatedClass.getClassName() );
//mojoDescriptor.setRoleHint( "default" );
mojoDescriptor.setImplementation( mojoAnnotatedClass.getClassName() );
mojoDescriptor.setLanguage( "java" );
MojoAnnotationContent mojo = mojoAnnotatedClass.getMojo();
mojoDescriptor.setDescription( mojo.getDescription() );
mojoDescriptor.setSince( mojo.getSince() );
mojo.setDeprecated( mojo.getDeprecated() );
mojoDescriptor.setAggregator( mojo.aggregator() );
mojoDescriptor.setDependencyResolutionRequired( mojo.requiresDependencyResolution().id() );
mojoDescriptor.setDependencyCollectionRequired( mojo.requiresDependencyCollection().id() );
mojoDescriptor.setDirectInvocationOnly( mojo.requiresDirectInvocation() );
mojoDescriptor.setDeprecated( mojo.getDeprecated() );
mojoDescriptor.setThreadSafe( mojo.threadSafe() );
ExecuteAnnotationContent execute = findExecuteInParentHierarchy( mojoAnnotatedClass, mojoAnnotatedClasses );
if ( execute != null )
{
mojoDescriptor.setExecuteGoal( execute.goal() );
mojoDescriptor.setExecuteLifecycle( execute.lifecycle() );
mojoDescriptor.setExecutePhase( execute.phase().id() );
}
mojoDescriptor.setExecutionStrategy( mojo.executionStrategy() );
// ???
//mojoDescriptor.alwaysExecute(mojo.a)
mojoDescriptor.setGoal( mojo.name() );
mojoDescriptor.setOnlineRequired( mojo.requiresOnline() );
mojoDescriptor.setPhase( mojo.defaultPhase().id() );
Map<String, ParameterAnnotationContent> parameters =
getParametersParentHierarchy( mojoAnnotatedClass, new HashMap<String, ParameterAnnotationContent>(),
mojoAnnotatedClasses );
for ( ParameterAnnotationContent parameterAnnotationContent : new TreeSet<ParameterAnnotationContent>(
parameters.values() ) )
{
org.apache.maven.plugin.descriptor.Parameter parameter =
new org.apache.maven.plugin.descriptor.Parameter();
parameter.setName( parameterAnnotationContent.getFieldName() );
parameter.setAlias( parameterAnnotationContent.alias() );
parameter.setDefaultValue( parameterAnnotationContent.defaultValue() );
parameter.setDeprecated( parameterAnnotationContent.getDeprecated() );
parameter.setDescription( parameterAnnotationContent.getDescription() );
parameter.setEditable( !parameterAnnotationContent.readonly() );
parameter.setExpression( parameterAnnotationContent.expression() );
parameter.setType( parameterAnnotationContent.getClassName() );
parameter.setSince( parameterAnnotationContent.getSince() );
parameter.setRequired( parameterAnnotationContent.required() );
mojoDescriptor.addParameter( parameter );
}
Map<String, ComponentAnnotationContent> components =
getComponentsParentHierarchy( mojoAnnotatedClass, new HashMap<String, ComponentAnnotationContent>(),
mojoAnnotatedClasses );
for ( ComponentAnnotationContent componentAnnotationContent : new TreeSet<ComponentAnnotationContent>(
components.values() ) )
{
org.apache.maven.plugin.descriptor.Parameter parameter =
new org.apache.maven.plugin.descriptor.Parameter();
parameter.setName( componentAnnotationContent.getFieldName() );
parameter.setRequirement(
new Requirement( componentAnnotationContent.role(), componentAnnotationContent.roleHint() ) );
parameter.setEditable( false );
parameter.setDeprecated( componentAnnotationContent.getDeprecated() );
parameter.setSince( componentAnnotationContent.getSince() );
mojoDescriptor.addParameter( parameter );
}
mojoDescriptor.setPluginDescriptor( request.getPluginDescriptor() );
mojoDescriptors.add( mojoDescriptor );
}
return mojoDescriptors;
}
|
diff --git a/src/jpcsp/Loader.java b/src/jpcsp/Loader.java
index db735761..c2580493 100644
--- a/src/jpcsp/Loader.java
+++ b/src/jpcsp/Loader.java
@@ -1,1149 +1,1149 @@
/*
This file is part of jpcsp.
Jpcsp 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.
Jpcsp 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 Jpcsp. If not, see <http://www.gnu.org/licenses/>.
*/
package jpcsp;
import java.io.File;
import java.io.FileFilter;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import jpcsp.Debugger.ElfHeaderInfo;
import jpcsp.HLE.pspSysMem;
import jpcsp.HLE.kernel.Managers;
import jpcsp.HLE.kernel.types.SceModule;
import jpcsp.format.DeferredStub;
import jpcsp.format.Elf32;
import jpcsp.format.Elf32EntHeader;
import jpcsp.format.Elf32ProgramHeader;
import jpcsp.format.Elf32Relocate;
import jpcsp.format.Elf32SectionHeader;
import jpcsp.format.Elf32StubHeader;
import jpcsp.format.PBP;
import jpcsp.format.PSF;
import jpcsp.format.PSP;
import jpcsp.format.PSPModuleInfo;
import jpcsp.util.Utilities;
public class Loader {
private static Loader instance;
private boolean loadedFirstModule;
// Format bits
public final static int FORMAT_UNKNOWN = 0x00;
public final static int FORMAT_ELF = 0x01;
public final static int FORMAT_PRX = 0x02;
public final static int FORMAT_PBP = 0x04;
public final static int FORMAT_SCE = 0x08;
public final static int FORMAT_PSP = 0x10;
public static Loader getInstance() {
if (instance == null)
instance = new Loader();
return instance;
}
private Loader() {
}
public void reset() {
loadedFirstModule = false;
}
/**
* @param pspfilename Example:
* ms0:/PSP/GAME/xxx/EBOOT.PBP
* disc0:/PSP_GAME/SYSDIR/BOOT.BIN
* disc0:/PSP_GAME/SYSDIR/EBOOT.BIN
* xxx:/yyy/zzz.prx
* @param baseAddress should be at least 64-byte aligned,
* or how ever much is the default alignment in pspsysmem.
* @return Always a SceModule object, you should check the
* fileFormat member against the FORMAT_* bits.
* Example: (fileFormat & FORMAT_ELF) == FORMAT_ELF */
public SceModule LoadModule(String pspfilename, ByteBuffer f, int baseAddress) throws IOException {
SceModule module = new SceModule(false);
// init context
int currentOffset = f.position();
module.fileFormat = FORMAT_UNKNOWN;
module.pspfilename = pspfilename;
// safety check
if (f.capacity() - f.position() == 0) {
Emulator.log.error("LoadModule: no data.");
return module;
}
// chain loaders
do {
f.position(currentOffset);
if (LoadPBP(f, module, baseAddress)) {
currentOffset = f.position();
// probably kxploit stub
if (currentOffset == f.limit())
break;
} else if (!loadedFirstModule) {
loadPSF(module);
}
if (module.psf != null) {
Emulator.log.info("PBP meta data :\n" + module.psf);
if (!loadedFirstModule) {
// Set firmware version from PSF embedded in PBP
Emulator.getInstance().setFirmwareVersion(module.psf.getString("PSP_SYSTEM_VER"));
}
}
f.position(currentOffset);
if (LoadSCE(f, module, baseAddress))
break;
f.position(currentOffset);
if (LoadPSP(f, module, baseAddress))
break;
f.position(currentOffset);
if (LoadELF(f, module, baseAddress))
break;
f.position(currentOffset);
LoadUNK(f, module, baseAddress);
} while(false);
return module;
}
private void loadPSF(SceModule module) {
if (module.psf != null)
return;
String filetoload = module.pspfilename;
if (filetoload.startsWith("ms0:"))
filetoload = filetoload.replace("ms0:", "ms0");
// PBP doesn't have a PSF included. Check for one in kxploit directories
File metapbp = null;
File pbpfile = new File(filetoload);
if (pbpfile.getParentFile() == null ||
pbpfile.getParentFile().getParentFile() == null) {
// probably dynamically loading a prx
return;
}
// %__SCE__kxploit
File metadir = new File(pbpfile.getParentFile().getParentFile().getPath()
+ File.separatorChar + "%" + pbpfile.getParentFile().getName());
if (metadir.exists()) {
File[] eboot = metadir.listFiles(new FileFilter() {
@Override
public boolean accept(File arg0) {
return arg0.getName().equalsIgnoreCase("eboot.pbp");
}
});
if (eboot.length > 0)
metapbp = eboot[0];
}
// kxploit%
metadir = new File(pbpfile.getParentFile().getParentFile().getPath()
+ File.separatorChar + pbpfile.getParentFile().getName() + "%");
if (metadir.exists()) {
File[] eboot = metadir.listFiles(new FileFilter() {
@Override
public boolean accept(File arg0) {
return arg0.getName().equalsIgnoreCase("eboot.pbp");
}
});
if (eboot.length > 0)
metapbp = eboot[0];
}
if (metapbp != null) {
// Load PSF embedded in PBP
FileChannel roChannel;
try {
roChannel = new RandomAccessFile(metapbp, "r").getChannel();
ByteBuffer readbuffer = roChannel.map(FileChannel.MapMode.READ_ONLY, 0, (int)roChannel.size());
PBP meta = new PBP(readbuffer);
module.psf = meta.readPSF(readbuffer);
roChannel.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} else {
// Load unpacked PSF in the same directory
File[] psffile = pbpfile.getParentFile().listFiles(new FileFilter() {
@Override
public boolean accept(File arg0) {
return arg0.getName().equalsIgnoreCase("param.sfo");
}
});
if (psffile != null && psffile.length > 0) {
try {
FileChannel roChannel = new RandomAccessFile(psffile[0], "r").getChannel();
ByteBuffer readbuffer = roChannel.map(FileChannel.MapMode.READ_ONLY, 0, (int)roChannel.size());
module.psf = new PSF();
module.psf.read(readbuffer);
roChannel.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/** @return true on success */
private boolean LoadPBP(ByteBuffer f, SceModule module, int baseAddress) throws IOException {
PBP pbp = new PBP(f);
if (pbp.isValid()) {
module.fileFormat |= FORMAT_PBP;
// Dump PSF info
if (pbp.getOffsetParam() > 0) {
module.psf = pbp.readPSF(f);
}
// Dump unpacked PBP
if (Settings.getInstance().readBool("emu.pbpunpack")) {
PBP.unpackPBP(f);
}
// Save PBP info for debugger
ElfHeaderInfo.PbpInfo = pbp.toString();
// Setup position for chaining loaders
f.position((int)pbp.getOffsetPspData());
//Emulator.log.debug("Loader: PBP loaded");
return true;
} else {
// Not a valid PBP
//Emulator.log.debug("Loader: Not a PBP");
return false;
}
}
/** @return true on success */
private boolean LoadSCE(ByteBuffer f, SceModule module, int baseAddress) throws IOException {
long magic = Utilities.readUWord(f);
if (magic == 0x4543537EL) {
module.fileFormat |= FORMAT_SCE;
Emulator.log.warn("Encrypted file not supported! (~SCE)");
return true;
} else {
// Not a valid PSP
return false;
}
}
/** @return true on success */
private boolean LoadPSP(ByteBuffer f, SceModule module, int baseAddress) throws IOException {
PSP psp = new PSP(f);
if (psp.isValid()) {
module.fileFormat |= FORMAT_PSP;
Emulator.log.warn("Encrypted file not supported! (~PSP)");
return true;
} else {
// Not a valid PSP
return false;
}
}
/** @return true on success */
private boolean LoadELF(ByteBuffer f, SceModule module, int baseAddress) throws IOException {
int elfOffset = f.position();
Elf32 elf = new Elf32(f);
if (elf.getHeader().isValid()) {
module.fileFormat |= FORMAT_ELF;
if (!elf.getHeader().isMIPSExecutable()) {
Emulator.log.error("Loader NOT a MIPS executable");
return false;
}
if (elf.getHeader().isPRXDetected()) {
Emulator.log.debug("Loader: Relocation required (PRX)");
module.fileFormat |= FORMAT_PRX;
} else if (elf.getHeader().requiresRelocation()) {
// seen in .elf's generated by pspsdk with BUILD_PRX=1 before conversion to .prx
Emulator.log.info("Loader: Relocation required (ELF)");
} else {
//Emulator.log.debug("Relocation NOT required");
// After the user chooses a game to run and we load it, then
// we can't load another PBP at the same time. We can only load
// relocatable modules (PRX's) after the user loaded app.
if (baseAddress > 0x08900000)
Emulator.log.warn("Loader: Probably trying to load PBP ELF while another PBP ELF is already loaded");
baseAddress = 0;
}
module.baseAddress = baseAddress;
if (elf.getHeader().getE_entry() == 0xFFFFFFFFL) {
module.entry_addr = -1;
} else {
module.entry_addr = baseAddress + (int)elf.getHeader().getE_entry();
}
// Note: baseAddress is 0 unless we are loading a PRX
module.loadAddressLow = (baseAddress != 0) ? (int)baseAddress : 0x08900000;
module.loadAddressHigh = baseAddress;
// Load into mem
LoadELFProgram(f, module, baseAddress, elf, elfOffset);
LoadELFSections(f, module, baseAddress, elf, elfOffset);
// Relocate PRX
if (elf.getHeader().requiresRelocation()) {
relocateFromHeaders(f, module, baseAddress, elf, elfOffset);
}
// The following can only be done after relocation
// Load .rodata.sceModuleInfo
LoadELFModuleInfo(f, module, baseAddress, elf, elfOffset);
// After LoadELFModuleInfo so the we can name the memory allocation after the module name
LoadELFReserveMemory(module);
// Save imports
LoadELFImports(module, baseAddress, elf);
// Save exports
LoadELFExports(module, baseAddress, elf);
// Try to fixup imports for ALL modules
Managers.modules.addModule(module);
ProcessUnresolvedImports();
// Save some debugger stuff
LoadELFDebuggerInfo(f, module, baseAddress, elf, elfOffset);
// Flush module struct to psp mem
module.write(Memory.getInstance(), module.address);
loadedFirstModule = true;
//Emulator.log.debug("Loader: ELF loaded");
return true;
} else {
// Not a valid ELF
Emulator.log.debug("Loader: Not a ELF");
return false;
}
}
/** Dummy loader for unrecognized file formats, put at the end of a loader chain.
* @return true on success */
private boolean LoadUNK(ByteBuffer f, SceModule module, int baseAddress) throws IOException {
byte m0 = f.get();
byte m1 = f.get();
byte m2 = f.get();
byte m3 = f.get();
// catch common user errors
if (m0 == 0x43 && m1 == 0x49 && m2 == 0x53 && m3 == 0x4F) { // CSO
Emulator.log.info("This is not an executable file!");
Emulator.log.info("Try using the Load UMD menu item");
} else if ((m0 == 0 && m1 == 0x50 && m2 == 0x53 && m3 == 0x46)) { // PSF
Emulator.log.info("This is not an executable file!");
} else {
boolean handled = false;
// check for ISO
if (f.limit() >= 16 * 2048 + 6) {
f.position(16 * 2048);
byte[] id = new byte[6];
f.get(id);
if((((char)id[1])=='C')&&
(((char)id[2])=='D')&&
(((char)id[3])=='0')&&
(((char)id[4])=='0')&&
(((char)id[5])=='1'))
{
Emulator.log.info("This is not an executable file!");
Emulator.log.info("Try using the Load UMD menu item");
handled = true;
}
}
if (!handled) {
// print some debug info
Emulator.log.info("Unrecognized file format");
Emulator.log.info(String.format("File magic %02X %02X %02X %02X", m0, m1, m2, m3));
}
}
return false;
}
// ELF Loader
/** Load some programs into memory */
private void LoadELFProgram(ByteBuffer f, SceModule module, int baseAddress,
Elf32 elf, int elfOffset) throws IOException {
List<Elf32ProgramHeader> programHeaderList = elf.getProgramHeaderList();
Memory mem = Memory.getInstance();
int i = 0;
module.bss_size = 0;
for (Elf32ProgramHeader phdr : programHeaderList) {
if (phdr.getP_type() == 0x00000001L) {
int fileOffset = (int)phdr.getP_offset();
int memOffset = baseAddress + (int)phdr.getP_vaddr();
int fileLen = (int)phdr.getP_filesz();
int memLen = (int)phdr.getP_memsz();
Memory.log.debug(String.format("PH#%d: loading program %08X - %08X - %08X", i, memOffset, memOffset + fileLen, memOffset + memLen));
f.position(elfOffset + fileOffset);
if (f.position() + fileLen > f.limit()) {
int newLen = f.limit() - f.position();
Memory.log.warn(String.format("PH#%d: program overflow clamping len %08X to %08X", i, fileLen, newLen));
fileLen = newLen;
}
mem.copyToMemory(memOffset, f, fileLen);
// Update memory area consumed by the module
if (memOffset < module.loadAddressLow) {
module.loadAddressLow = memOffset;
Memory.log.debug(String.format("PH#%d: new loadAddressLow %08X", i, module.loadAddressLow));
}
if (memOffset + memLen > module.loadAddressHigh) {
module.loadAddressHigh = memOffset + memLen;
Memory.log.trace(String.format("PH#%d: new loadAddressHigh %08X", i, module.loadAddressHigh));
}
Memory.log.trace(String.format("PH#%d: contributes %08X to bss size", i, (int)(phdr.getP_memsz() - phdr.getP_filesz())));
module.bss_size += (int)(phdr.getP_memsz() - phdr.getP_filesz());
}
i++;
}
Memory.log.debug(String.format("PH alloc consumption %08X (mem %08X)", (module.loadAddressHigh - module.loadAddressLow), module.bss_size));
}
/** Load some sections into memory */
private void LoadELFSections(ByteBuffer f, SceModule module, int baseAddress,
Elf32 elf, int elfOffset) throws IOException {
List<Elf32SectionHeader> sectionHeaderList = elf.getSectionHeaderList();
Memory mem = Memory.getInstance();
//boolean noBssInSh = true;
for (Elf32SectionHeader shdr : sectionHeaderList) {
if ((shdr.getSh_flags() & Elf32SectionHeader.SHF_ALLOCATE) == Elf32SectionHeader.SHF_ALLOCATE) {
switch (shdr.getSh_type()) {
case Elf32SectionHeader.SHT_PROGBITS: // 1
{
// Load this section into memory
// now loaded using program header type 1
//int fileOffset = elfOffset + (int)shdr.getSh_offset();
int memOffset = baseAddress + (int)shdr.getSh_addr();
int len = (int)shdr.getSh_size();
/*
Memory.log.debug(String.format("%s: loading section %08X - %08X", shdr.getSh_namez(), memOffset, (memOffset + len)));
f.position(fileOffset);
Utilities.copyByteBuffertoByteBuffer(f, mainmemory, memOffset - MemoryMap.START_RAM, len);
*/
// Update memory area consumed by the module
if ((int)(baseAddress + shdr.getSh_addr()) < module.loadAddressLow) {
Memory.log.warn(String.format("%s: section allocates more than program %08X - %08X", shdr.getSh_namez(), memOffset, (memOffset + len)));
module.loadAddressLow = (int)(baseAddress + shdr.getSh_addr());
}
if ((int)(baseAddress + shdr.getSh_addr() + shdr.getSh_size()) > module.loadAddressHigh) {
Memory.log.warn(String.format("%s: section allocates more than program %08X - %08X", shdr.getSh_namez(), memOffset, (memOffset + len)));
module.loadAddressHigh = (int)(baseAddress + shdr.getSh_addr() + shdr.getSh_size());
}
break;
}
case Elf32SectionHeader.SHT_NOBITS: // 8
{
// Zero out this portion of memory
int memOffset = baseAddress + (int)shdr.getSh_addr();
int len = (int)shdr.getSh_size();
if (len == 0) {
Memory.log.debug(String.format("%s: ignoring zero-length type 8 section %08X", shdr.getSh_namez(), memOffset));
} else if (memOffset >= MemoryMap.START_RAM && memOffset + len <= MemoryMap.END_RAM) {
Memory.log.debug(String.format("%s: clearing section %08X - %08X (len %08X)", shdr.getSh_namez(), memOffset, (memOffset + len), len));
mem.memset(memOffset, (byte) 0x0, len);
// Update memory area consumed by the module
if (memOffset < module.loadAddressLow) {
module.loadAddressLow = memOffset;
Memory.log.debug(String.format("%s: new loadAddressLow %08X (+%08X)", shdr.getSh_namez(), module.loadAddressLow, len));
}
if (memOffset + len > module.loadAddressHigh) {
module.loadAddressHigh = memOffset + len;
Memory.log.debug(String.format("%s: new loadAddressHigh %08X (+%08X)", shdr.getSh_namez(), module.loadAddressHigh, len));
}
/*
if (shdr.getSh_namez().equals(".bss")) {
noBssInSh = false;
}
*/
} else {
Memory.log.warn(String.format("Type 8 section outside valid range %08X - %08X", memOffset, (memOffset + len)));
}
break;
}
}
}
}
// TODO completely ignore sh .bss and use only ph .bss?
// If so then maybe we should just be using memsz instead of filesz in LoadELFProgram
/*
if (noBssInSh) {
module.loadAddressHigh += module.bss_size;
Memory.log.debug(String.format(".bss: new loadAddressHigh %08X (+%08X PH extra)", module.loadAddressHigh, module.bss_size));
}
*/
// Save the address/size of some sections for SceModule
Elf32SectionHeader shdr = elf.getSectionHeader(".text");
if (shdr != null) {
Emulator.log.trace(String.format("SH: Storing text size %08X %d", shdr.getSh_size(), shdr.getSh_size()));
module.text_addr = (int)(baseAddress + shdr.getSh_addr());
module.text_size = (int)shdr.getSh_size();
}
shdr = elf.getSectionHeader(".data");
if (shdr != null) {
Emulator.log.trace(String.format("SH: Storing data size %08X %d", shdr.getSh_size(), shdr.getSh_size()));
module.data_size = (int)shdr.getSh_size();
}
shdr = elf.getSectionHeader(".bss");
if (shdr != null && shdr.getSh_size() != 0) {
Emulator.log.trace(String.format("SH: Storing bss size %08X %d", shdr.getSh_size(), shdr.getSh_size()));
if (module.bss_size == (int)shdr.getSh_size()) {
Emulator.log.trace("SH: Same bss size already set");
} else if (module.bss_size > (int)shdr.getSh_size()) {
Emulator.log.trace(String.format("SH: Larger bss size already set (%08X > %08X)", module.bss_size, shdr.getSh_size()));
} else if (module.bss_size != 0) {
Emulator.log.warn(String.format("SH: Overwriting bss size %08X with %08X", module.bss_size, shdr.getSh_size()));
module.bss_size = (int)shdr.getSh_size();
} else {
// Can we even get here? bss size always set from PH first
Emulator.log.info("SH: bss size not already set");
module.bss_size = (int)shdr.getSh_size();
}
}
module.nsegment += 1;
module.segmentaddr[0] = module.loadAddressLow;
module.segmentsize[0] = module.loadAddressHigh - module.loadAddressLow;
}
private void LoadELFReserveMemory(SceModule module) {
// Mark the area of memory the module loaded into as used
Memory.log.debug("Reserving " + (module.loadAddressHigh - module.loadAddressLow) + " bytes at "
+ String.format("%08x", module.loadAddressLow)
+ " for module '" + module.pspfilename + "'");
pspSysMem SysMemUserForUserModule = pspSysMem.getInstance();
int address = module.loadAddressLow & ~0x3F; // round down to nearest 64-bytes to match sysmem allocations
int size = module.loadAddressHigh - address;
int allocatedAddress = SysMemUserForUserModule.malloc(2, pspSysMem.PSP_SMEM_Addr, size, address);
if (allocatedAddress != address) {
Memory.log.warn("Failed to properly reserve memory consumed by module " + module.modname
+ " at address 0x" + Integer.toHexString(address)
+ " size " + size
+ " new address 0x" + Integer.toHexString(allocatedAddress));
}
SysMemUserForUserModule.addSysMemInfo(2, module.modname, pspSysMem.PSP_SMEM_Low, size, allocatedAddress);
}
/** Loads from memory */
private void LoadELFModuleInfo(ByteBuffer f, SceModule module, int baseAddress,
Elf32 elf, int elfOffset) throws IOException {
Elf32ProgramHeader phdr = elf.getProgramHeader(0);
Elf32SectionHeader shdr = elf.getSectionHeader(".rodata.sceModuleInfo");
if (elf.getHeader().isPRXDetected()) {
//int fileOffset = (int)(elfOffset + (phdr.getP_paddr() & 0x7FFFFFFFL));
int memOffset = (int)(baseAddress + (phdr.getP_paddr() & 0x7FFFFFFFL) - phdr.getP_offset());
//Emulator.log.debug(String.format("ModuleInfo file=%08X mem=%08X (PRX)", fileOffset, memOffset));
PSPModuleInfo moduleInfo = new PSPModuleInfo();
//f.position(fileOffset);
//moduleInfo.read(f);
moduleInfo.read(Memory.getInstance(), memOffset);
module.copy(moduleInfo);
} else if (shdr != null) {
//int fileOffset = (int)(elfOffset + shdr.getSh_offset());
int memOffset = (int)(baseAddress + shdr.getSh_addr());
//Emulator.log.debug(String.format("ModuleInfo file=%08X mem=%08X", fileOffset, memOffset));
PSPModuleInfo moduleInfo = new PSPModuleInfo();
//f.position(fileOffset);
//moduleInfo.read(f);
moduleInfo.read(Memory.getInstance(), memOffset);
module.copy(moduleInfo);
} else {
Emulator.log.error("ModuleInfo not found!");
return;
}
Emulator.log.info("Found ModuleInfo name:'" + module.modname
+ "' version:" + String.format("%02x%02x", module.version[1], module.version[0])
+ " attr:" + String.format("%08x", module.attribute)
+ " gp:" + String.format("%08x", module.gp_value));
if ((module.attribute & 0x1000) != 0) {
Emulator.log.warn("Kernel mode module detected");
}
if ((module.attribute & 0x0800) != 0) {
Emulator.log.warn("VSH mode module detected");
}
}
/**
* @param f The position of this buffer must be at the start of a
* list of Elf32Rel structs.
* @param RelCount The number of Elf32Rel structs to read and process.
*/
private void relocateFromBuffer(ByteBuffer f, SceModule module, int baseAddress,
Elf32 elf, int RelCount, Elf32SectionHeader relocatedSection) throws IOException {
// Display a message about untested R_MIPS_NONE only once per section
boolean displayedUntestedR_MIPS_NONE = false;
Elf32Relocate rel = new Elf32Relocate();
int AHL = 0; // (AHI << 16) | (ALO & 0xFFFF)
List<Integer> deferredHi16 = new LinkedList<Integer>(); // We'll use this to relocate R_MIPS_HI16 when we get a R_MIPS_LO16
int nextAddr = 0;
if (relocatedSection != null) {
nextAddr = (int) (relocatedSection.getSh_addr() + baseAddress);
}
Memory mem = Memory.getInstance();
for (int i = 0; i < RelCount; i++) {
rel.read(f);
int R_TYPE = (int)( rel.getR_info() & 0xFF);
int OFS_BASE = (int)((rel.getR_info() >> 8) & 0xFF);
int ADDR_BASE = (int)((rel.getR_info() >> 16) & 0xFF);
if (Memory.log.isTraceEnabled()) {
Memory.log.trace(String.format("Relocation #%d type=%d,base=%08X,addr=%08X", i, R_TYPE, OFS_BASE, ADDR_BASE));
}
int phOffset = (int)elf.getProgramHeader(OFS_BASE).getP_vaddr();
int phBaseOffset = (int)elf.getProgramHeader(ADDR_BASE).getP_vaddr();
// Address of data to relocate
int data_addr = (int)(baseAddress + rel.getR_offset() + phOffset);
// Value of data to relocate
int data = mem.read32(data_addr);
long result = 0; // Used to hold the result of relocation, OR this back into data
// these are the addends?
// SysV ABI MIPS quote: "Because MIPS uses only Elf32_Rel re-location entries, the relocated field holds the addend."
int word32 = data & 0xFFFFFFFF; // <=> data;
int targ26 = data & 0x03FFFFFF;
int hi16 = data & 0x0000FFFF;
int lo16 = data & 0x0000FFFF;
int A = 0; // addend
// moved outside the loop so context is saved
//int AHL = 0; // (AHI << 16) | (ALO & 0xFFFF)
int S = (int) baseAddress + phBaseOffset;
int GP = (int) baseAddress + (int) module.gp_value; // final gp value, computed correctly? 31/07/08 only used in R_MIPS_GPREL16 which is untested (fiveofhearts)
switch (R_TYPE) {
case 0: //R_MIPS_NONE
// Starting at the last relocation address
// (or at the beginning of the section for the first relocation),
// perform a relocation analog to R_MIPS_32 on the first non NULL address.
int value;
while (true) {
value = mem.read32(nextAddr);
if (value != 0) {
break;
}
nextAddr += 4;
}
data_addr = nextAddr;
data = value + S;
if (!displayedUntestedR_MIPS_NONE) {
// I'm not sure about the implementation of the relocation R_MIPS_NONE (gid15).
// This seems to work for the game "Little Britain".
// Display a message to identify which programs are using this relocation type.
Memory.log.info(String.format("Untested relocation of type R_MIPS_NONE addr=%08X", data_addr));
displayedUntestedR_MIPS_NONE = true;
} else if (Memory.log.isTraceEnabled()) {
Memory.log.trace(String.format("R_MIPS_NONE addr=%08X", data_addr));
}
break;
case 5: //R_MIPS_HI16
A = hi16;
AHL = A << 16;
//HI_addr = data_addr;
deferredHi16.add(data_addr);
if (Memory.log.isTraceEnabled()) {
Memory.log.trace(String.format("R_MIPS_HI16 addr=%08X", data_addr));
}
break;
case 6: //R_MIPS_LO16
A = lo16;
AHL &= ~0x0000FFFF; // delete lower bits, since many R_MIPS_LO16 can follow one R_MIPS_HI16
AHL |= A & 0x0000FFFF;
result = AHL + S;
data &= ~0x0000FFFF;
data |= result & 0x0000FFFF; // truncate
// Process deferred R_MIPS_HI16
for (Iterator<Integer> it = deferredHi16.iterator(); it.hasNext();) {
int data_addr2 = it.next();
int data2 = mem.read32(data_addr2);
result = ((data2 & 0x0000FFFF) << 16) + A + S;
// The low order 16 bits are always treated as a signed
// value. Therefore, a negative value in the low order bits
// requires an adjustment in the high order bits. We need
// to make this adjustment in two ways: once for the bits we
// took from the data, and once for the bits we are putting
// back in to the data.
if ((A & 0x8000) != 0)
{
result -= 0x10000;
}
if ((result & 0x8000) != 0)
{
result += 0x10000;
}
data2 &= ~0x0000FFFF;
data2 |= (result >> 16) & 0x0000FFFF; // truncate
if (Memory.log.isTraceEnabled()) {
Memory.log.trace(String.format("R_MIPS_HILO16 addr=%08X before=%08X after=%08X", data_addr2, mem.read32(data_addr2), data2));
}
mem.write32(data_addr2, data2);
it.remove();
}
if (Memory.log.isTraceEnabled()) {
Memory.log.trace(String.format("R_MIPS_LO16 addr=%08X before=%08X after=%08X", data_addr, word32, data));
}
break;
case 4: //R_MIPS_26
A = targ26;
// docs say "sign-extend(A < 2)", but is it meant to be A << 2? if so then there's no point sign extending
//result = (sign-extend(A < 2) + S) >> 2;
//result = (((A < 2) ? 0xFFFFFFFF : 0x00000000) + S) >> 2;
result = ((A << 2) + S) >> 2; // copied from soywiz/pspemulator
data &= ~0x03FFFFFF;
data |= (int) (result & 0x03FFFFFF); // truncate
if (Memory.log.isTraceEnabled()) {
Memory.log.trace(String.format("R_MIPS_26 addr=%08X before=%08X after=%08X", data_addr, word32, data));
}
break;
case 2: //R_MIPS_32
data += S;
if (Memory.log.isTraceEnabled()) {
- Memory.log.trace(String.format("R_MIPS_32 addr=%08X before%%08X after=%08X", data_addr, word32, data));
+ Memory.log.trace(String.format("R_MIPS_32 addr=%08X before=%08X after=%08X", data_addr, word32, data));
}
break;
/* sample before relocation: 0x00015020: 0x8F828008 '....' - lw $v0, -32760($gp)
case 7: //R_MIPS_GPREL16
// 31/07/08 untested (fiveofhearts)
Memory.log.warn("Untested relocation type " + R_TYPE + " at " + String.format("%08x", data_addr));
A = rel16;
//result = sign-extend(A) + S + GP;
result = (((A & 0x00008000) != 0) ? A | 0xFFFF0000 : A) + S + GP;
// verify
if ((result & ~0x0000FFFF) != 0) {
//throw new IOException("Relocation overflow (R_MIPS_GPREL16)");
Memory.log.warn("Relocation overflow (R_MIPS_GPREL16)");
}
data &= ~0x0000FFFF;
data |= (int)(result & 0x0000FFFF);
break;
/* */
default:
Memory.log.warn(String.format("Unhandled relocation type %d at %08X", R_TYPE, data_addr));
break;
}
//System.out.println("Relocation type " + R_TYPE + " at " + String.format("%08x", (int)baseAddress + (int)rel.r_offset));
mem.write32(data_addr, data);
nextAddr = data_addr + 4;
}
}
/** Uses info from the elf program headers and elf section headers to
* relocate a PRX. */
private void relocateFromHeaders(ByteBuffer f, SceModule module, int baseAddress,
Elf32 elf, int elfOffset) throws IOException {
// Relocate from program headers
int i = 0;
for (Elf32ProgramHeader phdr : elf.getProgramHeaderList()) {
if (phdr.getP_type() == 0x700000A0L) {
int RelCount = (int)phdr.getP_filesz() / Elf32Relocate.sizeof();
Memory.log.debug("PH#" + i + ": relocating " + RelCount + " entries");
f.position((int)(elfOffset + phdr.getP_offset()));
relocateFromBuffer(f, module, baseAddress, elf, RelCount, null);
// now skip relocate from section headers
return;
} else if (phdr.getP_type() == 0x700000A1L) {
// Issue 91 Support more relocate format in program headers
// http://forums.ps2dev.org/viewtopic.php?p=80416#80416
Memory.log.warn("Unimplemented:PH#" + i + ": relocate type 0x700000A1");
}
i++;
}
// Relocate from section headers
for (Elf32SectionHeader shdr : elf.getSectionHeaderList()) {
if (shdr.getSh_type() == Elf32SectionHeader.SHT_REL) {
Memory.log.warn(shdr.getSh_namez() + ": not relocating section");
}
if (shdr.getSh_type() == Elf32SectionHeader.SHT_PRXREL /*|| // 0x700000A0
shdr.getSh_type() == Elf32SectionHeader.SHT_REL*/) // 0x00000009
{
int RelCount = (int)shdr.getSh_size() / Elf32Relocate.sizeof();
Memory.log.debug(shdr.getSh_namez() + ": relocating " + RelCount + " entries");
// The INFO field gives the section number of the section relocated
// by this relocation section.
Elf32SectionHeader relocatedSection = elf.getSectionHeader(shdr.getSh_info());
f.position((int)(elfOffset + shdr.getSh_offset()));
relocateFromBuffer(f, module, baseAddress, elf, RelCount, relocatedSection);
}
}
}
private void ProcessUnresolvedImports() {
Memory mem = Memory.getInstance();
NIDMapper nidMapper = NIDMapper.getInstance();
int numberoffailedNIDS = 0;
int numberofmappedNIDS = 0;
for (SceModule module : Managers.modules.values()) {
module.importFixupAttempts++;
for (Iterator<DeferredStub> it = module.unresolvedImports.iterator(); it.hasNext(); ) {
DeferredStub deferredStub = it.next();
String moduleName = deferredStub.getModuleName();
int nid = deferredStub.getNid();
int importAddress = deferredStub.getImportAddress();
int exportAddress;
// Attempt to fixup stub to point to an already loaded module export
exportAddress = nidMapper.moduleNidToAddress(moduleName, nid);
if (exportAddress != -1)
{
int instruction = // j <jumpAddress>
((jpcsp.AllegrexOpcodes.J & 0x3f) << 26)
| ((exportAddress >>> 2) & 0x03ffffff);
mem.write32(importAddress, instruction);
mem.write32(importAddress + 4, 0); // write a nop over our "unmapped import detection special syscall"
it.remove();
numberofmappedNIDS++;
Emulator.log.debug(String.format("Mapped import at 0x%08X to export at 0x%08X [0x%08X] (attempt %d)",
importAddress, exportAddress, nid, module.importFixupAttempts));
}
// Ignore patched nids
else if (nid == 0)
{
Emulator.log.warn(String.format("Ignoring import at 0x%08X [0x%08X] (attempt %d)",
importAddress, nid, module.importFixupAttempts));
it.remove();
mem.write32(importAddress + 4, 0); // write a nop over our "unmapped import detection special syscall"
}
else
{
// Attempt to fixup stub to known syscalls
int code = nidMapper.nidToSyscall(nid);
if (code != -1)
{
// Fixup stub, replacing nop with syscall
int instruction = // syscall <code>
((jpcsp.AllegrexOpcodes.SPECIAL & 0x3f) << 26)
| (jpcsp.AllegrexOpcodes.SYSCALL & 0x3f)
| ((code & 0x000fffff) << 6);
mem.write32(importAddress + 4, instruction);
it.remove();
numberofmappedNIDS++;
// Don't spam mappings on the first module (the one the user loads)
if (loadedFirstModule) {
Emulator.log.debug(String.format("Mapped import at 0x%08X to syscall 0x%05X [0x%08X] (attempt %d)",
importAddress, code, nid, module.importFixupAttempts));
}
}
// Save for later
else
{
Emulator.log.warn(String.format("Failed to map import at 0x%08X [0x%08X] (attempt %d)",
importAddress, nid, module.importFixupAttempts));
numberoffailedNIDS++;
}
}
}
}
Emulator.log.info(numberofmappedNIDS + " NIDS mapped");
if (numberoffailedNIDS > 0)
Emulator.log.info(numberoffailedNIDS + " remaining unmapped NIDS");
}
/* Loads from memory */
private void LoadELFImports(SceModule module, int baseAddress, Elf32 elf) throws IOException {
Memory mem = Memory.getInstance();
int stubHeadersAddress;
int stubHeadersCount;
if (false) {
// Old: from file, from sections
Elf32SectionHeader shdr = elf.getSectionHeader(".lib.stub");
if (shdr == null) {
Emulator.log.warn("Failed to find .lib.stub section");
return;
}
stubHeadersAddress = (int)(baseAddress + shdr.getSh_addr());
stubHeadersCount = (int)(shdr.getSh_size() / Elf32StubHeader.sizeof());
//System.out.println(shdr.getSh_namez() + ":" + stubsCount + " module entries");
} else {
// New: from memory, from module info
stubHeadersAddress = module.stub_top;
stubHeadersCount = module.stub_size / Elf32StubHeader.sizeof();
}
// n modules to import, 1 stub header per module to import
for (int i = 0; i < stubHeadersCount; i++)
{
Elf32StubHeader stubHeader = new Elf32StubHeader(mem, stubHeadersAddress);
stubHeader.setModuleNamez(Utilities.readStringNZ((int)stubHeader.getOffsetModuleName(), 64));
if(stubHeader.getSize() > 5) {
stubHeadersAddress += stubHeader.getSize() * 4;
Emulator.log.warn("'" + stubHeader.getModuleNamez() + "' has size " + stubHeader.getSize());
}
else
stubHeadersAddress += Elf32StubHeader.sizeof();
// n stubs per module to import
for (int j = 0; j < stubHeader.getImports(); j++)
{
int nid = mem.read32((int)(stubHeader.getOffsetNid() + j * 4));
int importAddress = (int)(stubHeader.getOffsetText() + j * 8);
DeferredStub deferredStub = new DeferredStub(stubHeader.getModuleNamez(), importAddress, nid);
module.unresolvedImports.add(deferredStub);
// Add a 0xfffff syscall so we can detect if an unresolved import is called
int instruction = // syscall <code>
((jpcsp.AllegrexOpcodes.SPECIAL & 0x3f) << 26)
| (jpcsp.AllegrexOpcodes.SYSCALL & 0x3f)
| ((0xfffff & 0x000fffff) << 6);
mem.write32(importAddress + 4, instruction);
}
}
Emulator.log.info("Found " + module.unresolvedImports.size() + " imports from " + stubHeadersCount + " modules");
}
/* Loads from memory */
private void LoadELFExports(SceModule module, int baseAddress, Elf32 elf) throws IOException {
NIDMapper nidMapper = NIDMapper.getInstance();
Memory mem = Memory.getInstance();
int entHeadersAddress;
int entHeadersCount;
int entCount = 0;
if (false) {
// Old: from file, from sections
Elf32SectionHeader shdr = elf.getSectionHeader(".lib.ent");
if (shdr == null) {
Emulator.log.warn("Failed to find .lib.ent section");
return;
}
entHeadersAddress = (int)(baseAddress + shdr.getSh_addr());
entHeadersCount = (int)(shdr.getSh_size() / Elf32EntHeader.sizeof());
//System.out.println(shdr.getSh_namez() + ":" + stubsCount + " module entries");
} else {
// New: from memory, from module info
entHeadersAddress = module.ent_top;
entHeadersCount = module.ent_size / Elf32EntHeader.sizeof();
}
// n modules to export, 1 ent header per module to import
String moduleName;
for (int i = 0; i < entHeadersCount; i++)
{
Elf32EntHeader entHeader = new Elf32EntHeader(mem, entHeadersAddress);
if (entHeader.getOffsetModuleName() != 0) {
moduleName = Utilities.readStringNZ((int) entHeader.getOffsetModuleName(), 64);
} else {
// Generate a module name
moduleName = module.modname;
}
entHeader.setModuleNamez(moduleName);
entHeadersAddress += Elf32EntHeader.sizeof(); //entHeader.size * 4;
//System.out.println(entHeader.toString());
// n ents per module to export
int functionCount = entHeader.getFunctionCount();
for (int j = 0; j < functionCount; j++)
{
int nid = mem.read32((int)(entHeader.getOffsetResident() + j * 4));
int exportAddress = mem.read32((int)(entHeader.getOffsetResident() + (j + functionCount) * 4));
switch(nid) {
// magic export nids from yapspd
case 0xd3744be0: // module_bootstart
case 0x2f064fa6: // module_reboot_before
case 0xadf12745: // module_reboot_phase
case 0xd632acdb: // module_start
case 0xcee8593c: // module_stop
case 0xf01d73a7: // module_stop
case 0x0f7c276c: // ?
// Ignore magic exports
break;
default:
// Save export
nidMapper.addModuleNid(moduleName, nid, exportAddress);
break;
}
entCount++;
Emulator.log.debug(String.format("Export found at 0x%08X [0x%08X]", exportAddress, nid));
}
}
if (entCount > 0)
Emulator.log.info("Found " + entCount + " exports");
}
private void LoadELFDebuggerInfo(ByteBuffer f, SceModule module, int baseAddress,
Elf32 elf, int elfOffset) throws IOException {
// Save executable section address/size for the debugger/instruction counter
Elf32SectionHeader shdr;
// .text moved to module.text_addr/module.text_size, assigned in LoadELFSections
shdr = elf.getSectionHeader(".init");
if (shdr != null)
{
module.initsection[0] = (int)(baseAddress + shdr.getSh_addr());
module.initsection[1] = (int)shdr.getSh_size();
}
shdr = elf.getSectionHeader(".fini");
if (shdr != null)
{
module.finisection[0] = (int)(baseAddress + shdr.getSh_addr());
module.finisection[1] = (int)shdr.getSh_size();
}
shdr = elf.getSectionHeader(".sceStub.text");
if (shdr != null)
{
module.stubtextsection[0] = (int)(baseAddress + shdr.getSh_addr());
module.stubtextsection[1] = (int)shdr.getSh_size();
}
// test the instruction counter
//if (/*shdr.getSh_namez().equals(".text") || */shdr.getSh_namez().equals(".init") /*|| shdr.getSh_namez().equals(".fini")*/) {
/*
int sectionAddress = (int)(baseAddress + shdr.getSh_addr());
System.out.println(Integer.toHexString(sectionAddress) + " size = " + shdr.getSh_size());
for(int i =0; i< shdr.getSh_size(); i+=4)
{
int memread32 = Memory.getInstance().read32(sectionAddress+i);
//System.out.println(memread32);
jpcsp.Allegrex.Decoder.instruction(memread32).increaseCount();
}
}
System.out.println(jpcsp.Allegrex.Instructions.ADDIU.getCount());
*/
// Only do this for the app the user loads and not any prx's loaded
// later, otherwise the last loaded module overwrites previous saved info.
// TODO save debugger info for all loaded modules
if (!loadedFirstModule) {
// Set ELF info in the debugger
ElfHeaderInfo.ElfInfo = elf.getElfInfo();
ElfHeaderInfo.ProgInfo = elf.getProgInfo();
ElfHeaderInfo.SectInfo = elf.getSectInfo();
}
}
}
| true | true | private void relocateFromBuffer(ByteBuffer f, SceModule module, int baseAddress,
Elf32 elf, int RelCount, Elf32SectionHeader relocatedSection) throws IOException {
// Display a message about untested R_MIPS_NONE only once per section
boolean displayedUntestedR_MIPS_NONE = false;
Elf32Relocate rel = new Elf32Relocate();
int AHL = 0; // (AHI << 16) | (ALO & 0xFFFF)
List<Integer> deferredHi16 = new LinkedList<Integer>(); // We'll use this to relocate R_MIPS_HI16 when we get a R_MIPS_LO16
int nextAddr = 0;
if (relocatedSection != null) {
nextAddr = (int) (relocatedSection.getSh_addr() + baseAddress);
}
Memory mem = Memory.getInstance();
for (int i = 0; i < RelCount; i++) {
rel.read(f);
int R_TYPE = (int)( rel.getR_info() & 0xFF);
int OFS_BASE = (int)((rel.getR_info() >> 8) & 0xFF);
int ADDR_BASE = (int)((rel.getR_info() >> 16) & 0xFF);
if (Memory.log.isTraceEnabled()) {
Memory.log.trace(String.format("Relocation #%d type=%d,base=%08X,addr=%08X", i, R_TYPE, OFS_BASE, ADDR_BASE));
}
int phOffset = (int)elf.getProgramHeader(OFS_BASE).getP_vaddr();
int phBaseOffset = (int)elf.getProgramHeader(ADDR_BASE).getP_vaddr();
// Address of data to relocate
int data_addr = (int)(baseAddress + rel.getR_offset() + phOffset);
// Value of data to relocate
int data = mem.read32(data_addr);
long result = 0; // Used to hold the result of relocation, OR this back into data
// these are the addends?
// SysV ABI MIPS quote: "Because MIPS uses only Elf32_Rel re-location entries, the relocated field holds the addend."
int word32 = data & 0xFFFFFFFF; // <=> data;
int targ26 = data & 0x03FFFFFF;
int hi16 = data & 0x0000FFFF;
int lo16 = data & 0x0000FFFF;
int A = 0; // addend
// moved outside the loop so context is saved
//int AHL = 0; // (AHI << 16) | (ALO & 0xFFFF)
int S = (int) baseAddress + phBaseOffset;
int GP = (int) baseAddress + (int) module.gp_value; // final gp value, computed correctly? 31/07/08 only used in R_MIPS_GPREL16 which is untested (fiveofhearts)
switch (R_TYPE) {
case 0: //R_MIPS_NONE
// Starting at the last relocation address
// (or at the beginning of the section for the first relocation),
// perform a relocation analog to R_MIPS_32 on the first non NULL address.
int value;
while (true) {
value = mem.read32(nextAddr);
if (value != 0) {
break;
}
nextAddr += 4;
}
data_addr = nextAddr;
data = value + S;
if (!displayedUntestedR_MIPS_NONE) {
// I'm not sure about the implementation of the relocation R_MIPS_NONE (gid15).
// This seems to work for the game "Little Britain".
// Display a message to identify which programs are using this relocation type.
Memory.log.info(String.format("Untested relocation of type R_MIPS_NONE addr=%08X", data_addr));
displayedUntestedR_MIPS_NONE = true;
} else if (Memory.log.isTraceEnabled()) {
Memory.log.trace(String.format("R_MIPS_NONE addr=%08X", data_addr));
}
break;
case 5: //R_MIPS_HI16
A = hi16;
AHL = A << 16;
//HI_addr = data_addr;
deferredHi16.add(data_addr);
if (Memory.log.isTraceEnabled()) {
Memory.log.trace(String.format("R_MIPS_HI16 addr=%08X", data_addr));
}
break;
case 6: //R_MIPS_LO16
A = lo16;
AHL &= ~0x0000FFFF; // delete lower bits, since many R_MIPS_LO16 can follow one R_MIPS_HI16
AHL |= A & 0x0000FFFF;
result = AHL + S;
data &= ~0x0000FFFF;
data |= result & 0x0000FFFF; // truncate
// Process deferred R_MIPS_HI16
for (Iterator<Integer> it = deferredHi16.iterator(); it.hasNext();) {
int data_addr2 = it.next();
int data2 = mem.read32(data_addr2);
result = ((data2 & 0x0000FFFF) << 16) + A + S;
// The low order 16 bits are always treated as a signed
// value. Therefore, a negative value in the low order bits
// requires an adjustment in the high order bits. We need
// to make this adjustment in two ways: once for the bits we
// took from the data, and once for the bits we are putting
// back in to the data.
if ((A & 0x8000) != 0)
{
result -= 0x10000;
}
if ((result & 0x8000) != 0)
{
result += 0x10000;
}
data2 &= ~0x0000FFFF;
data2 |= (result >> 16) & 0x0000FFFF; // truncate
if (Memory.log.isTraceEnabled()) {
Memory.log.trace(String.format("R_MIPS_HILO16 addr=%08X before=%08X after=%08X", data_addr2, mem.read32(data_addr2), data2));
}
mem.write32(data_addr2, data2);
it.remove();
}
if (Memory.log.isTraceEnabled()) {
Memory.log.trace(String.format("R_MIPS_LO16 addr=%08X before=%08X after=%08X", data_addr, word32, data));
}
break;
case 4: //R_MIPS_26
A = targ26;
// docs say "sign-extend(A < 2)", but is it meant to be A << 2? if so then there's no point sign extending
//result = (sign-extend(A < 2) + S) >> 2;
//result = (((A < 2) ? 0xFFFFFFFF : 0x00000000) + S) >> 2;
result = ((A << 2) + S) >> 2; // copied from soywiz/pspemulator
data &= ~0x03FFFFFF;
data |= (int) (result & 0x03FFFFFF); // truncate
if (Memory.log.isTraceEnabled()) {
Memory.log.trace(String.format("R_MIPS_26 addr=%08X before=%08X after=%08X", data_addr, word32, data));
}
break;
case 2: //R_MIPS_32
data += S;
if (Memory.log.isTraceEnabled()) {
Memory.log.trace(String.format("R_MIPS_32 addr=%08X before%%08X after=%08X", data_addr, word32, data));
}
break;
/* sample before relocation: 0x00015020: 0x8F828008 '....' - lw $v0, -32760($gp)
case 7: //R_MIPS_GPREL16
// 31/07/08 untested (fiveofhearts)
Memory.log.warn("Untested relocation type " + R_TYPE + " at " + String.format("%08x", data_addr));
A = rel16;
//result = sign-extend(A) + S + GP;
result = (((A & 0x00008000) != 0) ? A | 0xFFFF0000 : A) + S + GP;
// verify
if ((result & ~0x0000FFFF) != 0) {
//throw new IOException("Relocation overflow (R_MIPS_GPREL16)");
Memory.log.warn("Relocation overflow (R_MIPS_GPREL16)");
}
data &= ~0x0000FFFF;
data |= (int)(result & 0x0000FFFF);
break;
/* */
default:
Memory.log.warn(String.format("Unhandled relocation type %d at %08X", R_TYPE, data_addr));
break;
}
//System.out.println("Relocation type " + R_TYPE + " at " + String.format("%08x", (int)baseAddress + (int)rel.r_offset));
mem.write32(data_addr, data);
nextAddr = data_addr + 4;
}
}
| private void relocateFromBuffer(ByteBuffer f, SceModule module, int baseAddress,
Elf32 elf, int RelCount, Elf32SectionHeader relocatedSection) throws IOException {
// Display a message about untested R_MIPS_NONE only once per section
boolean displayedUntestedR_MIPS_NONE = false;
Elf32Relocate rel = new Elf32Relocate();
int AHL = 0; // (AHI << 16) | (ALO & 0xFFFF)
List<Integer> deferredHi16 = new LinkedList<Integer>(); // We'll use this to relocate R_MIPS_HI16 when we get a R_MIPS_LO16
int nextAddr = 0;
if (relocatedSection != null) {
nextAddr = (int) (relocatedSection.getSh_addr() + baseAddress);
}
Memory mem = Memory.getInstance();
for (int i = 0; i < RelCount; i++) {
rel.read(f);
int R_TYPE = (int)( rel.getR_info() & 0xFF);
int OFS_BASE = (int)((rel.getR_info() >> 8) & 0xFF);
int ADDR_BASE = (int)((rel.getR_info() >> 16) & 0xFF);
if (Memory.log.isTraceEnabled()) {
Memory.log.trace(String.format("Relocation #%d type=%d,base=%08X,addr=%08X", i, R_TYPE, OFS_BASE, ADDR_BASE));
}
int phOffset = (int)elf.getProgramHeader(OFS_BASE).getP_vaddr();
int phBaseOffset = (int)elf.getProgramHeader(ADDR_BASE).getP_vaddr();
// Address of data to relocate
int data_addr = (int)(baseAddress + rel.getR_offset() + phOffset);
// Value of data to relocate
int data = mem.read32(data_addr);
long result = 0; // Used to hold the result of relocation, OR this back into data
// these are the addends?
// SysV ABI MIPS quote: "Because MIPS uses only Elf32_Rel re-location entries, the relocated field holds the addend."
int word32 = data & 0xFFFFFFFF; // <=> data;
int targ26 = data & 0x03FFFFFF;
int hi16 = data & 0x0000FFFF;
int lo16 = data & 0x0000FFFF;
int A = 0; // addend
// moved outside the loop so context is saved
//int AHL = 0; // (AHI << 16) | (ALO & 0xFFFF)
int S = (int) baseAddress + phBaseOffset;
int GP = (int) baseAddress + (int) module.gp_value; // final gp value, computed correctly? 31/07/08 only used in R_MIPS_GPREL16 which is untested (fiveofhearts)
switch (R_TYPE) {
case 0: //R_MIPS_NONE
// Starting at the last relocation address
// (or at the beginning of the section for the first relocation),
// perform a relocation analog to R_MIPS_32 on the first non NULL address.
int value;
while (true) {
value = mem.read32(nextAddr);
if (value != 0) {
break;
}
nextAddr += 4;
}
data_addr = nextAddr;
data = value + S;
if (!displayedUntestedR_MIPS_NONE) {
// I'm not sure about the implementation of the relocation R_MIPS_NONE (gid15).
// This seems to work for the game "Little Britain".
// Display a message to identify which programs are using this relocation type.
Memory.log.info(String.format("Untested relocation of type R_MIPS_NONE addr=%08X", data_addr));
displayedUntestedR_MIPS_NONE = true;
} else if (Memory.log.isTraceEnabled()) {
Memory.log.trace(String.format("R_MIPS_NONE addr=%08X", data_addr));
}
break;
case 5: //R_MIPS_HI16
A = hi16;
AHL = A << 16;
//HI_addr = data_addr;
deferredHi16.add(data_addr);
if (Memory.log.isTraceEnabled()) {
Memory.log.trace(String.format("R_MIPS_HI16 addr=%08X", data_addr));
}
break;
case 6: //R_MIPS_LO16
A = lo16;
AHL &= ~0x0000FFFF; // delete lower bits, since many R_MIPS_LO16 can follow one R_MIPS_HI16
AHL |= A & 0x0000FFFF;
result = AHL + S;
data &= ~0x0000FFFF;
data |= result & 0x0000FFFF; // truncate
// Process deferred R_MIPS_HI16
for (Iterator<Integer> it = deferredHi16.iterator(); it.hasNext();) {
int data_addr2 = it.next();
int data2 = mem.read32(data_addr2);
result = ((data2 & 0x0000FFFF) << 16) + A + S;
// The low order 16 bits are always treated as a signed
// value. Therefore, a negative value in the low order bits
// requires an adjustment in the high order bits. We need
// to make this adjustment in two ways: once for the bits we
// took from the data, and once for the bits we are putting
// back in to the data.
if ((A & 0x8000) != 0)
{
result -= 0x10000;
}
if ((result & 0x8000) != 0)
{
result += 0x10000;
}
data2 &= ~0x0000FFFF;
data2 |= (result >> 16) & 0x0000FFFF; // truncate
if (Memory.log.isTraceEnabled()) {
Memory.log.trace(String.format("R_MIPS_HILO16 addr=%08X before=%08X after=%08X", data_addr2, mem.read32(data_addr2), data2));
}
mem.write32(data_addr2, data2);
it.remove();
}
if (Memory.log.isTraceEnabled()) {
Memory.log.trace(String.format("R_MIPS_LO16 addr=%08X before=%08X after=%08X", data_addr, word32, data));
}
break;
case 4: //R_MIPS_26
A = targ26;
// docs say "sign-extend(A < 2)", but is it meant to be A << 2? if so then there's no point sign extending
//result = (sign-extend(A < 2) + S) >> 2;
//result = (((A < 2) ? 0xFFFFFFFF : 0x00000000) + S) >> 2;
result = ((A << 2) + S) >> 2; // copied from soywiz/pspemulator
data &= ~0x03FFFFFF;
data |= (int) (result & 0x03FFFFFF); // truncate
if (Memory.log.isTraceEnabled()) {
Memory.log.trace(String.format("R_MIPS_26 addr=%08X before=%08X after=%08X", data_addr, word32, data));
}
break;
case 2: //R_MIPS_32
data += S;
if (Memory.log.isTraceEnabled()) {
Memory.log.trace(String.format("R_MIPS_32 addr=%08X before=%08X after=%08X", data_addr, word32, data));
}
break;
/* sample before relocation: 0x00015020: 0x8F828008 '....' - lw $v0, -32760($gp)
case 7: //R_MIPS_GPREL16
// 31/07/08 untested (fiveofhearts)
Memory.log.warn("Untested relocation type " + R_TYPE + " at " + String.format("%08x", data_addr));
A = rel16;
//result = sign-extend(A) + S + GP;
result = (((A & 0x00008000) != 0) ? A | 0xFFFF0000 : A) + S + GP;
// verify
if ((result & ~0x0000FFFF) != 0) {
//throw new IOException("Relocation overflow (R_MIPS_GPREL16)");
Memory.log.warn("Relocation overflow (R_MIPS_GPREL16)");
}
data &= ~0x0000FFFF;
data |= (int)(result & 0x0000FFFF);
break;
/* */
default:
Memory.log.warn(String.format("Unhandled relocation type %d at %08X", R_TYPE, data_addr));
break;
}
//System.out.println("Relocation type " + R_TYPE + " at " + String.format("%08x", (int)baseAddress + (int)rel.r_offset));
mem.write32(data_addr, data);
nextAddr = data_addr + 4;
}
}
|
diff --git a/activemq-core/src/main/java/org/apache/activemq/security/AuthorizationBroker.java b/activemq-core/src/main/java/org/apache/activemq/security/AuthorizationBroker.java
index 9fd954a6b..77135f1ec 100644
--- a/activemq-core/src/main/java/org/apache/activemq/security/AuthorizationBroker.java
+++ b/activemq-core/src/main/java/org/apache/activemq/security/AuthorizationBroker.java
@@ -1,229 +1,229 @@
/**
*
* 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.activemq.security;
import org.apache.activemq.broker.Broker;
import org.apache.activemq.broker.BrokerFilter;
import org.apache.activemq.broker.ConnectionContext;
import org.apache.activemq.broker.region.Destination;
import org.apache.activemq.broker.region.Subscription;
import org.apache.activemq.command.ActiveMQDestination;
import org.apache.activemq.command.ActiveMQQueue;
import org.apache.activemq.command.ActiveMQTempDestination;
import org.apache.activemq.command.ActiveMQTopic;
import org.apache.activemq.command.ConsumerInfo;
import org.apache.activemq.command.Message;
import org.apache.activemq.command.ProducerInfo;
import org.apache.activemq.filter.BooleanExpression;
import org.apache.activemq.filter.MessageEvaluationContext;
import javax.jms.JMSException;
import java.util.Set;
/**
* Verifies if a authenticated user can do an operation against the broker using an authorization map.
*
* @version $Revision$
*/
public class AuthorizationBroker extends BrokerFilter implements SecurityAdminMBean {
private final AuthorizationMap authorizationMap;
public AuthorizationBroker(Broker next, AuthorizationMap authorizationMap) {
super(next);
this.authorizationMap = authorizationMap;
}
public Destination addDestination(ConnectionContext context, ActiveMQDestination destination) throws Exception {
final SecurityContext securityContext = (SecurityContext) context.getSecurityContext();
if( securityContext == null )
throw new SecurityException("User is not authenticated.");
//if(!((ActiveMQTempDestination)destination).getConnectionId().equals(context.getConnectionId().getValue()) ) {
if (!securityContext.isBrokerContext()) {
Set allowedACLs = null;
if(!destination.isTemporary()) {
allowedACLs = authorizationMap.getAdminACLs(destination);
} else {
allowedACLs = authorizationMap.getTempDestinationAdminACLs();
}
if(allowedACLs!=null && !securityContext.isInOneOf(allowedACLs))
throw new SecurityException("User "+securityContext.getUserName()+" is not authorized to create: "+destination);
}
// }
return super.addDestination(context, destination);
}
public void removeDestination(ConnectionContext context, ActiveMQDestination destination, long timeout) throws Exception {
final SecurityContext securityContext = (SecurityContext) context.getSecurityContext();
if( securityContext == null )
throw new SecurityException("User is not authenticated.");
Set allowedACLs = null;
if(!destination.isTemporary()) {
allowedACLs = authorizationMap.getAdminACLs(destination);
} else {
allowedACLs = authorizationMap.getTempDestinationAdminACLs();
}
if(allowedACLs!=null && !securityContext.isInOneOf(allowedACLs))
throw new SecurityException("User "+securityContext.getUserName()+" is not authorized to remove: "+destination);
super.removeDestination(context, destination, timeout);
}
public Subscription addConsumer(ConnectionContext context, ConsumerInfo info) throws Exception {
final SecurityContext subject = (SecurityContext) context.getSecurityContext();
if( subject == null )
throw new SecurityException("User is not authenticated.");
Set allowedACLs = null;
if(!info.getDestination().isTemporary()) {
allowedACLs = authorizationMap.getReadACLs(info.getDestination());
}else {
- allowedACLs = authorizationMap.getTempDestinationWriteACLs();
+ allowedACLs = authorizationMap.getTempDestinationReadACLs();
}
if(allowedACLs!=null && !subject.isInOneOf(allowedACLs))
throw new SecurityException("User "+subject.getUserName()+" is not authorized to read from: "+info.getDestination());
subject.getAuthorizedReadDests().put(info.getDestination(), info.getDestination());
/*
* Need to think about this a little more. We could do per message security checking
* to implement finer grained security checking. For example a user can only see messages
* with price>1000 . Perhaps this should just be another additional broker filter that installs
* this type of feature.
*
* If we did want to do that, then we would install a predicate. We should be careful since
* there may be an existing predicate already assigned and the consumer info may be sent to a remote
* broker, so it also needs to support being marshaled.
*
info.setAdditionalPredicate(new BooleanExpression() {
public boolean matches(MessageEvaluationContext message) throws JMSException {
if( !subject.getAuthorizedReadDests().contains(message.getDestination()) ) {
Set allowedACLs = authorizationMap.getReadACLs(message.getDestination());
if(allowedACLs!=null && !subject.isInOneOf(allowedACLs))
return false;
subject.getAuthorizedReadDests().put(message.getDestination(), message.getDestination());
}
return true;
}
public Object evaluate(MessageEvaluationContext message) throws JMSException {
return matches(message) ? Boolean.TRUE : Boolean.FALSE;
}
});
*/
return super.addConsumer(context, info);
}
public void addProducer(ConnectionContext context, ProducerInfo info) throws Exception {
SecurityContext subject = (SecurityContext) context.getSecurityContext();
if( subject == null )
throw new SecurityException("User is not authenticated.");
if( info.getDestination()!=null ) {
Set allowedACLs = null;
if(!info.getDestination().isTemporary()) {
allowedACLs = authorizationMap.getWriteACLs(info.getDestination());
}else {
allowedACLs = authorizationMap.getTempDestinationWriteACLs();
}
if(allowedACLs!=null && !subject.isInOneOf(allowedACLs))
throw new SecurityException("User "+subject.getUserName()+" is not authorized to write to: "+info.getDestination());
subject.getAuthorizedWriteDests().put(info.getDestination(), info.getDestination());
}
super.addProducer(context, info);
}
public void send(ConnectionContext context, Message messageSend) throws Exception {
SecurityContext subject = (SecurityContext) context.getSecurityContext();
if( subject == null )
throw new SecurityException("User is not authenticated.");
if( !subject.getAuthorizedWriteDests().contains(messageSend.getDestination()) ) {
Set allowedACLs = null;
if(!messageSend.getDestination().isTemporary()) {
allowedACLs = authorizationMap.getWriteACLs(messageSend.getDestination());
}else {
allowedACLs = authorizationMap.getTempDestinationWriteACLs();
}
if(allowedACLs!=null && !subject.isInOneOf(allowedACLs))
throw new SecurityException("User "+subject.getUserName()+" is not authorized to write to: "+messageSend.getDestination());
subject.getAuthorizedWriteDests().put(messageSend.getDestination(), messageSend.getDestination());
}
super.send(context, messageSend);
}
// SecurityAdminMBean interface
// -------------------------------------------------------------------------
public void addQueueRole(String queue, String operation, String role) {
addDestinationRole(new ActiveMQQueue(queue), operation, role);
}
public void addTopicRole(String topic, String operation, String role) {
addDestinationRole(new ActiveMQTopic(topic), operation, role);
}
public void removeQueueRole(String queue, String operation, String role) {
removeDestinationRole(new ActiveMQQueue(queue), operation, role);
}
public void removeTopicRole(String topic, String operation, String role) {
removeDestinationRole(new ActiveMQTopic(topic), operation, role);
}
public void addDestinationRole(javax.jms.Destination destination, String operation, String role) {
}
public void removeDestinationRole(javax.jms.Destination destination, String operation, String role) {
}
public void addRole(String role) {
}
public void addUserRole(String user, String role) {
}
public void removeRole(String role) {
}
public void removeUserRole(String user, String role) {
}
}
| true | true | public Subscription addConsumer(ConnectionContext context, ConsumerInfo info) throws Exception {
final SecurityContext subject = (SecurityContext) context.getSecurityContext();
if( subject == null )
throw new SecurityException("User is not authenticated.");
Set allowedACLs = null;
if(!info.getDestination().isTemporary()) {
allowedACLs = authorizationMap.getReadACLs(info.getDestination());
}else {
allowedACLs = authorizationMap.getTempDestinationWriteACLs();
}
if(allowedACLs!=null && !subject.isInOneOf(allowedACLs))
throw new SecurityException("User "+subject.getUserName()+" is not authorized to read from: "+info.getDestination());
subject.getAuthorizedReadDests().put(info.getDestination(), info.getDestination());
/*
* Need to think about this a little more. We could do per message security checking
* to implement finer grained security checking. For example a user can only see messages
* with price>1000 . Perhaps this should just be another additional broker filter that installs
* this type of feature.
*
* If we did want to do that, then we would install a predicate. We should be careful since
* there may be an existing predicate already assigned and the consumer info may be sent to a remote
* broker, so it also needs to support being marshaled.
*
info.setAdditionalPredicate(new BooleanExpression() {
public boolean matches(MessageEvaluationContext message) throws JMSException {
if( !subject.getAuthorizedReadDests().contains(message.getDestination()) ) {
Set allowedACLs = authorizationMap.getReadACLs(message.getDestination());
if(allowedACLs!=null && !subject.isInOneOf(allowedACLs))
return false;
subject.getAuthorizedReadDests().put(message.getDestination(), message.getDestination());
}
return true;
}
public Object evaluate(MessageEvaluationContext message) throws JMSException {
return matches(message) ? Boolean.TRUE : Boolean.FALSE;
}
});
*/
return super.addConsumer(context, info);
}
| public Subscription addConsumer(ConnectionContext context, ConsumerInfo info) throws Exception {
final SecurityContext subject = (SecurityContext) context.getSecurityContext();
if( subject == null )
throw new SecurityException("User is not authenticated.");
Set allowedACLs = null;
if(!info.getDestination().isTemporary()) {
allowedACLs = authorizationMap.getReadACLs(info.getDestination());
}else {
allowedACLs = authorizationMap.getTempDestinationReadACLs();
}
if(allowedACLs!=null && !subject.isInOneOf(allowedACLs))
throw new SecurityException("User "+subject.getUserName()+" is not authorized to read from: "+info.getDestination());
subject.getAuthorizedReadDests().put(info.getDestination(), info.getDestination());
/*
* Need to think about this a little more. We could do per message security checking
* to implement finer grained security checking. For example a user can only see messages
* with price>1000 . Perhaps this should just be another additional broker filter that installs
* this type of feature.
*
* If we did want to do that, then we would install a predicate. We should be careful since
* there may be an existing predicate already assigned and the consumer info may be sent to a remote
* broker, so it also needs to support being marshaled.
*
info.setAdditionalPredicate(new BooleanExpression() {
public boolean matches(MessageEvaluationContext message) throws JMSException {
if( !subject.getAuthorizedReadDests().contains(message.getDestination()) ) {
Set allowedACLs = authorizationMap.getReadACLs(message.getDestination());
if(allowedACLs!=null && !subject.isInOneOf(allowedACLs))
return false;
subject.getAuthorizedReadDests().put(message.getDestination(), message.getDestination());
}
return true;
}
public Object evaluate(MessageEvaluationContext message) throws JMSException {
return matches(message) ? Boolean.TRUE : Boolean.FALSE;
}
});
*/
return super.addConsumer(context, info);
}
|
diff --git a/src/r/builtins/Builtin.java b/src/r/builtins/Builtin.java
index ca4ab58..f725acc 100644
--- a/src/r/builtins/Builtin.java
+++ b/src/r/builtins/Builtin.java
@@ -1,109 +1,109 @@
package r.builtins;
import r.data.*;
import r.errors.*;
import r.nodes.*;
import r.nodes.truffle.*;
import com.oracle.truffle.api.frame.*;
import com.oracle.truffle.api.nodes.*;
/** The base class for builtin functions. */
public abstract class Builtin extends AbstractCall {
public Builtin(ASTNode orig, RSymbol[] argNames, RNode[] argExprs) {
super(orig, argNames, argExprs);
}
/** Builtin functions with no arguments. */
abstract static class BuiltIn0 extends Builtin {
public BuiltIn0(ASTNode orig, RSymbol[] argNames, RNode[] argExprs) {
super(orig, argNames, argExprs);
}
@Override public final Object execute(Frame frame) {
return doBuiltIn(frame);
}
public abstract RAny doBuiltIn(Frame frame);
@Override public final RAny doBuiltIn(Frame frame, RAny[] params) {
return doBuiltIn(frame);
}
}
/** Builtin functions of one argument. */
abstract static class BuiltIn1 extends Builtin {
public BuiltIn1(ASTNode orig, RSymbol[] argNames, RNode[] argExprs) {
super(orig, argNames, argExprs);
}
@Override public final Object execute(Frame frame) {
return doBuiltIn(frame, (RAny) argExprs[0].execute(frame));
}
public abstract RAny doBuiltIn(Frame frame, RAny arg);
@Override public final RAny doBuiltIn(Frame frame, RAny[] params) {
return doBuiltIn(frame, params[0]);
}
}
/** Builtin functions of two arguments. */
abstract static class BuiltIn2 extends Builtin {
public BuiltIn2(ASTNode orig, RSymbol[] argNames, RNode[] argExprs) {
super(orig, argNames, argExprs);
}
@Override public final Object execute(Frame frame) {
return doBuiltIn(frame, (RAny) argExprs[0].execute(frame), (RAny) argExprs[1].execute(frame));
}
public abstract RAny doBuiltIn(Frame frame, RAny arg0, RAny arg1);
@Override public final RAny doBuiltIn(Frame frame, RAny[] params) {
return doBuiltIn(frame, params[0], params[1]);
}
}
/** Return a constant or the Java null. */
public static RAny getConstantValue(RNode node) {
return node.getAST() instanceof r.nodes.Constant ? (RAny) node.execute(null) : null;
}
/** Is node a logical constant with the value cvalue? */
public static boolean isLogicalConstant(RNode node, int cvalue) {
RAny value = getConstantValue(node);
if (value == null || !(value instanceof RLogical)) { return false; }
RLogical lv = (RLogical) value;
return lv.size() == 1 ? lv.getLogical(0) == cvalue : false;
}
/** Is node a numeric constant with the value cvalue? */
public static boolean isNumericConstant(RNode node, double cvalue) {
RAny value = getConstantValue(node);
- if (value != null) { return false; }
+ if (value == null) { return false; }
boolean ok = value instanceof RDouble || value instanceof RInt || value instanceof RLogical;
if (!ok) { return false; }
RDouble dv = value.asDouble();
return dv.size() == 1 ? dv.getDouble(0) == cvalue : false;
}
@Override public Object execute(Frame frame) {
return doBuiltIn(frame, evalArgs(frame));
}
public abstract RAny doBuiltIn(Frame frame, RAny[] params);
@ExplodeLoop private RAny[] evalArgs(Frame frame) {
int len = argExprs.length;
RAny[] args = new RAny[len];
for (int i = 0; i < len; i++) {
args[i] = (RAny) argExprs[i].execute(frame);
}
return args;
}
}
| true | true | public static boolean isNumericConstant(RNode node, double cvalue) {
RAny value = getConstantValue(node);
if (value != null) { return false; }
boolean ok = value instanceof RDouble || value instanceof RInt || value instanceof RLogical;
if (!ok) { return false; }
RDouble dv = value.asDouble();
return dv.size() == 1 ? dv.getDouble(0) == cvalue : false;
}
| public static boolean isNumericConstant(RNode node, double cvalue) {
RAny value = getConstantValue(node);
if (value == null) { return false; }
boolean ok = value instanceof RDouble || value instanceof RInt || value instanceof RLogical;
if (!ok) { return false; }
RDouble dv = value.asDouble();
return dv.size() == 1 ? dv.getDouble(0) == cvalue : false;
}
|
diff --git a/src/floobits/FlooHandler.java b/src/floobits/FlooHandler.java
index 02f3555..a1dc830 100644
--- a/src/floobits/FlooHandler.java
+++ b/src/floobits/FlooHandler.java
@@ -1,1117 +1,1117 @@
package floobits;
import com.google.gson.Gson;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.intellij.notification.Notification;
import com.intellij.notification.NotificationType;
import com.intellij.notification.Notifications;
import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.editor.CaretModel;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.EditorFactory;
import com.intellij.openapi.editor.markup.*;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.fileEditor.FileEditorManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.project.ProjectManager;
import com.intellij.openapi.roots.ContentIterator;
import com.intellij.openapi.roots.ProjectRootManager;
import com.intellij.openapi.util.TextRange;
import com.intellij.openapi.vfs.LocalFileSystem;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.openapi.vfs.VfsUtil;
import com.intellij.openapi.wm.StatusBar;
import com.intellij.openapi.wm.WindowManager;
import com.intellij.ui.JBColor;
import org.apache.commons.httpclient.HttpMethod;
import javax.swing.*;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.lang.reflect.Type;
import java.net.MalformedURLException;
import java.util.*;
import java.util.Map.Entry;
class FlooAuth implements Serializable {
public String username;
public String api_key;
public String secret;
public String room;
public String room_owner;
public String client = "IntelliJ";
public String platform = System.getProperty("os.name");
public String version = "0.10";
public String[] supported_encodings = { "utf8", "base64" };
public FlooAuth (Settings settings, String owner, String workspace) {
this.username = settings.get("username");
this.api_key = settings.get("api_key");
this.room = workspace;
this.room_owner = owner;
this.secret = settings.get("secret");
}
}
class RiBuf implements Serializable {
public Integer id;
public String md5;
public String path;
public String encoding;
}
class User implements Serializable {
public String[] perms;
public String client;
public String platform;
public Integer user_id;
public String username;
public String version;
}
class Tree implements Serializable {
public HashMap<String, Integer> bufs;
public HashMap<String, Tree> folders;
public Tree (JsonObject obj) {
this.bufs = new HashMap<String, Integer>();
this.folders = new HashMap<String, Tree>();
for (Entry<String, JsonElement> entry : obj.entrySet()) {
String key = entry.getKey();
JsonElement value = entry.getValue();
if (value.isJsonPrimitive()) {
this.bufs.put(key, Integer.parseInt(value.getAsString()));
} else {
this.folders.put(key, new Tree(value.getAsJsonObject()));
}
}
}
}
class RoomInfoResponse implements Serializable {
public String[] anon_perms;
public Integer max_size;
public String name;
public String owner;
public String[] perms;
public String room_name;
public Boolean secret;
public HashMap<Integer, User> users;
public HashMap<Integer, RiBuf> bufs;
}
class GetBufRequest implements Serializable {
public String name = "get_buf";
public Integer id;
public GetBufRequest (Integer buf_id) {
this.id = buf_id;
}
}
class GetBufResponse implements Serializable {
public String name;
public Integer id;
public String path;
public String buf;
public String encoding;
public String md5;
}
class CreateBufResponse extends GetBufResponse {}
class FlooPatch implements Serializable {
public String name = "patch";
public Integer id;
public Integer user_id;
public String md5_after;
public String md5_before;
public String patch;
// Deprecated
public String path;
public String username;
public FlooPatch(){}
public FlooPatch (String patch, String md5_before, Buf buf) {
this.path = buf.path;
this.md5_before = md5_before;
this.md5_after = buf.md5;
this.id = buf.id;
this.patch = patch;
}
}
class FlooSetBuf implements Serializable {
public String name = "set_buf";
public Integer id;
public String buf;
public String md5;
public String encoding;
public FlooSetBuf (Buf buf) {
this.md5 = buf.md5;
this.id = buf.id;
this.buf = buf.serialize();
this.encoding = buf.encoding.toString();
}
}
class FlooCreateBuf implements Serializable {
public String name = "create_buf";
public String buf;
public String path;
public String md5;
public String encoding;
public FlooCreateBuf (Buf buf) {
this.path = buf.path;
this.buf = buf.serialize();
this.md5 = buf.md5;
this.encoding = buf.encoding.toString();
}
}
class FlooHighlight implements Serializable {
public String name = "highlight";
public Integer id;
public Boolean ping = false;
public Boolean summon = false;
public List<List<Integer>> ranges;
public Integer user_id;
public FlooHighlight(){}
public FlooHighlight (Buf buf, List<List<Integer>> ranges, Boolean summon) {
this.id = buf.id;
if (summon != null) {
this.summon = summon;
this.ping = summon;
}
this.ranges = ranges;
}
}
class FlooSaveBuf implements Serializable {
public Integer id;
public String name = "saved";
FlooSaveBuf(Integer id) {
this.id = id;
}
}
class FlooDeleteBuf implements Serializable {
public Integer id;
public String name = "delete_buf";
FlooDeleteBuf(Integer id) {
this.id = id;
}
}
class FlooRenameBuf implements Serializable {
public Integer id;
public String name = "rename_buf";
public String path;
FlooRenameBuf(Integer id, String path) {
this.id = id;
this.path = path;
}
}
abstract class DocumentFetcher {
Boolean make_document = false;
DocumentFetcher(Boolean make_document) {
this.make_document = make_document;
}
abstract public void on_document(Document document);
public void fetch(final String path) {
ThreadSafe.write(new Runnable() {
public void run() {
String absPath = Utils.absPath(path);
VirtualFile virtualFile = LocalFileSystem.getInstance().findFileByPath(absPath);
if (virtualFile == null || !virtualFile.exists()) {
Flog.info("no virtual file for %s", path);
return;
}
Document d = FileDocumentManager.getInstance().getCachedDocument(virtualFile);
if (d == null && make_document) {
d = FileDocumentManager.getInstance().getDocument(virtualFile);
}
if (d == null) {
Flog.info("could not make document for %s", path);
return;
}
on_document(d);
}
});
};
}
class FlooHandler extends ConnectionInterface {
protected static boolean is_joined = false;
protected Boolean should_upload = false;
protected Project project;
protected Boolean stomp = false;
protected HashMap<Integer, HashMap<Integer, LinkedList<RangeHighlighter>>> highlights =
new HashMap<Integer, HashMap<Integer, LinkedList<RangeHighlighter>>>();
protected Boolean stalking = false;
protected String[] perms;
protected Map<Integer, User> users = new HashMap<Integer, User>();
protected HashMap<Integer, Buf> bufs = new HashMap<Integer, Buf>();
protected HashMap<String, Integer> paths_to_ids = new HashMap<String, Integer>();
protected Tree tree;
protected FlooConn conn;
protected Timeouts timeouts = Timeouts.create();
protected void flash_message(final String message) {
ApplicationManager.getApplication().invokeLater(new Runnable() {
@Override
public void run() {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
StatusBar statusBar = WindowManager.getInstance().getStatusBar(project);
if (statusBar == null) {
return;
}
JLabel jLabel = new JLabel(message);
statusBar.fireNotificationPopup(jLabel, JBColor.WHITE);
}
});
}
});
}
protected void status_message(final String message, final NotificationType notificationType) {
ApplicationManager.getApplication().invokeLater(new Runnable() {
@Override
public void run() {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
Notifications.Bus.notify(new Notification("Floobits", "Floobits", message, notificationType), project);
}
});
}
});
}
protected void status_message(String message) {
Flog.log(message);
status_message(message, NotificationType.INFORMATION);
}
protected void error_message(String message) {
Flog.log(message);
status_message(message, NotificationType.ERROR);
}
protected String get_username(Integer user_id) {
User user = users.get(user_id);
if (user == null) {
return null;
}
return user.username;
}
protected Timeout setTimeout(final Timeout timeout) {
timeouts.setTimeout(timeout);
return timeout;
}
public void on_connect () {
this.conn.write(new FlooAuth(new Settings(), this.url.owner, this.url.workspace));
status_message(String.format("You successfully joined %s ", url.toString()));
}
public void on_data (String name, JsonObject obj) throws Exception {
String method_name = "_on_" + name;
Method method;
try {
method = this.getClass().getDeclaredMethod(method_name, new Class[]{JsonObject.class});
} catch (NoSuchMethodException e) {
Flog.warn(String.format("Could not find %s method.\n%s", method_name, e.toString()));
return;
}
Object objects[] = new Object[1];
objects[0] = obj;
Flog.log("Calling %s", method_name);
method.invoke(this, objects);
}
public static FlooHandler getInstance() {
return FloobitsPlugin.flooHandler;
}
public FlooHandler (Project p) {
this.project = p;
this.stomp = true;
// TODO: Should upload should be an explicit argument to the constructor.
this.should_upload = true;
final String project_path = p.getBasePath();
FlooUrl flooUrl = DotFloo.read(project_path);
if (workspaceExists(flooUrl)) {
joinWorkspace(flooUrl, project_path);
return;
}
PersistentJson persistentJson = PersistentJson.getInstance();
for (Entry<String, Map<String, Workspace>> i : persistentJson.workspaces.entrySet()) {
Map<String, Workspace> workspaces = i.getValue();
for (Entry<String, Workspace> j : workspaces.entrySet()) {
Workspace w = j.getValue();
if (Utils.isSamePath(w.path, project_path)) {
try {
flooUrl = new FlooUrl(w.url);
} catch (MalformedURLException e) {
Flog.error(e);
continue;
}
if (workspaceExists(flooUrl)) {
joinWorkspace(flooUrl, project_path);
return;
}
}
}
}
Settings settings = new Settings();
String owner = settings.get("username");
final String name = new File(project_path).getName();
List<String> orgs = API.getOrgsCanAdmin();
if (orgs.size() == 0) {
createWorkspace(owner, name, project_path);
return;
}
orgs.add(0, owner);
SelectOwner.build(orgs, new RunLater(null) {
@Override
void run(Object... objects) {
String owner = (String) objects[0];
createWorkspace(owner, name, project_path);
}
});
}
public FlooHandler (final FlooUrl flooUrl) {
if (!workspaceExists(flooUrl)) {
error_message(String.format("The workspace %s does not exist!", flooUrl.toString()));
}
PersistentJson p = PersistentJson.getInstance();
String path;
try {
path = p.workspaces.get(flooUrl.owner).get(flooUrl.workspace).path;
} catch (Exception e) {
SelectFolder.build(Utils.unFuckPath("~"), new RunLater(null) {
@Override
void run(Object... objects) {
File file = (File)objects[0];
String path;
try {
path = file.getCanonicalPath();
} catch (IOException e) {
Flog.error(e);
return;
}
joinWorkspace(flooUrl, path);
}
});
return;
}
ProjectManager pm = ProjectManager.getInstance();
// Check open projects
Project[] openProjects = pm.getOpenProjects();
for (Project project : openProjects) {
if (path.equals(project.getBasePath())) {
this.project = project;
break;
}
}
// Try to open existing project
if (this.project == null) {
try {
this.project = pm.loadAndOpenProject(path);
} catch (Exception e) {
Flog.error(e);
}
}
// Create project
if (this.project == null) {
this.project = pm.createProject(this.url.workspace, path);
try {
ProjectManager.getInstance().loadAndOpenProject(this.project.getBasePath());
} catch (Exception e) {
Flog.error(e);
return;
}
}
joinWorkspace(flooUrl, this.project.getBasePath());
}
public Boolean workspaceExists(final FlooUrl f) {
if (f == null) {
return false;
}
HttpMethod method;
try {
method = API.getWorkspace(f.owner, f.workspace);
} catch (IOException e) {
Flog.warn(e);
return false;
}
return method.getStatusCode() < 400;
}
public void joinWorkspace(final FlooUrl f, final String path) {
Flog.warn("join workspace");
url = f;
Shared.colabDir = path;
PersistentJson persistentJson = PersistentJson.getInstance();
persistentJson.addWorkspace(f, path);
persistentJson.save();
conn = new FlooConn(this);
conn.start();
}
protected void createWorkspace(String owner, String name, String project_path) {
HttpMethod method;
try {
method = API.createWorkspace(owner, name);
} catch (IOException e) {
error_message(String.format("Could not create workspace: %s", e.toString()));
return;
}
int code = method.getStatusCode();
switch (code) {
case 400:
// Todo: pick a new name or something
error_message("Invalid workspace name.");
return;
case 402:
String details;
try {
String res = method.getResponseBodyAsString();
JsonObject obj = (JsonObject)new JsonParser().parse(res);
details = obj.get("detail").getAsString();
} catch (IOException e) {
Flog.error(e);
return;
}
error_message(details);
return;
case 409:
Flog.warn("The workspace already exists so I am joining it.");
case 201:
Flog.log("Workspace created.");
joinWorkspace(new FlooUrl(Shared.defaultHost, owner, name, -1, true), project_path);
return;
default:
try {
Flog.error(String.format("Unknown error creating workspace:\n%s", method.getResponseBodyAsString()));
} catch (IOException e) {
Flog.error(e);
}
}
}
protected Buf get_buf_by_path(String absPath) {
String relPath = Utils.toProjectRelPath(absPath);
if (relPath == null) {
return null;
}
Integer id = this.paths_to_ids.get(relPath);
if (id == null) {
return null;
}
return this.bufs.get(id);
}
public void upload() {
final Ignore ignore;
try {
ignore = new Ignore(new File(Shared.colabDir), null, false);
} catch (Exception ex) {
Flog.error(ex);
return;
}
ProjectRootManager.getInstance(project).getFileIndex().iterateContent(new ContentIterator() {
public boolean processFile(final VirtualFile virtualFile) {
if (!ignore.isIgnored(virtualFile.getCanonicalPath())) upload(virtualFile);
return true;
}
});
}
public boolean upload(VirtualFile virtualFile) {
if (!Utils.isSharableFile(virtualFile)) {
return true;
}
String path = virtualFile.getPath();
if (!Utils.isShared(path)) {
Flog.info("Thing isn't shared: %s", path);
return true;
}
String rel_path = Utils.toProjectRelPath(path);
if (rel_path.equals(".idea/workspace.xml")) {
Flog.info("Not sharing the workspace.xml file");
return true;
}
Buf b = FloobitsPlugin.flooHandler.get_buf_by_path(path);
if (b != null) {
Flog.info("Already in workspace: %s", path);
return true;
}
FloobitsPlugin.flooHandler.send_create_buf(virtualFile);
return true;
}
protected void _on_room_info (JsonObject obj) {
RoomInfoResponse ri = new Gson().fromJson(obj, (Type) RoomInfoResponse.class);
is_joined = true;
this.tree = new Tree(obj.getAsJsonObject("tree"));
this.users = ri.users;
this.perms = ri.perms;
LocalFileSystem localFileSystem = LocalFileSystem.getInstance();
DotFloo.write(this.url.toString());
LinkedList<Buf> conflicts = new LinkedList<Buf>();
for (Map.Entry entry : ri.bufs.entrySet()) {
Integer buf_id = (Integer) entry.getKey();
RiBuf b = (RiBuf) entry.getValue();
Buf buf = Buf.createBuf(b.path, b.id, Encoding.from(b.encoding), b.md5);
this.bufs.put(buf_id, buf);
this.paths_to_ids.put(b.path, b.id);
buf.read();
if (buf.buf == null) {
this.send_get_buf(buf.id);
continue;
}
if (!b.md5.equals(buf.md5)) {
conflicts.add(buf);
continue;
}
}
if (conflicts.size() == 0) {
if (this.should_upload) {
this.upload();
}
return;
}
String dialog;
if (conflicts.size() > 15) {
- dialog = "<p>%d files are different. Do you want to overwrite them (OK)?</p> ";
+ dialog = String.format("<p>%d files are different. Do you want to overwrite them (OK)?</p> ", conflicts.size());
} else {
dialog = "<p>The following file(s) are different. Do you want to overwrite them (OK)?</p><ul>";
for (Buf buf : conflicts) {
dialog += String.format("<li>%s</li>", buf.path);
}
dialog += "</ul>";
}
DialogBuilder.build("Resolve Conflicts", dialog, new RunLater(conflicts) {
@Override
@SuppressWarnings("unchecked")
void run(Object... objects) {
Boolean stomp = (Boolean) objects[0];
LinkedList<Buf> conflicts = (LinkedList<Buf>) data;
for (Buf buf : conflicts) {
if (stomp) {
FloobitsPlugin.flooHandler.send_get_buf(buf.id);
buf.buf = null;
buf.md5 = null;
} else {
FloobitsPlugin.flooHandler.send_set_buf(buf);
}
}
if (should_upload) {
FloobitsPlugin.flooHandler.upload();
}
}
});
}
public void send_create_buf(VirtualFile virtualFile) {
Buf buf = Buf.createBuf(virtualFile);
if (buf == null) {
return;
}
this.conn.write(new FlooCreateBuf(buf));
}
protected void _on_get_buf (JsonObject obj) {
// TODO: be nice about this and update the existing view
Gson gson = new Gson();
GetBufResponse res = gson.fromJson(obj, (Type) GetBufResponse.class);
Buf b = this.bufs.get(res.id);
b.set(res.buf, res.md5);
b.write();
Flog.info("on get buffed. %s", b.path);
}
protected void _on_create_buf (JsonObject obj) {
// TODO: be nice about this and update the existing view
Gson gson = new Gson();
GetBufResponse res = gson.fromJson(obj, (Type) CreateBufResponse.class);
Buf buf = Buf.createBuf(res.path, res.id, res.buf, res.md5);
this.bufs.put(buf.id, buf);
this.paths_to_ids.put(buf.path, buf.id);
buf.write();
}
protected void _on_patch (JsonObject obj) {
final FlooPatch res = new Gson().fromJson(obj, (Type) FlooPatch.class);
final Buf b = this.bufs.get(res.id);
if (b.buf == null) {
Flog.warn("no buffer");
this.send_get_buf(res.id);
return;
}
if (res.patch.length() == 0) {
Flog.warn("wtf? no patches to apply. server is being stupid");
return;
}
b.patch(res);
}
public void get_document(Integer id, DocumentFetcher documentFetcher) {
Buf buf = this.bufs.get(id);
if (buf == null) {
Flog.info("Buf %d is not populated yet", id);
return;
}
if (buf.buf == null) {
Flog.info("Buf %s is not populated yet", buf.path);
return;
}
this.get_document(buf.path, documentFetcher);
}
public void get_document(String path, DocumentFetcher documentFetcher) {
documentFetcher.fetch(path);
}
protected Editor get_editor_for_document(Document document) {
Editor[] editors = EditorFactory.getInstance().getEditors(document, project);
if (editors.length > 0) {
return editors[0];
}
VirtualFile virtualFile = FileDocumentManager.getInstance().getFile(document);
if (virtualFile == null) {
return null;
}
return EditorFactory.getInstance().createEditor(document, project, virtualFile, true);
}
public void remove_highlight (Integer userId, Integer bufId, Document document) {
HashMap<Integer, LinkedList<RangeHighlighter>> integerRangeHighlighterHashMap = FloobitsPlugin.flooHandler.highlights.get(userId);
if (integerRangeHighlighterHashMap == null) {
return;
}
final LinkedList<RangeHighlighter> rangeHighlighters = integerRangeHighlighterHashMap.get(bufId);
if (rangeHighlighters == null) {
return;
}
if (document != null) {
Editor editor = get_editor_for_document(document);
MarkupModel markupModel = editor.getMarkupModel();
for (RangeHighlighter rangeHighlighter: rangeHighlighters) {
markupModel.removeHighlighter(rangeHighlighter);
}
rangeHighlighters.clear();
return;
}
FloobitsPlugin.flooHandler.get_document(bufId, new DocumentFetcher(false) {
@Override
public void on_document(Document document) {
Editor editor = get_editor_for_document(document);
MarkupModel markupModel = editor.getMarkupModel();
for (RangeHighlighter rangeHighlighter: rangeHighlighters) {
markupModel.removeHighlighter(rangeHighlighter);
}
rangeHighlighters.clear();
}
});
}
protected void _on_highlight (JsonObject obj) {
final FlooHighlight res = new Gson().fromJson(obj, (Type)FlooHighlight.class);
final List<List<Integer>> ranges = res.ranges;
final Boolean force = FloobitsPlugin.flooHandler.stalking || res.ping || (res.summon == null ? Boolean.FALSE : res.summon);
FloobitsPlugin.flooHandler.get_document(res.id, new DocumentFetcher(force) {
@Override
public void on_document(Document document) {
final FileEditorManager manager = FileEditorManager.getInstance(project);
VirtualFile virtualFile = FileDocumentManager.getInstance().getFile(document);
if (force && virtualFile != null) {
String username = get_username(res.user_id);
if (username != null) {
status_message(String.format("%s has summoned you to %s", username, virtualFile.getPath()));
}
manager.openFile(virtualFile, true, true);
}
FloobitsPlugin.flooHandler.remove_highlight(res.user_id, res.id, document);
int textLength = document.getTextLength();
if (textLength == 0) {
return;
}
TextAttributes attributes = new TextAttributes();
attributes.setEffectColor(JBColor.GREEN);
attributes.setEffectType(EffectType.SEARCH_MATCH);
attributes.setBackgroundColor(JBColor.GREEN);
boolean first = true;
Editor editor = FloobitsPlugin.flooHandler.get_editor_for_document(document);
MarkupModel markupModel = editor.getMarkupModel();
LinkedList<RangeHighlighter> rangeHighlighters = new LinkedList<RangeHighlighter>();
for (List<Integer> range : ranges) {
int start = range.get(0);
int end = range.get(1);
if (start == end) {
end += 1;
}
if (end > textLength) {
end = textLength;
}
if (start >= textLength) {
start = textLength - 1;
}
RangeHighlighter rangeHighlighter = markupModel.addRangeHighlighter(start, end, HighlighterLayer.ERROR + 100,
attributes, HighlighterTargetArea.EXACT_RANGE);
rangeHighlighters.add(rangeHighlighter);
if (force && first) {
CaretModel caretModel = editor.getCaretModel();
caretModel.moveToOffset(start);
first = false;
}
}
HashMap<Integer, LinkedList<RangeHighlighter>> integerRangeHighlighterHashMap = FloobitsPlugin.flooHandler.highlights.get(res.user_id);
if (integerRangeHighlighterHashMap == null) {
integerRangeHighlighterHashMap = new HashMap<Integer, LinkedList<RangeHighlighter>>();
FloobitsPlugin.flooHandler.highlights.put(res.user_id, integerRangeHighlighterHashMap);
}
integerRangeHighlighterHashMap.put(res.id, rangeHighlighters);
}
});
}
protected void _on_saved (JsonObject obj) {
Integer id = obj.get("id").getAsInt();
this.get_document(id, new DocumentFetcher(false) {
@Override
public void on_document(Document document) {
FileDocumentManager.getInstance().saveDocument(document);
}
});
}
private void set_buf_path(Buf buf, String newPath) {
paths_to_ids.remove(buf.path);
buf.path = newPath;
this.paths_to_ids.put(buf.path, buf.id);
}
protected void _on_rename_buf (JsonObject jsonObject) {
final String name = jsonObject.get("old_path").getAsString();
final String oldPath = Utils.absPath(name);
final String newPath = Utils.absPath(jsonObject.get("path").getAsString());
final VirtualFile foundFile = LocalFileSystem.getInstance().findFileByPath(oldPath);
Buf buf = get_buf_by_path(oldPath);
if (buf == null) {
if (get_buf_by_path(newPath) == null) {
Flog.error("Rename oldPath and newPath don't exist. %s %s", oldPath, newPath);
} else {
Flog.info("We probably renamed this, nothing to rename.");
}
return;
}
if (foundFile == null) {
Flog.warn("File we want to move was not found %s %s.", oldPath, newPath);
return;
}
String newRelativePath = Utils.toProjectRelPath(newPath);
set_buf_path(buf, newRelativePath);
ApplicationManager.getApplication().invokeLater(new Runnable() {
@Override
public void run() {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
File oldFile = new File(oldPath);
File newFile = new File(newPath);
String newFileName = newFile.getName();
// Rename file
try {
foundFile.rename(null, newFileName);
} catch (IOException e) {
Flog.error("Error renaming file %s %s %s", e, oldPath, newPath);
}
// Move file
String newParentDirectoryPath = newFile.getParent();
String oldParentDirectoryPath = oldFile.getParent();
if (newParentDirectoryPath == oldParentDirectoryPath) {
Flog.info("Only renamed file, don't need to move %s %s", oldPath, newPath);
return;
}
VirtualFile directory = null;
try {
directory = VfsUtil.createDirectories(newParentDirectoryPath);
} catch (IOException e) {
Flog.error("Failed to create directories in time for moving file. %s %s", oldPath, newPath);
}
if (directory == null) {
Flog.error("Failed to create directories in time for moving file. %s %s", oldPath, newPath);
return;
}
try {
foundFile.move(null, directory);
} catch (IOException e) {
Flog.error("Error moving file %s %s %s", e,oldPath, newPath);
}
}
});
}
});
}
protected void _on_request_perms(JsonObject obj) {
Flog.log("got perms request");
}
protected void _on_join (JsonObject obj) {
User u = new Gson().fromJson(obj, (Type)User.class);
this.users.put(u.user_id, u);
status_message(String.format("%s joined the workspace on %s (%s).", u.username, u.platform, u.client));
}
protected void _on_part (JsonObject obj) {
Integer userId = obj.get("user_id").getAsInt();
User u = users.get(userId);
this.users.remove(userId);
HashMap<Integer, LinkedList<RangeHighlighter>> integerRangeHighlighterHashMap = FloobitsPlugin.flooHandler.highlights.get(userId);
if (integerRangeHighlighterHashMap == null) {
return;
}
for (Entry<Integer, LinkedList<RangeHighlighter>> entry : integerRangeHighlighterHashMap.entrySet()) {
remove_highlight(userId, entry.getKey(), null);
}
status_message(String.format("%s left the workspace.", u.username));
}
protected void _on_disconnect (JsonObject jsonObject) {
is_joined = false;
String reason = jsonObject.get("reason").getAsString();
if (reason != null) {
error_message(reason);
flash_message(reason);
} else {
status_message("You have left the workspace");
}
FloobitsPlugin.flooHandler = null;
conn.shut_down();
}
protected void _on_delete_buf(JsonObject jsonObject) {
Integer id = jsonObject.get("id").getAsInt();
Buf buf = bufs.get(id);
if (buf == null) {
Flog.warn(String.format("Tried to delete a buf that doesn't exist: %s", id));
return;
}
String absPath = Utils.absPath(buf.path);
buf.cancelTimeout();
bufs.remove(id);
paths_to_ids.remove(buf.path);
final VirtualFile fileByPath = LocalFileSystem.getInstance().findFileByPath(absPath);
if (fileByPath == null) {
return;
}
ApplicationManager.getApplication().invokeLater(new Runnable() {
@Override
public void run() {
ApplicationManager.getApplication().runWriteAction(new Runnable() {
public void run() {
try {
fileByPath.delete(FlooHandler.getInstance());
} catch (IOException e) {
Flog.error(e);
}
}
});
}
});
}
public void _on_msg (JsonObject jsonObject){
String msg = jsonObject.get("data").getAsString();
String username = jsonObject.get("username").getAsString();
status_message(String.format("%s: %s", username, msg));
}
public void _on_term_stdout(JsonObject jsonObject) {}
public void _on_term_stdin(JsonObject jsonObject) {}
public void send_get_buf (Integer buf_id) {
this.conn.write(new GetBufRequest(buf_id));
}
public void send_patch (String textPatch, String before_md5, TextBuf buf) {
FlooPatch req = new FlooPatch(textPatch, before_md5, buf);
this.conn.write(req);
}
public void send_set_buf (Buf b) {
this.conn.write(new FlooSetBuf(b));
}
public void send_summon (String current, Integer offset) {
Buf buf = this.get_buf_by_path(current);
List<List<Integer>> ranges = new ArrayList<List<Integer>>();
ranges.add(Arrays.asList(offset, offset));
this.conn.write(new FlooHighlight(buf, ranges, true));
}
public void untellij_renamed(String path, String newPath) {
Flog.log("Renamed buf: %s - %s", path, newPath);
Buf buf = this.get_buf_by_path(path);
if (buf == null) {
Flog.info("buf does not exist.");
return;
}
String newRelativePath = Utils.toProjectRelPath(newPath);
if (buf.path.equals(newRelativePath)) {
Flog.info("untellij_renamed handling workspace rename, aborting.");
return;
}
buf.cancelTimeout();
this.conn.write(new FlooRenameBuf(buf.id, newRelativePath));
set_buf_path(buf, newRelativePath);
}
public void untellij_changed(VirtualFile file) {
Buf buf = this.get_buf_by_path(file.getPath());
if (buf == null || !buf.isPopulated()) {
Flog.info("buf isn't populated yet %s", buf);
return;
}
buf.send_patch(file);
}
public void untellij_selection_change(String path, TextRange[] textRanges) {
Buf buf = this.get_buf_by_path(path);
if (buf == null || buf.buf == null) {
Flog.info("buf isn't populated yet %s", path);
return;
}
List<List<Integer>> ranges = new ArrayList<List<Integer>>();
for (TextRange r : textRanges) {
ranges.add(Arrays.asList(r.getStartOffset(), r.getEndOffset()));
}
this.conn.write(new FlooHighlight(buf, ranges, false));
}
public void untellij_saved(String path) {
Buf buf = this.get_buf_by_path(path);
if (buf == null || buf.buf == null) {
Flog.info("buf isn't populated yet %s", path);
return;
}
this.conn.write(new FlooSaveBuf(buf.id));
}
public void untellij_deleted(String path) {
Buf buf = this.get_buf_by_path(path);
if (buf == null) {
Flog.info("buf does not exist");
return;
}
buf.cancelTimeout();
this.conn.write(new FlooDeleteBuf(buf.id));
}
public void untellij_deleted_directory(ArrayList<String> filePaths) {
for (String filePath : filePaths) {
untellij_deleted(filePath);
}
}
@SuppressWarnings("unused")
public void testHandlers () throws IOException {
JsonObject obj = new JsonObject();
_on_room_info(obj);
_on_get_buf(obj);
_on_patch(obj);
_on_highlight(obj);
_on_saved(obj);
_on_join(obj);
_on_part(obj);
_on_disconnect(obj);
_on_create_buf(obj);
_on_request_perms(obj);
_on_msg(obj);
_on_rename_buf(obj);
_on_term_stdin(obj);
_on_term_stdout(obj);
_on_delete_buf(obj);
}
public void clear_highlights() {
for (Entry<Integer, HashMap<Integer, LinkedList<RangeHighlighter>>> entry : FloobitsPlugin.flooHandler.highlights.entrySet()) {
Integer user_id = entry.getKey();
HashMap<Integer, LinkedList<RangeHighlighter>> value = entry.getValue();
for (Entry<Integer, LinkedList<RangeHighlighter>> integerLinkedListEntry: value.entrySet()) {
remove_highlight(user_id, integerLinkedListEntry.getKey(), null);
}
}
}
public void shut_down() {
status_message(String.format("Leaving workspace: %s.", url.toString()));
this.conn.shut_down();
is_joined = false;
}
}
| true | true | protected void _on_room_info (JsonObject obj) {
RoomInfoResponse ri = new Gson().fromJson(obj, (Type) RoomInfoResponse.class);
is_joined = true;
this.tree = new Tree(obj.getAsJsonObject("tree"));
this.users = ri.users;
this.perms = ri.perms;
LocalFileSystem localFileSystem = LocalFileSystem.getInstance();
DotFloo.write(this.url.toString());
LinkedList<Buf> conflicts = new LinkedList<Buf>();
for (Map.Entry entry : ri.bufs.entrySet()) {
Integer buf_id = (Integer) entry.getKey();
RiBuf b = (RiBuf) entry.getValue();
Buf buf = Buf.createBuf(b.path, b.id, Encoding.from(b.encoding), b.md5);
this.bufs.put(buf_id, buf);
this.paths_to_ids.put(b.path, b.id);
buf.read();
if (buf.buf == null) {
this.send_get_buf(buf.id);
continue;
}
if (!b.md5.equals(buf.md5)) {
conflicts.add(buf);
continue;
}
}
if (conflicts.size() == 0) {
if (this.should_upload) {
this.upload();
}
return;
}
String dialog;
if (conflicts.size() > 15) {
dialog = "<p>%d files are different. Do you want to overwrite them (OK)?</p> ";
} else {
dialog = "<p>The following file(s) are different. Do you want to overwrite them (OK)?</p><ul>";
for (Buf buf : conflicts) {
dialog += String.format("<li>%s</li>", buf.path);
}
dialog += "</ul>";
}
DialogBuilder.build("Resolve Conflicts", dialog, new RunLater(conflicts) {
@Override
@SuppressWarnings("unchecked")
void run(Object... objects) {
Boolean stomp = (Boolean) objects[0];
LinkedList<Buf> conflicts = (LinkedList<Buf>) data;
for (Buf buf : conflicts) {
if (stomp) {
FloobitsPlugin.flooHandler.send_get_buf(buf.id);
buf.buf = null;
buf.md5 = null;
} else {
FloobitsPlugin.flooHandler.send_set_buf(buf);
}
}
if (should_upload) {
FloobitsPlugin.flooHandler.upload();
}
}
});
}
| protected void _on_room_info (JsonObject obj) {
RoomInfoResponse ri = new Gson().fromJson(obj, (Type) RoomInfoResponse.class);
is_joined = true;
this.tree = new Tree(obj.getAsJsonObject("tree"));
this.users = ri.users;
this.perms = ri.perms;
LocalFileSystem localFileSystem = LocalFileSystem.getInstance();
DotFloo.write(this.url.toString());
LinkedList<Buf> conflicts = new LinkedList<Buf>();
for (Map.Entry entry : ri.bufs.entrySet()) {
Integer buf_id = (Integer) entry.getKey();
RiBuf b = (RiBuf) entry.getValue();
Buf buf = Buf.createBuf(b.path, b.id, Encoding.from(b.encoding), b.md5);
this.bufs.put(buf_id, buf);
this.paths_to_ids.put(b.path, b.id);
buf.read();
if (buf.buf == null) {
this.send_get_buf(buf.id);
continue;
}
if (!b.md5.equals(buf.md5)) {
conflicts.add(buf);
continue;
}
}
if (conflicts.size() == 0) {
if (this.should_upload) {
this.upload();
}
return;
}
String dialog;
if (conflicts.size() > 15) {
dialog = String.format("<p>%d files are different. Do you want to overwrite them (OK)?</p> ", conflicts.size());
} else {
dialog = "<p>The following file(s) are different. Do you want to overwrite them (OK)?</p><ul>";
for (Buf buf : conflicts) {
dialog += String.format("<li>%s</li>", buf.path);
}
dialog += "</ul>";
}
DialogBuilder.build("Resolve Conflicts", dialog, new RunLater(conflicts) {
@Override
@SuppressWarnings("unchecked")
void run(Object... objects) {
Boolean stomp = (Boolean) objects[0];
LinkedList<Buf> conflicts = (LinkedList<Buf>) data;
for (Buf buf : conflicts) {
if (stomp) {
FloobitsPlugin.flooHandler.send_get_buf(buf.id);
buf.buf = null;
buf.md5 = null;
} else {
FloobitsPlugin.flooHandler.send_set_buf(buf);
}
}
if (should_upload) {
FloobitsPlugin.flooHandler.upload();
}
}
});
}
|
diff --git a/src/org/subethamail/smtp/client/SMTPClient.java b/src/org/subethamail/smtp/client/SMTPClient.java
index 536fbea..a8a3da5 100644
--- a/src/org/subethamail/smtp/client/SMTPClient.java
+++ b/src/org/subethamail/smtp/client/SMTPClient.java
@@ -1,235 +1,246 @@
package org.subethamail.smtp.client;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;
import java.net.UnknownHostException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.subethamail.smtp.io.DotTerminatedOutputStream;
import org.subethamail.smtp.io.ExtraDotOutputStream;
/**
* A very low level abstraction of the STMP stream which knows how to handle
* the raw protocol for lines, whitespace, etc.
*
* @author Jeff Schnitzer
*/
public class SMTPClient
{
/** 5 minutes */
private static final int CONNECT_TIMEOUT = 300 * 1000;
/** 10 minutes */
private static final int REPLY_TIMEOUT = 600 * 1000;
/** */
private static Logger log = LoggerFactory.getLogger(SMTPClient.class);
/** Just for display purposes */
String hostPort;
/** The raw socket */
Socket socket;
/** */
BufferedReader reader;
/** Output streams used for data */
OutputStream rawOutput;
/**
* A stream which wraps {@link #rawOutput} and is used to write out the DOT
* CR LF terminating sequence in the DATA command, if necessary
* complementing the message content with a closing CR LF.
*/
DotTerminatedOutputStream dotTerminatedOutput;
/**
* This stream wraps {@link #dotTerminatedOutput} and it does the dot
* stuffing for the SMTP DATA command.
*/
ExtraDotOutputStream dataOutput;
/** Note we bypass this during DATA */
PrintWriter writer;
/**
* Result of an SMTP exchange.
*/
public static class Response
{
int code;
String message;
public Response(int code, String text)
{
this.code = code;
this.message = text;
}
public int getCode() { return this.code; }
public String getMessage() { return this.message; }
public boolean isSuccess()
{
return this.code >= 100 && this.code < 400;
}
@Override
public String toString() { return this.code + " " + this.message; }
}
/**
* Establishes a connection to host and port and negotiate the initial EHLO
* exchange.
*
* @throws UnknownHostException if the hostname cannot be resolved
* @throws IOException if there is a problem connecting to the port
*/
public SMTPClient(String host, int port) throws UnknownHostException, IOException
{
this(host, port, null);
}
/**
* Establishes a connection to host and port from the specified local socket
* address and negotiate the initial EHLO exchange.
*
* @param bindpoint the local socket address. If null, the system will pick
* up an ephemeral port and a valid local address.
*
* @throws UnknownHostException if the hostname cannot be resolved
* @throws IOException if there is a problem connecting to the port
*/
public SMTPClient(String host, int port, SocketAddress bindpoint) throws UnknownHostException, IOException
{
this.hostPort = host + ":" + port;
if (log.isDebugEnabled())
log.debug("Connecting to " + this.hostPort);
this.socket = new Socket();
this.socket.bind(bindpoint);
this.socket.setSoTimeout(REPLY_TIMEOUT);
this.socket.connect(new InetSocketAddress(host, port), CONNECT_TIMEOUT);
this.reader = new BufferedReader(new InputStreamReader(this.socket.getInputStream()));
this.rawOutput = this.socket.getOutputStream();
this.dotTerminatedOutput = new DotTerminatedOutputStream(this.rawOutput);
this.dataOutput = new ExtraDotOutputStream(this.dotTerminatedOutput);
this.writer = new PrintWriter(this.rawOutput, true);
}
/**
* @return a nice pretty description of who we are connected to
*/
public String getHostPort()
{
return this.hostPort;
}
/**
* Sends a message to the server, ie "HELO foo.example.com". A newline will
* be appended to the message.
*
* @param msg should not have any newlines
*/
protected void send(String msg) throws IOException
{
if (log.isDebugEnabled())
log.debug("Client: " + msg);
// Force \r\n since println() behaves differently on different platforms
this.writer.print(msg + "\r\n");
this.writer.flush();
}
/**
* Note that the response text comes back without trailing newlines.
*/
protected Response receive() throws IOException
{
StringBuilder builder = new StringBuilder();
String line = null;
boolean done = false;
while (!done)
{
line = this.reader.readLine();
if (log.isDebugEnabled())
log.debug("Server: " + line);
+ if (line.length() < 4)
+ throw new IOException("Malformed SMTP reply: " + line);
builder.append(line.substring(4));
if (line.charAt(3) == '-')
builder.append('\n');
else
done = true;
}
- String code = line.substring(0, 3);
+ int code;
+ String codeString = line.substring(0, 3);
+ try
+ {
+ code = Integer.parseInt(codeString);
+ }
+ catch (NumberFormatException e)
+ {
+ throw new IOException("Malformed SMTP reply: " + line, e);
+ }
- return new Response(Integer.parseInt(code), builder.toString());
+ return new Response(code, builder.toString());
}
/**
* Sends a message to the server, ie "HELO foo.example.com". A newline will
* be appended to the message.
*
* @param msg should not have any newlines
* @return the response from the server
*/
public Response sendReceive(String msg) throws IOException
{
this.send(msg);
return this.receive();
}
/** If response is not success, throw an exception */
public void receiveAndCheck() throws IOException, SMTPException
{
Response resp = this.receive();
if (!resp.isSuccess())
throw new SMTPException(resp);
}
/** If response is not success, throw an exception */
public void sendAndCheck(String msg) throws IOException, SMTPException
{
this.send(msg);
this.receiveAndCheck();
}
/** Logs but otherwise ignores errors */
public void close()
{
if (!this.socket.isClosed())
{
try
{
this.socket.close();
if (log.isDebugEnabled())
log.debug("Closed connection to " + this.hostPort);
}
catch (IOException ex)
{
log.error("Problem closing connection to " + this.hostPort, ex);
}
}
}
/** */
@Override
public String toString()
{
return this.getClass().getSimpleName() + " { " + this.hostPort + "}";
}
}
| false | true | protected Response receive() throws IOException
{
StringBuilder builder = new StringBuilder();
String line = null;
boolean done = false;
while (!done)
{
line = this.reader.readLine();
if (log.isDebugEnabled())
log.debug("Server: " + line);
builder.append(line.substring(4));
if (line.charAt(3) == '-')
builder.append('\n');
else
done = true;
}
String code = line.substring(0, 3);
return new Response(Integer.parseInt(code), builder.toString());
}
| protected Response receive() throws IOException
{
StringBuilder builder = new StringBuilder();
String line = null;
boolean done = false;
while (!done)
{
line = this.reader.readLine();
if (log.isDebugEnabled())
log.debug("Server: " + line);
if (line.length() < 4)
throw new IOException("Malformed SMTP reply: " + line);
builder.append(line.substring(4));
if (line.charAt(3) == '-')
builder.append('\n');
else
done = true;
}
int code;
String codeString = line.substring(0, 3);
try
{
code = Integer.parseInt(codeString);
}
catch (NumberFormatException e)
{
throw new IOException("Malformed SMTP reply: " + line, e);
}
return new Response(code, builder.toString());
}
|
diff --git a/samples/demos/src/com/actionbarsherlock/sample/demos/app/ActionBarSimple.java b/samples/demos/src/com/actionbarsherlock/sample/demos/app/ActionBarSimple.java
index eca265b2..7baafe13 100644
--- a/samples/demos/src/com/actionbarsherlock/sample/demos/app/ActionBarSimple.java
+++ b/samples/demos/src/com/actionbarsherlock/sample/demos/app/ActionBarSimple.java
@@ -1,30 +1,30 @@
/*
* Copyright (C) 2011 Jake Wharton
*
* 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.actionbarsherlock.sample.demos.app;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.widget.TextView;
import com.actionbarsherlock.sample.demos.R;
public class ActionBarSimple extends FragmentActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.actionbar_text);
- ((TextView)findViewById(R.id.text)).setText(R.string.actionbar_simple);
+ ((TextView)findViewById(R.id.text)).setText(R.string.actionbar_simple_content);
}
}
| true | true | protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.actionbar_text);
((TextView)findViewById(R.id.text)).setText(R.string.actionbar_simple);
}
| protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.actionbar_text);
((TextView)findViewById(R.id.text)).setText(R.string.actionbar_simple_content);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.