repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
open-health-hub/openmaxims-linux
openmaxims_workspace/ValueObjects/src/ims/core/vo/domain/MedicationUnitVoAssembler.java
17281
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program 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. # //# # //# 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 Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH /* * This code was generated * Copyright (C) 1995-2004 IMS MAXIMS plc. All rights reserved. * IMS Development Environment (version 1.80 build 5007.25751) * WARNING: DO NOT MODIFY the content of this file * Generated on 16/04/2014, 12:31 * */ package ims.core.vo.domain; import ims.vo.domain.DomainObjectMap; import java.util.HashMap; import org.hibernate.proxy.HibernateProxy; /** * @author Calin Perebiceanu */ public class MedicationUnitVoAssembler { /** * Copy one ValueObject to another * @param valueObjectDest to be updated * @param valueObjectSrc to copy values from */ public static ims.core.vo.MedicationUnitVo copy(ims.core.vo.MedicationUnitVo valueObjectDest, ims.core.vo.MedicationUnitVo valueObjectSrc) { if (null == valueObjectSrc) { return valueObjectSrc; } valueObjectDest.setID_MedicationUnit(valueObjectSrc.getID_MedicationUnit()); valueObjectDest.setIsRIE(valueObjectSrc.getIsRIE()); // DoseUnit valueObjectDest.setDoseUnit(valueObjectSrc.getDoseUnit()); return valueObjectDest; } /** * Create the ValueObject collection to hold the set of DomainObjects. * This is a convenience method only. * It is intended to be used when one called to an Assembler is made. * If more than one call to an Assembler is made then #createMedicationUnitVoCollectionFromMedicationUnit(DomainObjectMap, Set) should be used. * @param domainObjectSet - Set of ims.core.clinical.domain.objects.MedicationUnit objects. */ public static ims.core.vo.MedicationUnitVoCollection createMedicationUnitVoCollectionFromMedicationUnit(java.util.Set domainObjectSet) { return createMedicationUnitVoCollectionFromMedicationUnit(new DomainObjectMap(), domainObjectSet); } /** * Create the ValueObject collection to hold the set of DomainObjects. * @param map - maps DomainObjects to created ValueObjects * @param domainObjectSet - Set of ims.core.clinical.domain.objects.MedicationUnit objects. */ public static ims.core.vo.MedicationUnitVoCollection createMedicationUnitVoCollectionFromMedicationUnit(DomainObjectMap map, java.util.Set domainObjectSet) { ims.core.vo.MedicationUnitVoCollection voList = new ims.core.vo.MedicationUnitVoCollection(); if ( null == domainObjectSet ) { return voList; } int rieCount=0; int activeCount=0; java.util.Iterator iterator = domainObjectSet.iterator(); while( iterator.hasNext() ) { ims.core.clinical.domain.objects.MedicationUnit domainObject = (ims.core.clinical.domain.objects.MedicationUnit) iterator.next(); ims.core.vo.MedicationUnitVo vo = create(map, domainObject); if (vo != null) voList.add(vo); if (domainObject != null) { if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true) rieCount++; else activeCount++; } } voList.setRieCount(rieCount); voList.setActiveCount(activeCount); return voList; } /** * Create the ValueObject collection to hold the list of DomainObjects. * @param domainObjectList - List of ims.core.clinical.domain.objects.MedicationUnit objects. */ public static ims.core.vo.MedicationUnitVoCollection createMedicationUnitVoCollectionFromMedicationUnit(java.util.List domainObjectList) { return createMedicationUnitVoCollectionFromMedicationUnit(new DomainObjectMap(), domainObjectList); } /** * Create the ValueObject collection to hold the list of DomainObjects. * @param map - maps DomainObjects to created ValueObjects * @param domainObjectList - List of ims.core.clinical.domain.objects.MedicationUnit objects. */ public static ims.core.vo.MedicationUnitVoCollection createMedicationUnitVoCollectionFromMedicationUnit(DomainObjectMap map, java.util.List domainObjectList) { ims.core.vo.MedicationUnitVoCollection voList = new ims.core.vo.MedicationUnitVoCollection(); if ( null == domainObjectList ) { return voList; } int rieCount=0; int activeCount=0; for (int i = 0; i < domainObjectList.size(); i++) { ims.core.clinical.domain.objects.MedicationUnit domainObject = (ims.core.clinical.domain.objects.MedicationUnit) domainObjectList.get(i); ims.core.vo.MedicationUnitVo vo = create(map, domainObject); if (vo != null) voList.add(vo); if (domainObject != null) { if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true) rieCount++; else activeCount++; } } voList.setRieCount(rieCount); voList.setActiveCount(activeCount); return voList; } /** * Create the ims.core.clinical.domain.objects.MedicationUnit set from the value object collection. * @param domainFactory - used to create existing (persistent) domain objects. * @param voCollection - the collection of value objects */ public static java.util.Set extractMedicationUnitSet(ims.domain.ILightweightDomainFactory domainFactory, ims.core.vo.MedicationUnitVoCollection voCollection) { return extractMedicationUnitSet(domainFactory, voCollection, null, new HashMap()); } public static java.util.Set extractMedicationUnitSet(ims.domain.ILightweightDomainFactory domainFactory, ims.core.vo.MedicationUnitVoCollection voCollection, java.util.Set domainObjectSet, HashMap domMap) { int size = (null == voCollection) ? 0 : voCollection.size(); if (domainObjectSet == null) { domainObjectSet = new java.util.HashSet(); } java.util.Set newSet = new java.util.HashSet(); for(int i=0; i<size; i++) { ims.core.vo.MedicationUnitVo vo = voCollection.get(i); ims.core.clinical.domain.objects.MedicationUnit domainObject = MedicationUnitVoAssembler.extractMedicationUnit(domainFactory, vo, domMap); //TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it. if (domainObject == null) { continue; } //Trying to avoid the hibernate collection being marked as dirty via its public interface methods. (like add) if (!domainObjectSet.contains(domainObject)) domainObjectSet.add(domainObject); newSet.add(domainObject); } java.util.Set removedSet = new java.util.HashSet(); java.util.Iterator iter = domainObjectSet.iterator(); //Find out which objects need to be removed while (iter.hasNext()) { ims.domain.DomainObject o = (ims.domain.DomainObject)iter.next(); if ((o == null || o.getIsRIE() == null || !o.getIsRIE().booleanValue()) && !newSet.contains(o)) { removedSet.add(o); } } iter = removedSet.iterator(); //Remove the unwanted objects while (iter.hasNext()) { domainObjectSet.remove(iter.next()); } return domainObjectSet; } /** * Create the ims.core.clinical.domain.objects.MedicationUnit list from the value object collection. * @param domainFactory - used to create existing (persistent) domain objects. * @param voCollection - the collection of value objects */ public static java.util.List extractMedicationUnitList(ims.domain.ILightweightDomainFactory domainFactory, ims.core.vo.MedicationUnitVoCollection voCollection) { return extractMedicationUnitList(domainFactory, voCollection, null, new HashMap()); } public static java.util.List extractMedicationUnitList(ims.domain.ILightweightDomainFactory domainFactory, ims.core.vo.MedicationUnitVoCollection voCollection, java.util.List domainObjectList, HashMap domMap) { int size = (null == voCollection) ? 0 : voCollection.size(); if (domainObjectList == null) { domainObjectList = new java.util.ArrayList(); } for(int i=0; i<size; i++) { ims.core.vo.MedicationUnitVo vo = voCollection.get(i); ims.core.clinical.domain.objects.MedicationUnit domainObject = MedicationUnitVoAssembler.extractMedicationUnit(domainFactory, vo, domMap); //TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it. if (domainObject == null) { continue; } int domIdx = domainObjectList.indexOf(domainObject); if (domIdx == -1) { domainObjectList.add(i, domainObject); } else if (i != domIdx && i < domainObjectList.size()) { Object tmp = domainObjectList.get(i); domainObjectList.set(i, domainObjectList.get(domIdx)); domainObjectList.set(domIdx, tmp); } } //Remove all ones in domList where index > voCollection.size() as these should //now represent the ones removed from the VO collection. No longer referenced. int i1=domainObjectList.size(); while (i1 > size) { domainObjectList.remove(i1-1); i1=domainObjectList.size(); } return domainObjectList; } /** * Create the ValueObject from the ims.core.clinical.domain.objects.MedicationUnit object. * @param domainObject ims.core.clinical.domain.objects.MedicationUnit */ public static ims.core.vo.MedicationUnitVo create(ims.core.clinical.domain.objects.MedicationUnit domainObject) { if (null == domainObject) { return null; } DomainObjectMap map = new DomainObjectMap(); return create(map, domainObject); } /** * Create the ValueObject from the ims.core.clinical.domain.objects.MedicationUnit object. * @param map DomainObjectMap of DomainObjects to already created ValueObjects. * @param domainObject */ public static ims.core.vo.MedicationUnitVo create(DomainObjectMap map, ims.core.clinical.domain.objects.MedicationUnit domainObject) { if (null == domainObject) { return null; } // check if the domainObject already has a valueObject created for it ims.core.vo.MedicationUnitVo valueObject = (ims.core.vo.MedicationUnitVo) map.getValueObject(domainObject, ims.core.vo.MedicationUnitVo.class); if ( null == valueObject ) { valueObject = new ims.core.vo.MedicationUnitVo(domainObject.getId(), domainObject.getVersion()); map.addValueObject(domainObject, valueObject); valueObject = insert(map, valueObject, domainObject); } return valueObject; } /** * Update the ValueObject with the Domain Object. * @param valueObject to be updated * @param domainObject ims.core.clinical.domain.objects.MedicationUnit */ public static ims.core.vo.MedicationUnitVo insert(ims.core.vo.MedicationUnitVo valueObject, ims.core.clinical.domain.objects.MedicationUnit domainObject) { if (null == domainObject) { return valueObject; } DomainObjectMap map = new DomainObjectMap(); return insert(map, valueObject, domainObject); } /** * Update the ValueObject with the Domain Object. * @param map DomainObjectMap of DomainObjects to already created ValueObjects. * @param valueObject to be updated * @param domainObject ims.core.clinical.domain.objects.MedicationUnit */ public static ims.core.vo.MedicationUnitVo insert(DomainObjectMap map, ims.core.vo.MedicationUnitVo valueObject, ims.core.clinical.domain.objects.MedicationUnit domainObject) { if (null == domainObject) { return valueObject; } if (null == map) { map = new DomainObjectMap(); } valueObject.setID_MedicationUnit(domainObject.getId()); valueObject.setIsRIE(domainObject.getIsRIE()); // If this is a recordedInError record, and the domainObject // value isIncludeRecord has not been set, then we return null and // not the value object if (valueObject.getIsRIE() != null && valueObject.getIsRIE().booleanValue() == true && !domainObject.isIncludeRecord()) return null; // If this is not a recordedInError record, and the domainObject // value isIncludeRecord has been set, then we return null and // not the value object if ((valueObject.getIsRIE() == null || valueObject.getIsRIE().booleanValue() == false) && domainObject.isIncludeRecord()) return null; // DoseUnit ims.domain.lookups.LookupInstance instance1 = domainObject.getDoseUnit(); if ( null != instance1 ) { ims.framework.utils.ImagePath img = null; ims.framework.utils.Color color = null; img = null; if (instance1.getImage() != null) { img = new ims.framework.utils.ImagePath(instance1.getImage().getImageId(), instance1.getImage().getImagePath()); } color = instance1.getColor(); if (color != null) color.getValue(); ims.core.vo.lookups.MedicationDoseUnit voLookup1 = new ims.core.vo.lookups.MedicationDoseUnit(instance1.getId(),instance1.getText(), instance1.isActive(), null, img, color); ims.core.vo.lookups.MedicationDoseUnit parentVoLookup1 = voLookup1; ims.domain.lookups.LookupInstance parent1 = instance1.getParent(); while (parent1 != null) { if (parent1.getImage() != null) { img = new ims.framework.utils.ImagePath(parent1.getImage().getImageId(), parent1.getImage().getImagePath() ); } else { img = null; } color = parent1.getColor(); if (color != null) color.getValue(); parentVoLookup1.setParent(new ims.core.vo.lookups.MedicationDoseUnit(parent1.getId(),parent1.getText(), parent1.isActive(), null, img, color)); parentVoLookup1 = parentVoLookup1.getParent(); parent1 = parent1.getParent(); } valueObject.setDoseUnit(voLookup1); } return valueObject; } /** * Create the domain object from the value object. * @param domainFactory - used to create existing (persistent) domain objects. * @param valueObject - extract the domain object fields from this. */ public static ims.core.clinical.domain.objects.MedicationUnit extractMedicationUnit(ims.domain.ILightweightDomainFactory domainFactory, ims.core.vo.MedicationUnitVo valueObject) { return extractMedicationUnit(domainFactory, valueObject, new HashMap()); } public static ims.core.clinical.domain.objects.MedicationUnit extractMedicationUnit(ims.domain.ILightweightDomainFactory domainFactory, ims.core.vo.MedicationUnitVo valueObject, HashMap domMap) { if (null == valueObject) { return null; } Integer id = valueObject.getID_MedicationUnit(); ims.core.clinical.domain.objects.MedicationUnit domainObject = null; if ( null == id) { if (domMap.get(valueObject) != null) { return (ims.core.clinical.domain.objects.MedicationUnit)domMap.get(valueObject); } // ims.core.vo.MedicationUnitVo ID_MedicationUnit field is unknown domainObject = new ims.core.clinical.domain.objects.MedicationUnit(); domMap.put(valueObject, domainObject); } else { String key = (valueObject.getClass().getName() + "__" + valueObject.getID_MedicationUnit()); if (domMap.get(key) != null) { return (ims.core.clinical.domain.objects.MedicationUnit)domMap.get(key); } domainObject = (ims.core.clinical.domain.objects.MedicationUnit) domainFactory.getDomainObject(ims.core.clinical.domain.objects.MedicationUnit.class, id ); //TODO: Not sure how this should be handled. Effectively it must be a staleobject exception, but maybe should be handled as that further up. if (domainObject == null) return null; domMap.put(key, domainObject); } domainObject.setVersion(valueObject.getVersion_MedicationUnit()); // create LookupInstance from vo LookupType ims.domain.lookups.LookupInstance value1 = null; if ( null != valueObject.getDoseUnit() ) { value1 = domainFactory.getLookupInstance(valueObject.getDoseUnit().getID()); } domainObject.setDoseUnit(value1); return domainObject; } }
agpl-3.0
open-health-hub/openmaxims-linux
openmaxims_workspace/Scheduling/src/ims/scheduling/forms/patientappointmentmanagement/BaseLogic.java
2394
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program 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. # //# # //# 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 Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751) // Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.scheduling.forms.patientappointmentmanagement; public abstract class BaseLogic extends Handlers { public final Class getDomainInterface() throws ClassNotFoundException { return ims.scheduling.domain.PatientAppointmentManagement.class; } public final void setContext(ims.framework.UIEngine engine, GenForm form, ims.scheduling.domain.PatientAppointmentManagement domain) { setContext(engine, form); this.domain = domain; } public void clearContextInformation() { engine.clearPatientContextInformation(); } public final void free() { super.free(); domain = null; } protected ims.scheduling.domain.PatientAppointmentManagement domain; }
agpl-3.0
open-health-hub/openmaxims-linux
openmaxims_workspace/ValueObjects/src/ims/admin/vo/beans/Icd10AmProcVoBean.java
6215
//############################################################################# //# # //# Copyright (C) <2014> <IMS MAXIMS> # //# # //# This program 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. # //# # //# 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 Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751) // Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.admin.vo.beans; public class Icd10AmProcVoBean extends ims.vo.ValueObjectBean { public Icd10AmProcVoBean() { } public Icd10AmProcVoBean(ims.admin.vo.Icd10AmProcVo vo) { this.id = vo.getBoId(); this.version = vo.getBoVersion(); this.code_id = vo.getCode_id(); this.block = vo.getBlock() == null ? null : (ims.admin.vo.beans.Icd10AmBlockVoBean)vo.getBlock().getBean(); this.ascii_desc = vo.getAscii_desc(); this.ascii_short_desc = vo.getAscii_short_desc(); this.effective_from = vo.getEffective_from() == null ? null : (ims.framework.utils.beans.DateBean)vo.getEffective_from().getBean(); this.inactive = vo.getInactive() == null ? null : (ims.framework.utils.beans.DateBean)vo.getInactive().getBean(); this.sex = vo.getSex(); this.stype = vo.getStype(); this.agel = vo.getAgeL(); this.agelh = vo.getAgelH(); this.atype = vo.getAtype(); } public void populate(ims.vo.ValueObjectBeanMap map, ims.admin.vo.Icd10AmProcVo vo) { this.id = vo.getBoId(); this.version = vo.getBoVersion(); this.code_id = vo.getCode_id(); this.block = vo.getBlock() == null ? null : (ims.admin.vo.beans.Icd10AmBlockVoBean)vo.getBlock().getBean(map); this.ascii_desc = vo.getAscii_desc(); this.ascii_short_desc = vo.getAscii_short_desc(); this.effective_from = vo.getEffective_from() == null ? null : (ims.framework.utils.beans.DateBean)vo.getEffective_from().getBean(); this.inactive = vo.getInactive() == null ? null : (ims.framework.utils.beans.DateBean)vo.getInactive().getBean(); this.sex = vo.getSex(); this.stype = vo.getStype(); this.agel = vo.getAgeL(); this.agelh = vo.getAgelH(); this.atype = vo.getAtype(); } public ims.admin.vo.Icd10AmProcVo buildVo() { return this.buildVo(new ims.vo.ValueObjectBeanMap()); } public ims.admin.vo.Icd10AmProcVo buildVo(ims.vo.ValueObjectBeanMap map) { ims.admin.vo.Icd10AmProcVo vo = null; if(map != null) vo = (ims.admin.vo.Icd10AmProcVo)map.getValueObject(this); if(vo == null) { vo = new ims.admin.vo.Icd10AmProcVo(); map.addValueObject(this, vo); vo.populate(map, this); } return vo; } public Integer getId() { return this.id; } public void setId(Integer value) { this.id = value; } public int getVersion() { return this.version; } public void setVersion(int value) { this.version = value; } public String getCode_id() { return this.code_id; } public void setCode_id(String value) { this.code_id = value; } public ims.admin.vo.beans.Icd10AmBlockVoBean getBlock() { return this.block; } public void setBlock(ims.admin.vo.beans.Icd10AmBlockVoBean value) { this.block = value; } public String getAscii_desc() { return this.ascii_desc; } public void setAscii_desc(String value) { this.ascii_desc = value; } public String getAscii_short_desc() { return this.ascii_short_desc; } public void setAscii_short_desc(String value) { this.ascii_short_desc = value; } public ims.framework.utils.beans.DateBean getEffective_from() { return this.effective_from; } public void setEffective_from(ims.framework.utils.beans.DateBean value) { this.effective_from = value; } public ims.framework.utils.beans.DateBean getInactive() { return this.inactive; } public void setInactive(ims.framework.utils.beans.DateBean value) { this.inactive = value; } public Integer getSex() { return this.sex; } public void setSex(Integer value) { this.sex = value; } public Integer getStype() { return this.stype; } public void setStype(Integer value) { this.stype = value; } public Integer getAgeL() { return this.agel; } public void setAgeL(Integer value) { this.agel = value; } public Integer getAgelH() { return this.agelh; } public void setAgelH(Integer value) { this.agelh = value; } public Integer getAtype() { return this.atype; } public void setAtype(Integer value) { this.atype = value; } private Integer id; private int version; private String code_id; private ims.admin.vo.beans.Icd10AmBlockVoBean block; private String ascii_desc; private String ascii_short_desc; private ims.framework.utils.beans.DateBean effective_from; private ims.framework.utils.beans.DateBean inactive; private Integer sex; private Integer stype; private Integer agel; private Integer agelh; private Integer atype; }
agpl-3.0
FreudianNM/openMAXIMS
Source Library/openmaxims_workspace/Core/src/ims/core/forms/reportstomodalityconfigform/FormInfo.java
3043
//############################################################################# //# # //# Copyright (C) <2015> <IMS MAXIMS> # //# # //# This program 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. # //# # //# 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 Affero General Public License for more details. # //# # //# You should have received a copy of the GNU Affero General Public License # //# along with this program. If not, see <http://www.gnu.org/licenses/>. # //# # //# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of # //# this program. Users of this software do so entirely at their own risk. # //# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time # //# software that it builds, deploys and maintains. # //# # //############################################################################# //#EOH // This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814) // Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved. // WARNING: DO NOT MODIFY the content of this file package ims.core.forms.reportstomodalityconfigform; public final class FormInfo extends ims.framework.FormInfo { private static final long serialVersionUID = 1L; public FormInfo(Integer formId) { super(formId); } public String getNamespaceName() { return "Core"; } public String getFormName() { return "ReportsToModalityConfigForm"; } public int getWidth() { return 848; } public int getHeight() { return 632; } public String[] getContextVariables() { return new String[] { "_cv_Core.ModalityReport" }; } public String getLocalVariablesPrefix() { return "_lv_Core.ReportsToModalityConfigForm.__internal_x_context__" + String.valueOf(getFormId()); } public ims.framework.FormInfo[] getComponentsFormInfo() { ims.framework.FormInfo[] componentsInfo = new ims.framework.FormInfo[0]; return componentsInfo; } public String getImagePath() { return ""; } }
agpl-3.0
Tanaguru/Tanaguru
engine/persistence/src/main/java/org/tanaguru/entity/dao/audit/AuditDAOImpl.java
2500
/* * Tanaguru - Automated webpage assessment * Copyright (C) 2008-2015 Tanaguru.org * * This file is part of Tanaguru. * * Tanaguru 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. * * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * * Contact us by mail: tanaguru AT tanaguru DOT org */ package org.tanaguru.entity.dao.audit; import java.util.List; import javax.persistence.NoResultException; import javax.persistence.Query; import org.tanaguru.entity.audit.Audit; import org.tanaguru.entity.audit.AuditImpl; import org.tanaguru.entity.audit.AuditStatus; import org.tanaguru.sdk.entity.dao.jpa.AbstractJPADAO; /** * * @author jkowalczyk */ public class AuditDAOImpl extends AbstractJPADAO<Audit, Long> implements AuditDAO { public AuditDAOImpl() { super(); } @Override public List<Audit> findAll() { List<Audit> auditList = super.findAll(); return auditList; } @Override public List<Audit> findAll(AuditStatus status) { Query query = entityManager.createQuery("SELECT o FROM " + getEntityClass().getName() + " o" + " LEFT JOIN FETCH o.subject" + " WHERE o.status = :status"); query.setParameter("status", status); return (List<Audit>)query.getResultList(); } @Override protected Class<AuditImpl> getEntityClass() { return AuditImpl.class; } @Override public Audit findAuditWithTest(Long id) { Query query = entityManager.createQuery("SELECT a FROM " + getEntityClass().getName() + " a" + " LEFT JOIN FETCH a.testList" + " WHERE a.id = :id"); query.setParameter("id", id); try { return (Audit)query.getSingleResult(); } catch (NoResultException nre) { return null; } } }
agpl-3.0
NicolasEYSSERIC/Silverpeas-Components
project-manager/project-manager-ejb/src/main/java/com/silverpeas/projectManager/model/HolidayDetail.java
2178
/** * Copyright (C) 2000 - 2011 Silverpeas * * This program 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. * * As a special exception to the terms and conditions of version 3.0 of * the GPL, you may redistribute this Program in connection with Free/Libre * Open Source Software ("FLOSS") applications as described in Silverpeas's * FLOSS exception. You should have received a copy of the text describing * the FLOSS exception, and it is also available here: * "http://repository.silverpeas.com/legal/licensing" * * 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 Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.silverpeas.projectManager.model; import java.io.Serializable; import java.util.Date; /** * @author neysseri */ public class HolidayDetail implements Serializable { private static final long serialVersionUID = 5791543598843818180L; private Date holidayDate = null; private String instanceId = null; private int fatherId = -1; public HolidayDetail(Date holidayDate, int fatherId, String instanceId) { setDate(holidayDate); setInstanceId(instanceId); setFatherId(fatherId); } /** * @return */ public int getFatherId() { return fatherId; } /** * @return */ public Date getDate() { return holidayDate; } /** * @return */ public String getInstanceId() { return instanceId; } /** * @param i */ public void setFatherId(int i) { fatherId = i; } /** * @param date */ public void setDate(Date date) { holidayDate = date; } /** * @param string */ public void setInstanceId(String string) { instanceId = string; } }
agpl-3.0
xwiki-labs/sankoreorg
xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/web/XWikiServletRequestStub.java
6881
package com.xpn.xwiki.web; import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.UnsupportedEncodingException; import java.security.Principal; import java.util.Enumeration; import java.util.Locale; import java.util.Map; import javax.portlet.PortalContext; import javax.portlet.PortletMode; import javax.portlet.PortletPreferences; import javax.portlet.PortletSession; import javax.portlet.WindowState; import javax.servlet.RequestDispatcher; import javax.servlet.ServletInputStream; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpSession; /** * This stub is intended to simulate a servlet request in a daemon context, in order to be able to create a custom XWiki * context. This trick is used in to give a daemon thread access to the XWiki api. * * @version $Id$ */ public class XWikiServletRequestStub implements XWikiRequest { /** The scheme used by the runtime instance. This is required for creating URLs from daemon thread. */ private String scheme; public XWikiServletRequestStub() { this.host = ""; } private String host; public void setHost(String host) { this.host = host; } public String getHeader(String s) { if (s.equals("x-forwarded-host")) { return this.host; } return ""; } public String get(String name) { return ""; } public HttpServletRequest getHttpServletRequest() { return null; } public Cookie getCookie(String cookieName) { return null; } public boolean isWindowStateAllowed(WindowState windowState) { return false; } public boolean isPortletModeAllowed(PortletMode portletMode) { return false; } public PortletMode getPortletMode() { return null; } public WindowState getWindowState() { return null; } public PortletPreferences getPreferences() { return null; } public PortletSession getPortletSession() { return null; } public PortletSession getPortletSession(boolean b) { return null; } public String getProperty(String s) { return null; } public Enumeration getProperties(String s) { return null; } public Enumeration getPropertyNames() { return null; } public PortalContext getPortalContext() { return null; } public String getAuthType() { return ""; } public Cookie[] getCookies() { return new Cookie[0]; } public long getDateHeader(String s) { return 0; } public Enumeration getHeaders(String s) { return null; } public Enumeration getHeaderNames() { return null; } public int getIntHeader(String s) { return 0; } public String getMethod() { return null; } public String getPathInfo() { return null; } public String getPathTranslated() { return null; } public String getContextPath() { return null; } public String getQueryString() { return ""; } public String getRemoteUser() { return null; } public boolean isUserInRole(String s) { return false; } public Principal getUserPrincipal() { return null; } public String getRequestedSessionId() { return null; } public String getRequestURI() { return null; } public StringBuffer getRequestURL() { return new StringBuffer(); } public String getServletPath() { return null; } public HttpSession getSession(boolean b) { return null; } public HttpSession getSession() { return null; } public boolean isRequestedSessionIdValid() { return false; } public String getResponseContentType() { return null; } public Enumeration getResponseContentTypes() { return null; } public boolean isRequestedSessionIdFromCookie() { return false; } public boolean isRequestedSessionIdFromURL() { return false; } /** * @deprecated */ @Deprecated public boolean isRequestedSessionIdFromUrl() { return false; } public Object getAttribute(String s) { return null; } public Enumeration getAttributeNames() { return null; } public String getCharacterEncoding() { return null; } public InputStream getPortletInputStream() throws IOException { return null; } public void setCharacterEncoding(String s) throws UnsupportedEncodingException { } public int getContentLength() { return 0; } public String getContentType() { return null; } public ServletInputStream getInputStream() throws IOException { return null; } public String getParameter(String s) { return null; } public Enumeration getParameterNames() { return null; } public String[] getParameterValues(String s) { return new String[0]; } public Map getParameterMap() { return null; } public String getProtocol() { return null; } public void setScheme(String scheme) { this.scheme = scheme; } public String getScheme() { return scheme; } public String getServerName() { return null; } public int getServerPort() { return 0; } public BufferedReader getReader() throws IOException { return null; } public String getRemoteAddr() { return null; } public String getRemoteHost() { return null; } public void setAttribute(String s, Object o) { } public void removeAttribute(String s) { } public Locale getLocale() { return null; } public Enumeration getLocales() { return null; } public boolean isSecure() { return false; } public RequestDispatcher getRequestDispatcher(String s) { return null; } /** * @deprecated */ @Deprecated public String getRealPath(String s) { return null; } public int getRemotePort() { return 0; } public String getLocalName() { return null; } public String getLocalAddr() { return null; } public int getLocalPort() { return 0; } }
lgpl-2.1
ggiudetti/opencms-core
src-gwt/org/opencms/ade/sitemap/client/CmsCategoryTreeItem.java
2499
/* * This library is part of OpenCms - * the Open Source Content Management System * * Copyright (c) Alkacon Software GmbH & Co. KG (http://www.alkacon.com) * * 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. * * For further information about Alkacon Software, please see the * company website: http://www.alkacon.com * * For further information about OpenCms, please see the * project website: http://www.opencms.org * * 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.opencms.ade.sitemap.client; import org.opencms.gwt.client.ui.CmsListItemWidget; import org.opencms.gwt.client.ui.tree.CmsTreeItem; import org.opencms.gwt.shared.CmsCategoryTreeEntry; import org.opencms.gwt.shared.CmsListInfoBean; import org.opencms.util.CmsUUID; /** * Widget representing a category in the category mode of the sitemap editor.<p> */ public class CmsCategoryTreeItem extends CmsTreeItem { /** Structure id of the category. */ private CmsUUID m_structureId; /** * Creates a new tree item.<p> * * @param entry the data for the tree item */ public CmsCategoryTreeItem(CmsCategoryTreeEntry entry) { super(true, new CmsListItemWidget(createCategoryListInfo(entry))); m_structureId = entry.getId(); } /** * Creates the list info bean for a tree item from a category bean.<p> * * @param entry the category data * * @return the list info bean */ public static CmsListInfoBean createCategoryListInfo(CmsCategoryTreeEntry entry) { CmsListInfoBean info = new CmsListInfoBean(entry.getTitle(), entry.getPath(), null); info.setResourceType("category"); return info; } /** * Gets the structure id.<p> * * @return the structure id */ public CmsUUID getStructureId() { return m_structureId; } }
lgpl-2.1
SuperUnitato/UnLonely
build/tmp/recompileMc/sources/net/minecraft/item/ItemSpade.java
2523
package net.minecraft.item; import com.google.common.collect.Sets; import java.util.Set; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.block.state.IBlockState; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.init.SoundEvents; import net.minecraft.util.EnumActionResult; import net.minecraft.util.EnumFacing; import net.minecraft.util.EnumHand; import net.minecraft.util.SoundCategory; import net.minecraft.util.math.BlockPos; import net.minecraft.world.World; public class ItemSpade extends ItemTool { private static final Set<Block> EFFECTIVE_ON = Sets.newHashSet(new Block[] {Blocks.CLAY, Blocks.DIRT, Blocks.FARMLAND, Blocks.GRASS, Blocks.GRAVEL, Blocks.MYCELIUM, Blocks.SAND, Blocks.SNOW, Blocks.SNOW_LAYER, Blocks.SOUL_SAND, Blocks.GRASS_PATH}); public ItemSpade(Item.ToolMaterial material) { super(1.5F, -3.0F, material, EFFECTIVE_ON); } /** * Check whether this Item can harvest the given Block */ public boolean canHarvestBlock(IBlockState blockIn) { Block block = blockIn.getBlock(); return block == Blocks.SNOW_LAYER ? true : block == Blocks.SNOW; } /** * Called when a Block is right-clicked with this Item */ public EnumActionResult onItemUse(EntityPlayer player, World worldIn, BlockPos pos, EnumHand hand, EnumFacing facing, float hitX, float hitY, float hitZ) { ItemStack itemstack = player.getHeldItem(hand); if (!player.canPlayerEdit(pos.offset(facing), facing, itemstack)) { return EnumActionResult.FAIL; } else { IBlockState iblockstate = worldIn.getBlockState(pos); Block block = iblockstate.getBlock(); if (facing != EnumFacing.DOWN && worldIn.getBlockState(pos.up()).getMaterial() == Material.AIR && block == Blocks.GRASS) { IBlockState iblockstate1 = Blocks.GRASS_PATH.getDefaultState(); worldIn.playSound(player, pos, SoundEvents.ITEM_SHOVEL_FLATTEN, SoundCategory.BLOCKS, 1.0F, 1.0F); if (!worldIn.isRemote) { worldIn.setBlockState(pos, iblockstate1, 11); itemstack.damageItem(1, player); } return EnumActionResult.SUCCESS; } else { return EnumActionResult.PASS; } } } }
lgpl-2.1
ggiudetti/opencms-core
test/org/opencms/configuration/TestConfiguration.java
4500
/* * This library is part of OpenCms - * the Open Source Content Management System * * Copyright (c) Alkacon Software GmbH & Co. KG (http://www.alkacon.com) * * 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. * * For further information about Alkacon Software GmbH & Co. KG, please see the * company website: http://www.alkacon.com * * For further information about OpenCms, please see the * project website: http://www.opencms.org * * 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.opencms.configuration; import org.opencms.file.CmsResource; import org.opencms.i18n.CmsEncoder; import org.opencms.test.OpenCmsTestCase; import org.opencms.test.OpenCmsTestProperties; import org.opencms.xml.CmsXmlEntityResolver; import org.opencms.xml.CmsXmlUtils; import java.io.FileInputStream; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.dom4j.Document; import org.xml.sax.InputSource; /** * Tests for the OpenCms configuration handling.<p> * * @since 6.0.0 */ public class TestConfiguration extends OpenCmsTestCase { /** * Default JUnit constructor.<p> * * @param arg0 JUnit parameters */ public TestConfiguration(String arg0) { super(arg0, false); } /** * Loads the configuration using the configuration manager, * if anyting goes wrong an exception is thrown and the test fails.<p> * * * @throws Exception if something goes wrong */ public void testLoadXmlConfiguration() throws Exception { // get the file name of the input resource String inputFile = CmsResource.getParentFolder( OpenCmsTestProperties.getResourcePathFromClassloader("org/opencms/configuration/opencms.xml")); // generate the configuration manager CmsConfigurationManager manager = new CmsConfigurationManager(inputFile); // now digest the XML manager.loadXmlConfiguration(); CmsWorkplaceConfiguration wpConfig = (CmsWorkplaceConfiguration)manager.getConfiguration( CmsWorkplaceConfiguration.class); wpConfig.getWorkplaceManager().getDefaultUserSettings().initPreferences(wpConfig.getWorkplaceManager()); // generate an output XML format List<I_CmsXmlConfiguration> allConfigurations = new ArrayList<I_CmsXmlConfiguration>(); allConfigurations.add(manager); allConfigurations.addAll(manager.getConfigurations()); Iterator<I_CmsXmlConfiguration> i = allConfigurations.iterator(); while (i.hasNext()) { I_CmsXmlConfiguration config = i.next(); String xmlOrigFile = inputFile + config.getXmlFileName(); System.out.println("\n\nConfiguration instance: " + config + ":\n"); // generate XML document for the configuration Document outputDoc = manager.generateXml(config); outputDoc.setName(config.getXmlFileName()); // load XML from original file and compare to generated document InputSource source = new InputSource(new FileInputStream(xmlOrigFile)); Document inputDoc = CmsXmlUtils.unmarshalHelper(source, new CmsXmlEntityResolver(null)); // output the document System.out.println("---"); System.out.println(CmsXmlUtils.marshal(outputDoc, CmsEncoder.ENCODING_UTF_8)); System.out.println("---"); // it's better to not output the original doc, since spotting an error is easier // if you compare console output to the original input file in your IDE // System.out.println("+++"); // System.out.println(CmsXmlUtils.marshal(inputDoc, CmsEncoder.ENCODING_UTF_8)); // System.out.println("+++"); assertEquals(outputDoc, inputDoc); } } }
lgpl-2.1
SonarQubeCommunity/sonar-css
css-checks/src/main/java/org/sonar/css/checks/LeadingZeroCheck.java
1685
/* * SonarQube CSS Plugin * Copyright (C) 2013-2016 Tamas Kende and David RACODON * mailto: kende.tamas@gmail.com and david.racodon@gmail.com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.css.checks; import org.sonar.check.Priority; import org.sonar.check.Rule; import org.sonar.plugins.css.api.tree.NumberTree; import org.sonar.plugins.css.api.visitors.DoubleDispatchVisitorCheck; import org.sonar.squidbridge.annotations.ActivatedByDefault; import org.sonar.squidbridge.annotations.SqaleConstantRemediation; @Rule( key = "leading-zeros", name = "Leading zeros should be removed", priority = Priority.MINOR, tags = {Tags.CONVENTION}) @ActivatedByDefault @SqaleConstantRemediation("2min") public class LeadingZeroCheck extends DoubleDispatchVisitorCheck { @Override public void visitNumber(NumberTree tree) { if (tree.text().startsWith("0.")) { addPreciseIssue(tree, "Remove the leading zero."); } super.visitNumber(tree); } }
lgpl-3.0
hy2708/hy2708-repository
java/commons/commons-lang/src/main/java/org/hy/commons/lang/character/FullCharConverter.java
3837
package org.hy.commons.lang.character; import java.io.UnsupportedEncodingException; /** * 特殊字符串转换 * * @Class Name FullCharConverter * @Author v-jiangwei * @Create In 2012-8-24 */ public class FullCharConverter { /** * 全角转半角的 转换函数 * * @Methods Name full2HalfChange * @Create In 2012-8-24 By v-jiangwei * @param QJstr * @return String */ public static final String full2HalfChange(String QJstr) { StringBuffer outStrBuf = new StringBuffer(""); String Tstr = ""; byte[] b = null; for (int i = 0; i < QJstr.length(); i++) { Tstr = QJstr.substring(i, i + 1); // 全角空格转换成半角空格 if (Tstr.equals(" ")) { outStrBuf.append(" "); continue; } try { b = Tstr.getBytes("unicode"); // 得到 unicode 字节数据 if (b[2] == -1) { // 表示全角 b[3] = (byte) (b[3] + 32); b[2] = 0; outStrBuf.append(new String(b, "unicode")); } else { outStrBuf.append(Tstr); } } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } // end for. return outStrBuf.toString(); } /** * 半角转全角 * * @Methods Name half2Fullchange * @Create In 2012-8-24 By v-jiangwei * @param QJstr * @return String */ public static final String half2Fullchange(String QJstr) { StringBuffer outStrBuf = new StringBuffer(""); String Tstr = ""; byte[] b = null; for (int i = 0; i < QJstr.length(); i++) { Tstr = QJstr.substring(i, i + 1); if (Tstr.equals(" ")) { // 半角空格 outStrBuf.append(Tstr); continue; } try { b = Tstr.getBytes("unicode"); if (b[2] == 0) { // 半角 b[3] = (byte) (b[3] - 32); b[2] = -1; outStrBuf.append(new String(b, "unicode")); } else { outStrBuf.append(Tstr); } return outStrBuf.toString(); } catch (UnsupportedEncodingException e) { // TODO Auto-generated catch block e.printStackTrace(); } } return outStrBuf.toString(); } /** * 全角转半角 * @param input String. * @return 半角字符串 */ public static String ToDBC(String input) { char c[] = input.toCharArray(); return ToDBC(c); } public static String ToDBC(char c[]) { //char c[] = input.toCharArray(); for (int i = 0; i < c.length; i++) { if (c[i] == '\u3000') { c[i] = ' '; } else if (c[i] > '\uFF00' && c[i] < '\uFF5F') { c[i] = (char) (c[i] - 65248); } } String returnString = new String(c); return returnString; } /** * 半角转全角 * @param input String. * @return 全角字符串. */ public static String ToSBC(String input) { char c[] = input.toCharArray(); for (int i = 0; i < c.length; i++) { if (c[i] == ' ') { c[i] = '\u3000'; } else if (c[i] < '\177') { c[i] = (char) (c[i] + 65248); } } return new String(c); } /** * @Methods Name main * @Create In 2012-8-24 By v-jiangwei * @param args * void */ public static void main(String[] args) { // TODO Auto-generated method stub String QJstr = "814乡道"; String result = FullCharConverter.ToDBC(QJstr); System.out.println(QJstr); System.out.println(result); System.out.println("------------------------------------"); // 半角转全角 String str = "大G45大广高速"; String reString =FullCharConverter.ToSBC(str); System.out.println(str); System.out.println(reString); } }
lgpl-3.0
yogthos/itext
src/com/lowagie/text/pdf/PdfAction.java
23194
/* * $Id: PdfAction.java 4065 2009-09-16 23:09:11Z psoares33 $ * * Copyright 2000 by Bruno Lowagie. * * 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 'iText, a free JAVA-PDF library'. * * The Initial Developer of the Original Code is Bruno Lowagie. Portions created by * the Initial Developer are Copyright (C) 1999, 2000, 2001, 2002 by Bruno Lowagie. * All Rights Reserved. * Co-Developer of the code is Paulo Soares. Portions created by the Co-Developer * are Copyright (C) 2000, 2001, 2002 by Paulo Soares. All Rights Reserved. * * Contributor(s): all the names of the contributors are added in the source code * where applicable. * * Alternatively, the contents of this file may be used under the terms of the * LGPL license (the "GNU LIBRARY GENERAL PUBLIC LICENSE"), in which case the * provisions of LGPL are applicable instead of those above. If you wish to * allow use of your version of this file only under the terms of the LGPL * License and not to allow others to use your version of this file under * the MPL, indicate your decision by deleting the provisions above and * replace them with the notice and other provisions required by the LGPL. * If you do not delete the provisions above, a recipient may use your version * of this file under either the MPL or the GNU LIBRARY GENERAL PUBLIC LICENSE. * * This library is free software; you can redistribute it and/or modify it * under the terms of the MPL as stated above or under the terms of the GNU * Library General Public License as published by the Free Software Foundation; * either version 2 of the License, or any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Library general Public License for more * details. * * If you didn't download this code from the following link, you should check if * you aren't using an obsolete version: * http://www.lowagie.com/iText/ */ package com.lowagie.text.pdf; import java.io.IOException; import java.net.URL; import java.util.ArrayList; import com.lowagie.text.error_messages.MessageLocalization; import com.lowagie.text.pdf.collection.PdfTargetDictionary; /** * A <CODE>PdfAction</CODE> defines an action that can be triggered from a PDF file. * * @see PdfDictionary */ public class PdfAction extends PdfDictionary { /** A named action to go to the first page. */ public static final int FIRSTPAGE = 1; /** A named action to go to the previous page. */ public static final int PREVPAGE = 2; /** A named action to go to the next page. */ public static final int NEXTPAGE = 3; /** A named action to go to the last page. */ public static final int LASTPAGE = 4; /** A named action to open a print dialog. */ public static final int PRINTDIALOG = 5; /** a possible submitvalue */ public static final int SUBMIT_EXCLUDE = 1; /** a possible submitvalue */ public static final int SUBMIT_INCLUDE_NO_VALUE_FIELDS = 2; /** a possible submitvalue */ public static final int SUBMIT_HTML_FORMAT = 4; /** a possible submitvalue */ public static final int SUBMIT_HTML_GET = 8; /** a possible submitvalue */ public static final int SUBMIT_COORDINATES = 16; /** a possible submitvalue */ public static final int SUBMIT_XFDF = 32; /** a possible submitvalue */ public static final int SUBMIT_INCLUDE_APPEND_SAVES = 64; /** a possible submitvalue */ public static final int SUBMIT_INCLUDE_ANNOTATIONS = 128; /** a possible submitvalue */ public static final int SUBMIT_PDF = 256; /** a possible submitvalue */ public static final int SUBMIT_CANONICAL_FORMAT = 512; /** a possible submitvalue */ public static final int SUBMIT_EXCL_NON_USER_ANNOTS = 1024; /** a possible submitvalue */ public static final int SUBMIT_EXCL_F_KEY = 2048; /** a possible submitvalue */ public static final int SUBMIT_EMBED_FORM = 8196; /** a possible submitvalue */ public static final int RESET_EXCLUDE = 1; // constructors /** Create an empty action. */ public PdfAction() { } /** * Constructs a new <CODE>PdfAction</CODE> of Subtype URI. * * @param url the Url to go to */ public PdfAction(URL url) { this(url.toExternalForm()); } /** * Construct a new <CODE>PdfAction</CODE> of Subtype URI that accepts the x and y coordinate of the position that was clicked. * @param url * @param isMap */ public PdfAction(URL url, boolean isMap) { this(url.toExternalForm(), isMap); } /** * Constructs a new <CODE>PdfAction</CODE> of Subtype URI. * * @param url the url to go to */ public PdfAction(String url) { this(url, false); } /** * Construct a new <CODE>PdfAction</CODE> of Subtype URI that accepts the x and y coordinate of the position that was clicked. * @param url * @param isMap */ public PdfAction(String url, boolean isMap) { put(PdfName.S, PdfName.URI); put(PdfName.URI, new PdfString(url)); if (isMap) put(PdfName.ISMAP, PdfBoolean.PDFTRUE); } /** * Constructs a new <CODE>PdfAction</CODE> of Subtype GoTo. * @param destination the destination to go to */ PdfAction(PdfIndirectReference destination) { put(PdfName.S, PdfName.GOTO); put(PdfName.D, destination); } /** * Constructs a new <CODE>PdfAction</CODE> of Subtype GoToR. * @param filename the file name to go to * @param name the named destination to go to */ public PdfAction(String filename, String name) { put(PdfName.S, PdfName.GOTOR); put(PdfName.F, new PdfString(filename)); put(PdfName.D, new PdfString(name)); } /** * Constructs a new <CODE>PdfAction</CODE> of Subtype GoToR. * @param filename the file name to go to * @param page the page destination to go to */ public PdfAction(String filename, int page) { put(PdfName.S, PdfName.GOTOR); put(PdfName.F, new PdfString(filename)); put(PdfName.D, new PdfLiteral("[" + (page - 1) + " /FitH 10000]")); } /** Implements name actions. The action can be FIRSTPAGE, LASTPAGE, * NEXTPAGE, PREVPAGE and PRINTDIALOG. * @param named the named action */ public PdfAction(int named) { put(PdfName.S, PdfName.NAMED); switch (named) { case FIRSTPAGE: put(PdfName.N, PdfName.FIRSTPAGE); break; case LASTPAGE: put(PdfName.N, PdfName.LASTPAGE); break; case NEXTPAGE: put(PdfName.N, PdfName.NEXTPAGE); break; case PREVPAGE: put(PdfName.N, PdfName.PREVPAGE); break; case PRINTDIALOG: put(PdfName.S, PdfName.JAVASCRIPT); put(PdfName.JS, new PdfString("this.print(true);\r")); break; default: throw new RuntimeException(MessageLocalization.getComposedMessage("invalid.named.action")); } } /** Launches an application or a document. * @param application the application to be launched or the document to be opened or printed. * @param parameters (Windows-specific) A parameter string to be passed to the application. * It can be <CODE>null</CODE>. * @param operation (Windows-specific) the operation to perform: "open" - Open a document, * "print" - Print a document. * It can be <CODE>null</CODE>. * @param defaultDir (Windows-specific) the default directory in standard DOS syntax. * It can be <CODE>null</CODE>. */ public PdfAction(String application, String parameters, String operation, String defaultDir) { put(PdfName.S, PdfName.LAUNCH); if (parameters == null && operation == null && defaultDir == null) put(PdfName.F, new PdfString(application)); else { PdfDictionary dic = new PdfDictionary(); dic.put(PdfName.F, new PdfString(application)); if (parameters != null) dic.put(PdfName.P, new PdfString(parameters)); if (operation != null) dic.put(PdfName.O, new PdfString(operation)); if (defaultDir != null) dic.put(PdfName.D, new PdfString(defaultDir)); put(PdfName.WIN, dic); } } /** Launches an application or a document. * @param application the application to be launched or the document to be opened or printed. * @param parameters (Windows-specific) A parameter string to be passed to the application. * It can be <CODE>null</CODE>. * @param operation (Windows-specific) the operation to perform: "open" - Open a document, * "print" - Print a document. * It can be <CODE>null</CODE>. * @param defaultDir (Windows-specific) the default directory in standard DOS syntax. * It can be <CODE>null</CODE>. * @return a Launch action */ public static PdfAction createLaunch(String application, String parameters, String operation, String defaultDir) { return new PdfAction(application, parameters, operation, defaultDir); } /**Creates a Rendition action * @param file * @param fs * @param mimeType * @param ref * @return a Media Clip action * @throws IOException */ public static PdfAction rendition(String file, PdfFileSpecification fs, String mimeType, PdfIndirectReference ref) throws IOException { PdfAction js = new PdfAction(); js.put(PdfName.S, PdfName.RENDITION); js.put(PdfName.R, new PdfRendition(file, fs, mimeType)); js.put(new PdfName("OP"), new PdfNumber(0)); js.put(new PdfName("AN"), ref); return js; } /** Creates a JavaScript action. If the JavaScript is smaller than * 50 characters it will be placed as a string, otherwise it will * be placed as a compressed stream. * @param code the JavaScript code * @param writer the writer for this action * @param unicode select JavaScript unicode. Note that the internal * Acrobat JavaScript engine does not support unicode, * so this may or may not work for you * @return the JavaScript action */ public static PdfAction javaScript(String code, PdfWriter writer, boolean unicode) { PdfAction js = new PdfAction(); js.put(PdfName.S, PdfName.JAVASCRIPT); if (unicode && code.length() < 50) { js.put(PdfName.JS, new PdfString(code, PdfObject.TEXT_UNICODE)); } else if (!unicode && code.length() < 100) { js.put(PdfName.JS, new PdfString(code)); } else { try { byte b[] = PdfEncodings.convertToBytes(code, unicode ? PdfObject.TEXT_UNICODE : PdfObject.TEXT_PDFDOCENCODING); PdfStream stream = new PdfStream(b); stream.flateCompress(writer.getCompressionLevel()); js.put(PdfName.JS, writer.addToBody(stream).getIndirectReference()); } catch (Exception e) { js.put(PdfName.JS, new PdfString(code)); } } return js; } /** Creates a JavaScript action. If the JavaScript is smaller than * 50 characters it will be place as a string, otherwise it will * be placed as a compressed stream. * @param code the JavaScript code * @param writer the writer for this action * @return the JavaScript action */ public static PdfAction javaScript(String code, PdfWriter writer) { return javaScript(code, writer, false); } /** * A Hide action hides or shows an object. * @param obj object to hide or show * @param hide true is hide, false is show * @return a Hide Action */ static PdfAction createHide(PdfObject obj, boolean hide) { PdfAction action = new PdfAction(); action.put(PdfName.S, PdfName.HIDE); action.put(PdfName.T, obj); if (!hide) action.put(PdfName.H, PdfBoolean.PDFFALSE); return action; } /** * A Hide action hides or shows an annotation. * @param annot * @param hide * @return A Hide Action */ public static PdfAction createHide(PdfAnnotation annot, boolean hide) { return createHide(annot.getIndirectReference(), hide); } /** * A Hide action hides or shows an annotation. * @param name * @param hide * @return A Hide Action */ public static PdfAction createHide(String name, boolean hide) { return createHide(new PdfString(name), hide); } static PdfArray buildArray(Object names[]) { PdfArray array = new PdfArray(); for (int k = 0; k < names.length; ++k) { Object obj = names[k]; if (obj instanceof String) array.add(new PdfString((String)obj)); else if (obj instanceof PdfAnnotation) array.add(((PdfAnnotation)obj).getIndirectReference()); else throw new RuntimeException(MessageLocalization.getComposedMessage("the.array.must.contain.string.or.pdfannotation")); } return array; } /** * A Hide action hides or shows objects. * @param names * @param hide * @return A Hide Action */ public static PdfAction createHide(Object names[], boolean hide) { return createHide(buildArray(names), hide); } /** * Creates a submit form. * @param file the URI to submit the form to * @param names the objects to submit * @param flags submit properties * @return A PdfAction */ public static PdfAction createSubmitForm(String file, Object names[], int flags) { PdfAction action = new PdfAction(); action.put(PdfName.S, PdfName.SUBMITFORM); PdfDictionary dic = new PdfDictionary(); dic.put(PdfName.F, new PdfString(file)); dic.put(PdfName.FS, PdfName.URL); action.put(PdfName.F, dic); if (names != null) action.put(PdfName.FIELDS, buildArray(names)); action.put(PdfName.FLAGS, new PdfNumber(flags)); return action; } /** * Creates a resetform. * @param names the objects to reset * @param flags submit properties * @return A PdfAction */ public static PdfAction createResetForm(Object names[], int flags) { PdfAction action = new PdfAction(); action.put(PdfName.S, PdfName.RESETFORM); if (names != null) action.put(PdfName.FIELDS, buildArray(names)); action.put(PdfName.FLAGS, new PdfNumber(flags)); return action; } /** * Creates an Import field. * @param file * @return A PdfAction */ public static PdfAction createImportData(String file) { PdfAction action = new PdfAction(); action.put(PdfName.S, PdfName.IMPORTDATA); action.put(PdfName.F, new PdfString(file)); return action; } /** Add a chained action. * @param na the next action */ public void next(PdfAction na) { PdfObject nextAction = get(PdfName.NEXT); if (nextAction == null) put(PdfName.NEXT, na); else if (nextAction.isDictionary()) { PdfArray array = new PdfArray(nextAction); array.add(na); put(PdfName.NEXT, array); } else { ((PdfArray)nextAction).add(na); } } /** Creates a GoTo action to an internal page. * @param page the page to go. First page is 1 * @param dest the destination for the page * @param writer the writer for this action * @return a GoTo action */ public static PdfAction gotoLocalPage(int page, PdfDestination dest, PdfWriter writer) { PdfIndirectReference ref = writer.getPageReference(page); dest.addPage(ref); PdfAction action = new PdfAction(); action.put(PdfName.S, PdfName.GOTO); action.put(PdfName.D, dest); return action; } /** * Creates a GoTo action to a named destination. * @param dest the named destination * @param isName if true sets the destination as a name, if false sets it as a String * @return a GoTo action */ public static PdfAction gotoLocalPage(String dest, boolean isName) { PdfAction action = new PdfAction(); action.put(PdfName.S, PdfName.GOTO); if (isName) action.put(PdfName.D, new PdfName(dest)); else action.put(PdfName.D, new PdfString(dest, null)); return action; } /** * Creates a GoToR action to a named destination. * @param filename the file name to go to * @param dest the destination name * @param isName if true sets the destination as a name, if false sets it as a String * @param newWindow open the document in a new window if <CODE>true</CODE>, if false the current document is replaced by the new document. * @return a GoToR action */ public static PdfAction gotoRemotePage(String filename, String dest, boolean isName, boolean newWindow) { PdfAction action = new PdfAction(); action.put(PdfName.F, new PdfString(filename)); action.put(PdfName.S, PdfName.GOTOR); if (isName) action.put(PdfName.D, new PdfName(dest)); else action.put(PdfName.D, new PdfString(dest, null)); if (newWindow) action.put(PdfName.NEWWINDOW, PdfBoolean.PDFTRUE); return action; } /** * Creates a GoToE action to an embedded file. * @param filename the root document of the target (null if the target is in the same document) * @param dest the named destination * @param isName if true sets the destination as a name, if false sets it as a String * @return a GoToE action */ public static PdfAction gotoEmbedded(String filename, PdfTargetDictionary target, String dest, boolean isName, boolean newWindow) { if (isName) return gotoEmbedded(filename, target, new PdfName(dest), newWindow); else return gotoEmbedded(filename, target, new PdfString(dest, null), newWindow); } /** * Creates a GoToE action to an embedded file. * @param filename the root document of the target (null if the target is in the same document) * @param target a path to the target document of this action * @param dest the destination inside the target document, can be of type PdfDestination, PdfName, or PdfString * @param newWindow if true, the destination document should be opened in a new window * @return a GoToE action */ public static PdfAction gotoEmbedded(String filename, PdfTargetDictionary target, PdfObject dest, boolean newWindow) { PdfAction action = new PdfAction(); action.put(PdfName.S, PdfName.GOTOE); action.put(PdfName.T, target); action.put(PdfName.D, dest); action.put(PdfName.NEWWINDOW, new PdfBoolean(newWindow)); if (filename != null) { action.put(PdfName.F, new PdfString(filename)); } return action; } /** * A set-OCG-state action (PDF 1.5) sets the state of one or more optional content * groups. * @param state an array consisting of any number of sequences beginning with a <CODE>PdfName</CODE> * or <CODE>String</CODE> (ON, OFF, or Toggle) followed by one or more optional content group dictionaries * <CODE>PdfLayer</CODE> or a <CODE>PdfIndirectReference</CODE> to a <CODE>PdfLayer</CODE>.<br> * The array elements are processed from left to right; each name is applied * to the subsequent groups until the next name is encountered: * <ul> * <li>ON sets the state of subsequent groups to ON</li> * <li>OFF sets the state of subsequent groups to OFF</li> * <li>Toggle reverses the state of subsequent groups</li> * </ul> * @param preserveRB if <CODE>true</CODE>, indicates that radio-button state relationships between optional * content groups (as specified by the RBGroups entry in the current configuration * dictionary) should be preserved when the states in the * <CODE>state</CODE> array are applied. That is, if a group is set to ON (either by ON or Toggle) during * processing of the <CODE>state</CODE> array, any other groups belong to the same radio-button * group are turned OFF. If a group is set to OFF, there is no effect on other groups.<br> * If <CODE>false</CODE>, radio-button state relationships, if any, are ignored * @return the action */ public static PdfAction setOCGstate(ArrayList state, boolean preserveRB) { PdfAction action = new PdfAction(); action.put(PdfName.S, PdfName.SETOCGSTATE); PdfArray a = new PdfArray(); for (int k = 0; k < state.size(); ++k) { Object o = state.get(k); if (o == null) continue; if (o instanceof PdfIndirectReference) a.add((PdfIndirectReference)o); else if (o instanceof PdfLayer) a.add(((PdfLayer)o).getRef()); else if (o instanceof PdfName) a.add((PdfName)o); else if (o instanceof String) { PdfName name = null; String s = (String)o; if (s.equalsIgnoreCase("on")) name = PdfName.ON; else if (s.equalsIgnoreCase("off")) name = PdfName.OFF; else if (s.equalsIgnoreCase("toggle")) name = PdfName.TOGGLE; else throw new IllegalArgumentException(MessageLocalization.getComposedMessage("a.string.1.was.passed.in.state.only.on.off.and.toggle.are.allowed", s)); a.add(name); } else throw new IllegalArgumentException(MessageLocalization.getComposedMessage("invalid.type.was.passed.in.state.1", o.getClass().getName())); } action.put(PdfName.STATE, a); if (!preserveRB) action.put(PdfName.PRESERVERB, PdfBoolean.PDFFALSE); return action; } }
lgpl-3.0
Builders-SonarSource/sonarqube-bis
server/sonar-process-monitor/src/main/java/org/sonar/process/monitor/WatcherThread.java
2498
/* * SonarQube * Copyright (C) 2009-2016 SonarSource SA * mailto:contact AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.process.monitor; /** * This thread blocks as long as the monitored process is physically alive. * It avoids from executing {@link Process#exitValue()} at a fixed rate : * <ul> * <li>no usage of exception for flow control. Indeed {@link Process#exitValue()} throws an exception * if process is alive. There's no method <code>Process#isAlive()</code></li> * <li>no delay, instantaneous notification that process is down</li> * </ul> */ class WatcherThread extends Thread { private final ProcessRef processRef; private final Monitor monitor; private boolean askedForRestart = false; WatcherThread(ProcessRef processRef, Monitor monitor) { // this name is different than Thread#toString(), which includes name, priority // and thread group // -> do not override toString() super(String.format("Watch[%s]", processRef.getKey())); this.processRef = processRef; this.monitor = monitor; } @Override public void run() { boolean stopped = false; while (!stopped) { try { processRef.getProcess().waitFor(); askedForRestart = processRef.getCommands().askedForRestart(); processRef.getCommands().acknowledgeAskForRestart(); // finalize status of ProcessRef processRef.stop(); // terminate all other processes, but in another thread monitor.stopAsync(); stopped = true; } catch (InterruptedException ignored) { // continue to watch process } } } public ProcessRef getProcessRef() { return processRef; } public boolean isAskedForRestart() { return askedForRestart; } }
lgpl-3.0
MesquiteProject/MesquiteArchive
releases/Mesquite2.72build528/Mesquite Project/Source/mesquite/meristic/lib/RequiresExactlyMeristicData.java
2002
/* Mesquite source code. Copyright 1997-2009 W. Maddison and D. Maddison. Version 2.72, December 2009. Disclaimer: The Mesquite source code is lengthy and we are few. There are no doubt inefficiencies and goofs in this code. The commenting leaves much to be desired. Please approach this source code with the spirit of helping out. Perhaps with your help we can be more than a few, and make Mesquite better. Mesquite is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY. Mesquite's web site is http://mesquiteproject.org This source code and its compiled class files are free and modifiable under the terms of GNU Lesser General Public License. (http://www.gnu.org/copyleft/lesser.html) */package mesquite.meristic.lib; import mesquite.lib.CompatibilityTest; import mesquite.lib.EmployerEmployee; import mesquite.lib.MesquiteProject; import mesquite.lib.characters.CharacterData; import mesquite.lib.characters.CharacterState; /* ======================================================================== */ /** An object a module can create and pass back to store in module info. Tests whether module will be compatible with passed object. Classes of modules will have known ways of responding to particular classes of objects, e.g. character sources should test whether they can handle given CharacterState types.*/ public class RequiresExactlyMeristicData extends CompatibilityTest { public boolean isCompatible(Object obj, MesquiteProject project, EmployerEmployee prospectiveEmployer){ if (obj == null) return true; if (obj instanceof RequiresExactlyMeristicData) return true; if (obj instanceof CompatibilityTest) return false; if (!(obj instanceof Class)) return true; if (!CharacterState.class.isAssignableFrom((Class)obj) && !CharacterData.class.isAssignableFrom((Class)obj)) return true; return (MeristicState.class == obj) || MeristicState.class == obj; } public Class getAcceptedClass(){ return MeristicState.class; } }
lgpl-3.0
automenta/netentionweb
netention/automenta/netention/value/integer/IntegerEquals.java
380
package automenta.netention.value.integer; import automenta.netention.PropertyValue; public class IntegerEquals extends PropertyValue { private int value; public IntegerEquals() { super(); } public IntegerEquals(int i) { super(); this.value = i; } public void setValue(Integer i) { this.value = i; } public int getValue() { return value; } }
lgpl-3.0
e-ucm/ead
engine/core/src/main/java/es/eucm/ead/engine/systems/VisibilitySystem.java
2412
/** * eAdventure is a research project of the * e-UCM research group. * * Copyright 2005-2014 e-UCM research group. * * You can access a list of all the contributors to eAdventure at: * http://e-adventure.e-ucm.es/contributors * * e-UCM is a research group of the Department of Software Engineering * and Artificial Intelligence at the Complutense University of Madrid * (School of Computer Science). * * CL Profesor Jose Garcia Santesmases 9, * 28040 Madrid (Madrid), Spain. * * For more info please visit: <http://e-adventure.e-ucm.es> or * <http://www.e-ucm.es> * * **************************************************************************** * * This file is part of eAdventure * * eAdventure is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * eAdventure 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 eAdventure. If not, see <http://www.gnu.org/licenses/>. */ package es.eucm.ead.engine.systems; import com.badlogic.ashley.core.Entity; import com.badlogic.ashley.core.Family; import es.eucm.ead.engine.GameLoop; import es.eucm.ead.engine.components.VisibilityComponent; import es.eucm.ead.engine.variables.VariablesManager; /** * Deals with entities that have conditioned visibility. For each of these * entities, it evaluates its condition and updates its visibility accordingly. * * Created by Javier Torrente on 17/04/14. */ public class VisibilitySystem extends ConditionalSystem { public VisibilitySystem(GameLoop engine, VariablesManager variablesManager) { super(engine, variablesManager, Family.all(VisibilityComponent.class) .get(), 0); } @Override public void doProcessEntity(Entity entity, float deltaTime) { VisibilityComponent visibilityComponent = entity .getComponent(VisibilityComponent.class); visibilityComponent.update(); } }
lgpl-3.0
woate/asmsupport
asmsupport-client/src/main/java/cn/wensiqun/asmsupport/client/block/Finally.java
1079
/** * Asmsupport is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package cn.wensiqun.asmsupport.client.block; import cn.wensiqun.asmsupport.core.block.control.exception.KernelFinally; import cn.wensiqun.asmsupport.standard.block.exception.IFinally; public abstract class Finally extends ProgramBlock<KernelFinally> implements IFinally { public Finally() { targetBlock = new KernelFinally() { @Override public void body() { Finally.this.body(); } }; } }
lgpl-3.0
madoar/POL-POM-5
phoenicis-tools/src/main/java/org/phoenicis/tools/archive/cab/CFFolder.java
3050
/* * Copyright (C) 2015-2017 PÂRIS Quentin * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. */ package org.phoenicis.tools.archive.cab; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.io.IOException; import java.io.InputStream; public class CFFolder extends AbstractCabStructure { private final Logger LOGGER = LoggerFactory.getLogger(AbstractCabStructure.class); byte[] coffCabStart = new byte[4]; byte[] cCFData = new byte[2]; byte[] typeCompress = new byte[2]; byte[] abReserve = new byte[256]; CFFolder(long offset) { super(offset); } @Override public void populate(InputStream inputStream) { try { structureSize += inputStream.read(coffCabStart); structureSize += inputStream.read(cCFData); structureSize += inputStream.read(typeCompress); // structureSize += readVariableField(inputStream, abReserve); } catch (IOException e) { throw new CabException("Unable to extract CFFolder", e); } } public long getOffsetStartData() { return decodeLittleEndian(coffCabStart); } public long getNumberOfDataStructures() { return decodeLittleEndian(cCFData); } public CompressionType getCompressType() { Long compressType = decodeLittleEndian(typeCompress) & 0x000F; if (compressType == 0) { return CompressionType.NONE; } if (compressType == 1) { return CompressionType.MSZIP; } if (compressType == 2) { return CompressionType.QUANTUM; } if (compressType == 3) { return CompressionType.LZX; } throw new CabException("Unsupported compression type"); } @Override public String toString() { String compressType; try { compressType = getCompressType().name(); } catch (CabException e) { LOGGER.warn("Failed to find compress type", e); compressType = "Unknown"; } return String.format( "Offset: %s\n" + "Size: %s\n" + "Offset of the first data: %s\n" + "Number of data structures: %s\n" + "typeCompress: %s\n", offset, getStructureSize(), getOffsetStartData(), getNumberOfDataStructures(), compressType); } }
lgpl-3.0
simeshev/parabuild-ci
src/org/parabuild/ci/webui/common/LoginNameField.java
967
/* * Parabuild CI licenses this file to You under the LGPL 2.1 * (the "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * https://www.gnu.org/licenses/lgpl-3.0.txt * * 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.parabuild.ci.webui.common; public final class LoginNameField extends CommonField { public static final int COLUMN_WIDTH = 175; public LoginNameField() { this(25); } public LoginNameField(final int visibleSize) { super(60, visibleSize); } public LoginNameField(final String fieldName, final int visibleSize) { super(fieldName, 60, visibleSize); } }
lgpl-3.0
teryk/sonarqube
server/sonar-ws-client/src/main/java/org/sonar/wsclient/qprofile/QProfileResult.java
1036
/* * SonarQube, open source software quality management tool. * Copyright (C) 2008-2014 SonarSource * mailto:contact AT sonarsource DOT com * * SonarQube is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * SonarQube is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.wsclient.qprofile; import java.util.List; public interface QProfileResult { List<String> infos(); List<String> warnings(); }
lgpl-3.0
sklaxel/inera-axel
shs/shs-protocol/src/main/java/se/inera/axel/shs/processor/SimpleLabelValidator.java
4028
/** * Copyright (C) 2013 Inera AB (http://www.inera.se) * * This file is part of Inera Axel (http://code.google.com/p/inera-axel). * * Inera Axel is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Inera Axel is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/> */ package se.inera.axel.shs.processor; import org.apache.commons.lang.StringUtils; import se.inera.axel.shs.exception.*; import se.inera.axel.shs.mime.ShsMessage; import se.inera.axel.shs.xml.UrnAddress; import se.inera.axel.shs.xml.UrnProduct; import se.inera.axel.shs.xml.label.From; import se.inera.axel.shs.xml.label.Originator; import se.inera.axel.shs.xml.label.ShsLabel; import se.inera.axel.shs.xml.label.To; import java.util.List; import java.util.UUID; public class SimpleLabelValidator { public SimpleLabelValidator() { super(); } public void validate(ShsMessage message) throws ShsException { validate(message.getLabel()); } public void validate(ShsLabel label) throws ShsException { validateOriginatorOrFrom(label); validateTo(label); validateProduct(label); validateSequenceType(label); } private void validateOriginatorOrFrom(ShsLabel label) { List<Object> orignatorOrFrom = label.getOriginatorOrFrom(); // If no From is given Originator is mandatory if (orignatorOrFrom == null || orignatorOrFrom.isEmpty()) { throw new IllegalSenderException("Originator is mandatory when from is not given"); } From from = null; Originator originator = null; for (Object object : orignatorOrFrom) { if (object instanceof From) { if (from != null) { throw new IllegalSenderException("Multiple from is not allowed"); } from = (From)object; } else if (object instanceof Originator) { if (originator != null) { throw new IllegalSenderException("Multiple originator is not allowed"); } originator = (Originator)object; } } // If from is empty Originator is mandatory // TODO is this the correct check? if (from == null || StringUtils.isBlank(from.getValue())) { if (originator == null || StringUtils.isBlank(originator.getValue())) { throw new IllegalSenderException("Originator is mandatory when from is not given"); } } } private void validateTo(ShsLabel label) { To to = label.getTo(); if (to == null) { // To is optional return; } // Check that the to address is valid try { UrnAddress.valueOf(to.getValue()); } catch (IllegalArgumentException e) { throw new IllegalReceiverException(e); } } private void validateProduct(ShsLabel label) { if (label.getProduct() == null) { throw new IllegalProductTypeException("Product is mandatory"); } UrnProduct product = null; try { product = UrnProduct.valueOf(label.getProduct().getValue()); } catch(IllegalArgumentException e) { throw new IllegalProductTypeException("The given product type id is not valid", e); } String productURN = product.getValue(); if (productURN == null) { throw new IllegalProductTypeException("Product type id must not be blank"); } if (!product.isSpecialProduct()) { try { UUID.fromString(productURN); } catch (IllegalArgumentException e) { throw new IllegalProductTypeException("Product type id [" + productURN + "] is not valid", e); } } } private void validateSequenceType(ShsLabel label) { if (label.getSequenceType() == null) { throw new IllegalMessageStructureException("Sequence type is mandatory"); } } }
lgpl-3.0
dgageot/sonarqube
sonar-db/src/main/gen-java/org/sonar/db/protobuf/DbIssues.java
106671
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: db-issues.proto package org.sonar.db.protobuf; public final class DbIssues { private DbIssues() {} public static void registerAllExtensions( com.google.protobuf.ExtensionRegistry registry) { } public interface LocationsOrBuilder extends // @@protoc_insertion_point(interface_extends:sonarqube.db.issues.Locations) com.google.protobuf.MessageOrBuilder { /** * <code>optional .sonarqube.db.commons.TextRange primary = 1;</code> */ boolean hasPrimary(); /** * <code>optional .sonarqube.db.commons.TextRange primary = 1;</code> */ org.sonar.db.protobuf.DbCommons.TextRange getPrimary(); /** * <code>optional .sonarqube.db.commons.TextRange primary = 1;</code> */ org.sonar.db.protobuf.DbCommons.TextRangeOrBuilder getPrimaryOrBuilder(); /** * <code>repeated .sonarqube.db.issues.Location secondary = 2;</code> */ java.util.List<org.sonar.db.protobuf.DbIssues.Location> getSecondaryList(); /** * <code>repeated .sonarqube.db.issues.Location secondary = 2;</code> */ org.sonar.db.protobuf.DbIssues.Location getSecondary(int index); /** * <code>repeated .sonarqube.db.issues.Location secondary = 2;</code> */ int getSecondaryCount(); /** * <code>repeated .sonarqube.db.issues.Location secondary = 2;</code> */ java.util.List<? extends org.sonar.db.protobuf.DbIssues.LocationOrBuilder> getSecondaryOrBuilderList(); /** * <code>repeated .sonarqube.db.issues.Location secondary = 2;</code> */ org.sonar.db.protobuf.DbIssues.LocationOrBuilder getSecondaryOrBuilder( int index); /** * <code>repeated .sonarqube.db.issues.ExecutionFlow execution_flow = 3;</code> */ java.util.List<org.sonar.db.protobuf.DbIssues.ExecutionFlow> getExecutionFlowList(); /** * <code>repeated .sonarqube.db.issues.ExecutionFlow execution_flow = 3;</code> */ org.sonar.db.protobuf.DbIssues.ExecutionFlow getExecutionFlow(int index); /** * <code>repeated .sonarqube.db.issues.ExecutionFlow execution_flow = 3;</code> */ int getExecutionFlowCount(); /** * <code>repeated .sonarqube.db.issues.ExecutionFlow execution_flow = 3;</code> */ java.util.List<? extends org.sonar.db.protobuf.DbIssues.ExecutionFlowOrBuilder> getExecutionFlowOrBuilderList(); /** * <code>repeated .sonarqube.db.issues.ExecutionFlow execution_flow = 3;</code> */ org.sonar.db.protobuf.DbIssues.ExecutionFlowOrBuilder getExecutionFlowOrBuilder( int index); } /** * Protobuf type {@code sonarqube.db.issues.Locations} */ public static final class Locations extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:sonarqube.db.issues.Locations) LocationsOrBuilder { // Use Locations.newBuilder() to construct. private Locations(com.google.protobuf.GeneratedMessage.Builder<?> builder) { super(builder); this.unknownFields = builder.getUnknownFields(); } private Locations(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); } private static final Locations defaultInstance; public static Locations getDefaultInstance() { return defaultInstance; } public Locations getDefaultInstanceForType() { return defaultInstance; } private final com.google.protobuf.UnknownFieldSet unknownFields; @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private Locations( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { initFields(); int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 10: { org.sonar.db.protobuf.DbCommons.TextRange.Builder subBuilder = null; if (((bitField0_ & 0x00000001) == 0x00000001)) { subBuilder = primary_.toBuilder(); } primary_ = input.readMessage(org.sonar.db.protobuf.DbCommons.TextRange.PARSER, extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom(primary_); primary_ = subBuilder.buildPartial(); } bitField0_ |= 0x00000001; break; } case 18: { if (!((mutable_bitField0_ & 0x00000002) == 0x00000002)) { secondary_ = new java.util.ArrayList<org.sonar.db.protobuf.DbIssues.Location>(); mutable_bitField0_ |= 0x00000002; } secondary_.add(input.readMessage(org.sonar.db.protobuf.DbIssues.Location.PARSER, extensionRegistry)); break; } case 26: { if (!((mutable_bitField0_ & 0x00000004) == 0x00000004)) { executionFlow_ = new java.util.ArrayList<org.sonar.db.protobuf.DbIssues.ExecutionFlow>(); mutable_bitField0_ |= 0x00000004; } executionFlow_.add(input.readMessage(org.sonar.db.protobuf.DbIssues.ExecutionFlow.PARSER, extensionRegistry)); break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e.getMessage()).setUnfinishedMessage(this); } finally { if (((mutable_bitField0_ & 0x00000002) == 0x00000002)) { secondary_ = java.util.Collections.unmodifiableList(secondary_); } if (((mutable_bitField0_ & 0x00000004) == 0x00000004)) { executionFlow_ = java.util.Collections.unmodifiableList(executionFlow_); } this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return org.sonar.db.protobuf.DbIssues.internal_static_sonarqube_db_issues_Locations_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return org.sonar.db.protobuf.DbIssues.internal_static_sonarqube_db_issues_Locations_fieldAccessorTable .ensureFieldAccessorsInitialized( org.sonar.db.protobuf.DbIssues.Locations.class, org.sonar.db.protobuf.DbIssues.Locations.Builder.class); } public static com.google.protobuf.Parser<Locations> PARSER = new com.google.protobuf.AbstractParser<Locations>() { public Locations parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new Locations(input, extensionRegistry); } }; @java.lang.Override public com.google.protobuf.Parser<Locations> getParserForType() { return PARSER; } private int bitField0_; public static final int PRIMARY_FIELD_NUMBER = 1; private org.sonar.db.protobuf.DbCommons.TextRange primary_; /** * <code>optional .sonarqube.db.commons.TextRange primary = 1;</code> */ public boolean hasPrimary() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * <code>optional .sonarqube.db.commons.TextRange primary = 1;</code> */ public org.sonar.db.protobuf.DbCommons.TextRange getPrimary() { return primary_; } /** * <code>optional .sonarqube.db.commons.TextRange primary = 1;</code> */ public org.sonar.db.protobuf.DbCommons.TextRangeOrBuilder getPrimaryOrBuilder() { return primary_; } public static final int SECONDARY_FIELD_NUMBER = 2; private java.util.List<org.sonar.db.protobuf.DbIssues.Location> secondary_; /** * <code>repeated .sonarqube.db.issues.Location secondary = 2;</code> */ public java.util.List<org.sonar.db.protobuf.DbIssues.Location> getSecondaryList() { return secondary_; } /** * <code>repeated .sonarqube.db.issues.Location secondary = 2;</code> */ public java.util.List<? extends org.sonar.db.protobuf.DbIssues.LocationOrBuilder> getSecondaryOrBuilderList() { return secondary_; } /** * <code>repeated .sonarqube.db.issues.Location secondary = 2;</code> */ public int getSecondaryCount() { return secondary_.size(); } /** * <code>repeated .sonarqube.db.issues.Location secondary = 2;</code> */ public org.sonar.db.protobuf.DbIssues.Location getSecondary(int index) { return secondary_.get(index); } /** * <code>repeated .sonarqube.db.issues.Location secondary = 2;</code> */ public org.sonar.db.protobuf.DbIssues.LocationOrBuilder getSecondaryOrBuilder( int index) { return secondary_.get(index); } public static final int EXECUTION_FLOW_FIELD_NUMBER = 3; private java.util.List<org.sonar.db.protobuf.DbIssues.ExecutionFlow> executionFlow_; /** * <code>repeated .sonarqube.db.issues.ExecutionFlow execution_flow = 3;</code> */ public java.util.List<org.sonar.db.protobuf.DbIssues.ExecutionFlow> getExecutionFlowList() { return executionFlow_; } /** * <code>repeated .sonarqube.db.issues.ExecutionFlow execution_flow = 3;</code> */ public java.util.List<? extends org.sonar.db.protobuf.DbIssues.ExecutionFlowOrBuilder> getExecutionFlowOrBuilderList() { return executionFlow_; } /** * <code>repeated .sonarqube.db.issues.ExecutionFlow execution_flow = 3;</code> */ public int getExecutionFlowCount() { return executionFlow_.size(); } /** * <code>repeated .sonarqube.db.issues.ExecutionFlow execution_flow = 3;</code> */ public org.sonar.db.protobuf.DbIssues.ExecutionFlow getExecutionFlow(int index) { return executionFlow_.get(index); } /** * <code>repeated .sonarqube.db.issues.ExecutionFlow execution_flow = 3;</code> */ public org.sonar.db.protobuf.DbIssues.ExecutionFlowOrBuilder getExecutionFlowOrBuilder( int index) { return executionFlow_.get(index); } private void initFields() { primary_ = org.sonar.db.protobuf.DbCommons.TextRange.getDefaultInstance(); secondary_ = java.util.Collections.emptyList(); executionFlow_ = java.util.Collections.emptyList(); } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); if (((bitField0_ & 0x00000001) == 0x00000001)) { output.writeMessage(1, primary_); } for (int i = 0; i < secondary_.size(); i++) { output.writeMessage(2, secondary_.get(i)); } for (int i = 0; i < executionFlow_.size(); i++) { output.writeMessage(3, executionFlow_.get(i)); } getUnknownFields().writeTo(output); } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(1, primary_); } for (int i = 0; i < secondary_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(2, secondary_.get(i)); } for (int i = 0; i < executionFlow_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(3, executionFlow_.get(i)); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } private static final long serialVersionUID = 0L; @java.lang.Override protected java.lang.Object writeReplace() throws java.io.ObjectStreamException { return super.writeReplace(); } public static org.sonar.db.protobuf.DbIssues.Locations parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static org.sonar.db.protobuf.DbIssues.Locations parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static org.sonar.db.protobuf.DbIssues.Locations parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static org.sonar.db.protobuf.DbIssues.Locations parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static org.sonar.db.protobuf.DbIssues.Locations parseFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static org.sonar.db.protobuf.DbIssues.Locations parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static org.sonar.db.protobuf.DbIssues.Locations parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseDelimitedFrom(input); } public static org.sonar.db.protobuf.DbIssues.Locations parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseDelimitedFrom(input, extensionRegistry); } public static org.sonar.db.protobuf.DbIssues.Locations parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static org.sonar.db.protobuf.DbIssues.Locations parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(org.sonar.db.protobuf.DbIssues.Locations prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code sonarqube.db.issues.Locations} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:sonarqube.db.issues.Locations) org.sonar.db.protobuf.DbIssues.LocationsOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return org.sonar.db.protobuf.DbIssues.internal_static_sonarqube_db_issues_Locations_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return org.sonar.db.protobuf.DbIssues.internal_static_sonarqube_db_issues_Locations_fieldAccessorTable .ensureFieldAccessorsInitialized( org.sonar.db.protobuf.DbIssues.Locations.class, org.sonar.db.protobuf.DbIssues.Locations.Builder.class); } // Construct using org.sonar.db.protobuf.DbIssues.Locations.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { getPrimaryFieldBuilder(); getSecondaryFieldBuilder(); getExecutionFlowFieldBuilder(); } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); if (primaryBuilder_ == null) { primary_ = org.sonar.db.protobuf.DbCommons.TextRange.getDefaultInstance(); } else { primaryBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); if (secondaryBuilder_ == null) { secondary_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000002); } else { secondaryBuilder_.clear(); } if (executionFlowBuilder_ == null) { executionFlow_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000004); } else { executionFlowBuilder_.clear(); } return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return org.sonar.db.protobuf.DbIssues.internal_static_sonarqube_db_issues_Locations_descriptor; } public org.sonar.db.protobuf.DbIssues.Locations getDefaultInstanceForType() { return org.sonar.db.protobuf.DbIssues.Locations.getDefaultInstance(); } public org.sonar.db.protobuf.DbIssues.Locations build() { org.sonar.db.protobuf.DbIssues.Locations result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public org.sonar.db.protobuf.DbIssues.Locations buildPartial() { org.sonar.db.protobuf.DbIssues.Locations result = new org.sonar.db.protobuf.DbIssues.Locations(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } if (primaryBuilder_ == null) { result.primary_ = primary_; } else { result.primary_ = primaryBuilder_.build(); } if (secondaryBuilder_ == null) { if (((bitField0_ & 0x00000002) == 0x00000002)) { secondary_ = java.util.Collections.unmodifiableList(secondary_); bitField0_ = (bitField0_ & ~0x00000002); } result.secondary_ = secondary_; } else { result.secondary_ = secondaryBuilder_.build(); } if (executionFlowBuilder_ == null) { if (((bitField0_ & 0x00000004) == 0x00000004)) { executionFlow_ = java.util.Collections.unmodifiableList(executionFlow_); bitField0_ = (bitField0_ & ~0x00000004); } result.executionFlow_ = executionFlow_; } else { result.executionFlow_ = executionFlowBuilder_.build(); } result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof org.sonar.db.protobuf.DbIssues.Locations) { return mergeFrom((org.sonar.db.protobuf.DbIssues.Locations)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(org.sonar.db.protobuf.DbIssues.Locations other) { if (other == org.sonar.db.protobuf.DbIssues.Locations.getDefaultInstance()) return this; if (other.hasPrimary()) { mergePrimary(other.getPrimary()); } if (secondaryBuilder_ == null) { if (!other.secondary_.isEmpty()) { if (secondary_.isEmpty()) { secondary_ = other.secondary_; bitField0_ = (bitField0_ & ~0x00000002); } else { ensureSecondaryIsMutable(); secondary_.addAll(other.secondary_); } onChanged(); } } else { if (!other.secondary_.isEmpty()) { if (secondaryBuilder_.isEmpty()) { secondaryBuilder_.dispose(); secondaryBuilder_ = null; secondary_ = other.secondary_; bitField0_ = (bitField0_ & ~0x00000002); secondaryBuilder_ = com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? getSecondaryFieldBuilder() : null; } else { secondaryBuilder_.addAllMessages(other.secondary_); } } } if (executionFlowBuilder_ == null) { if (!other.executionFlow_.isEmpty()) { if (executionFlow_.isEmpty()) { executionFlow_ = other.executionFlow_; bitField0_ = (bitField0_ & ~0x00000004); } else { ensureExecutionFlowIsMutable(); executionFlow_.addAll(other.executionFlow_); } onChanged(); } } else { if (!other.executionFlow_.isEmpty()) { if (executionFlowBuilder_.isEmpty()) { executionFlowBuilder_.dispose(); executionFlowBuilder_ = null; executionFlow_ = other.executionFlow_; bitField0_ = (bitField0_ & ~0x00000004); executionFlowBuilder_ = com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? getExecutionFlowFieldBuilder() : null; } else { executionFlowBuilder_.addAllMessages(other.executionFlow_); } } } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { org.sonar.db.protobuf.DbIssues.Locations parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (org.sonar.db.protobuf.DbIssues.Locations) e.getUnfinishedMessage(); throw e; } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private org.sonar.db.protobuf.DbCommons.TextRange primary_ = org.sonar.db.protobuf.DbCommons.TextRange.getDefaultInstance(); private com.google.protobuf.SingleFieldBuilder< org.sonar.db.protobuf.DbCommons.TextRange, org.sonar.db.protobuf.DbCommons.TextRange.Builder, org.sonar.db.protobuf.DbCommons.TextRangeOrBuilder> primaryBuilder_; /** * <code>optional .sonarqube.db.commons.TextRange primary = 1;</code> */ public boolean hasPrimary() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * <code>optional .sonarqube.db.commons.TextRange primary = 1;</code> */ public org.sonar.db.protobuf.DbCommons.TextRange getPrimary() { if (primaryBuilder_ == null) { return primary_; } else { return primaryBuilder_.getMessage(); } } /** * <code>optional .sonarqube.db.commons.TextRange primary = 1;</code> */ public Builder setPrimary(org.sonar.db.protobuf.DbCommons.TextRange value) { if (primaryBuilder_ == null) { if (value == null) { throw new NullPointerException(); } primary_ = value; onChanged(); } else { primaryBuilder_.setMessage(value); } bitField0_ |= 0x00000001; return this; } /** * <code>optional .sonarqube.db.commons.TextRange primary = 1;</code> */ public Builder setPrimary( org.sonar.db.protobuf.DbCommons.TextRange.Builder builderForValue) { if (primaryBuilder_ == null) { primary_ = builderForValue.build(); onChanged(); } else { primaryBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000001; return this; } /** * <code>optional .sonarqube.db.commons.TextRange primary = 1;</code> */ public Builder mergePrimary(org.sonar.db.protobuf.DbCommons.TextRange value) { if (primaryBuilder_ == null) { if (((bitField0_ & 0x00000001) == 0x00000001) && primary_ != org.sonar.db.protobuf.DbCommons.TextRange.getDefaultInstance()) { primary_ = org.sonar.db.protobuf.DbCommons.TextRange.newBuilder(primary_).mergeFrom(value).buildPartial(); } else { primary_ = value; } onChanged(); } else { primaryBuilder_.mergeFrom(value); } bitField0_ |= 0x00000001; return this; } /** * <code>optional .sonarqube.db.commons.TextRange primary = 1;</code> */ public Builder clearPrimary() { if (primaryBuilder_ == null) { primary_ = org.sonar.db.protobuf.DbCommons.TextRange.getDefaultInstance(); onChanged(); } else { primaryBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000001); return this; } /** * <code>optional .sonarqube.db.commons.TextRange primary = 1;</code> */ public org.sonar.db.protobuf.DbCommons.TextRange.Builder getPrimaryBuilder() { bitField0_ |= 0x00000001; onChanged(); return getPrimaryFieldBuilder().getBuilder(); } /** * <code>optional .sonarqube.db.commons.TextRange primary = 1;</code> */ public org.sonar.db.protobuf.DbCommons.TextRangeOrBuilder getPrimaryOrBuilder() { if (primaryBuilder_ != null) { return primaryBuilder_.getMessageOrBuilder(); } else { return primary_; } } /** * <code>optional .sonarqube.db.commons.TextRange primary = 1;</code> */ private com.google.protobuf.SingleFieldBuilder< org.sonar.db.protobuf.DbCommons.TextRange, org.sonar.db.protobuf.DbCommons.TextRange.Builder, org.sonar.db.protobuf.DbCommons.TextRangeOrBuilder> getPrimaryFieldBuilder() { if (primaryBuilder_ == null) { primaryBuilder_ = new com.google.protobuf.SingleFieldBuilder< org.sonar.db.protobuf.DbCommons.TextRange, org.sonar.db.protobuf.DbCommons.TextRange.Builder, org.sonar.db.protobuf.DbCommons.TextRangeOrBuilder>( getPrimary(), getParentForChildren(), isClean()); primary_ = null; } return primaryBuilder_; } private java.util.List<org.sonar.db.protobuf.DbIssues.Location> secondary_ = java.util.Collections.emptyList(); private void ensureSecondaryIsMutable() { if (!((bitField0_ & 0x00000002) == 0x00000002)) { secondary_ = new java.util.ArrayList<org.sonar.db.protobuf.DbIssues.Location>(secondary_); bitField0_ |= 0x00000002; } } private com.google.protobuf.RepeatedFieldBuilder< org.sonar.db.protobuf.DbIssues.Location, org.sonar.db.protobuf.DbIssues.Location.Builder, org.sonar.db.protobuf.DbIssues.LocationOrBuilder> secondaryBuilder_; /** * <code>repeated .sonarqube.db.issues.Location secondary = 2;</code> */ public java.util.List<org.sonar.db.protobuf.DbIssues.Location> getSecondaryList() { if (secondaryBuilder_ == null) { return java.util.Collections.unmodifiableList(secondary_); } else { return secondaryBuilder_.getMessageList(); } } /** * <code>repeated .sonarqube.db.issues.Location secondary = 2;</code> */ public int getSecondaryCount() { if (secondaryBuilder_ == null) { return secondary_.size(); } else { return secondaryBuilder_.getCount(); } } /** * <code>repeated .sonarqube.db.issues.Location secondary = 2;</code> */ public org.sonar.db.protobuf.DbIssues.Location getSecondary(int index) { if (secondaryBuilder_ == null) { return secondary_.get(index); } else { return secondaryBuilder_.getMessage(index); } } /** * <code>repeated .sonarqube.db.issues.Location secondary = 2;</code> */ public Builder setSecondary( int index, org.sonar.db.protobuf.DbIssues.Location value) { if (secondaryBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureSecondaryIsMutable(); secondary_.set(index, value); onChanged(); } else { secondaryBuilder_.setMessage(index, value); } return this; } /** * <code>repeated .sonarqube.db.issues.Location secondary = 2;</code> */ public Builder setSecondary( int index, org.sonar.db.protobuf.DbIssues.Location.Builder builderForValue) { if (secondaryBuilder_ == null) { ensureSecondaryIsMutable(); secondary_.set(index, builderForValue.build()); onChanged(); } else { secondaryBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * <code>repeated .sonarqube.db.issues.Location secondary = 2;</code> */ public Builder addSecondary(org.sonar.db.protobuf.DbIssues.Location value) { if (secondaryBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureSecondaryIsMutable(); secondary_.add(value); onChanged(); } else { secondaryBuilder_.addMessage(value); } return this; } /** * <code>repeated .sonarqube.db.issues.Location secondary = 2;</code> */ public Builder addSecondary( int index, org.sonar.db.protobuf.DbIssues.Location value) { if (secondaryBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureSecondaryIsMutable(); secondary_.add(index, value); onChanged(); } else { secondaryBuilder_.addMessage(index, value); } return this; } /** * <code>repeated .sonarqube.db.issues.Location secondary = 2;</code> */ public Builder addSecondary( org.sonar.db.protobuf.DbIssues.Location.Builder builderForValue) { if (secondaryBuilder_ == null) { ensureSecondaryIsMutable(); secondary_.add(builderForValue.build()); onChanged(); } else { secondaryBuilder_.addMessage(builderForValue.build()); } return this; } /** * <code>repeated .sonarqube.db.issues.Location secondary = 2;</code> */ public Builder addSecondary( int index, org.sonar.db.protobuf.DbIssues.Location.Builder builderForValue) { if (secondaryBuilder_ == null) { ensureSecondaryIsMutable(); secondary_.add(index, builderForValue.build()); onChanged(); } else { secondaryBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * <code>repeated .sonarqube.db.issues.Location secondary = 2;</code> */ public Builder addAllSecondary( java.lang.Iterable<? extends org.sonar.db.protobuf.DbIssues.Location> values) { if (secondaryBuilder_ == null) { ensureSecondaryIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, secondary_); onChanged(); } else { secondaryBuilder_.addAllMessages(values); } return this; } /** * <code>repeated .sonarqube.db.issues.Location secondary = 2;</code> */ public Builder clearSecondary() { if (secondaryBuilder_ == null) { secondary_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000002); onChanged(); } else { secondaryBuilder_.clear(); } return this; } /** * <code>repeated .sonarqube.db.issues.Location secondary = 2;</code> */ public Builder removeSecondary(int index) { if (secondaryBuilder_ == null) { ensureSecondaryIsMutable(); secondary_.remove(index); onChanged(); } else { secondaryBuilder_.remove(index); } return this; } /** * <code>repeated .sonarqube.db.issues.Location secondary = 2;</code> */ public org.sonar.db.protobuf.DbIssues.Location.Builder getSecondaryBuilder( int index) { return getSecondaryFieldBuilder().getBuilder(index); } /** * <code>repeated .sonarqube.db.issues.Location secondary = 2;</code> */ public org.sonar.db.protobuf.DbIssues.LocationOrBuilder getSecondaryOrBuilder( int index) { if (secondaryBuilder_ == null) { return secondary_.get(index); } else { return secondaryBuilder_.getMessageOrBuilder(index); } } /** * <code>repeated .sonarqube.db.issues.Location secondary = 2;</code> */ public java.util.List<? extends org.sonar.db.protobuf.DbIssues.LocationOrBuilder> getSecondaryOrBuilderList() { if (secondaryBuilder_ != null) { return secondaryBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(secondary_); } } /** * <code>repeated .sonarqube.db.issues.Location secondary = 2;</code> */ public org.sonar.db.protobuf.DbIssues.Location.Builder addSecondaryBuilder() { return getSecondaryFieldBuilder().addBuilder( org.sonar.db.protobuf.DbIssues.Location.getDefaultInstance()); } /** * <code>repeated .sonarqube.db.issues.Location secondary = 2;</code> */ public org.sonar.db.protobuf.DbIssues.Location.Builder addSecondaryBuilder( int index) { return getSecondaryFieldBuilder().addBuilder( index, org.sonar.db.protobuf.DbIssues.Location.getDefaultInstance()); } /** * <code>repeated .sonarqube.db.issues.Location secondary = 2;</code> */ public java.util.List<org.sonar.db.protobuf.DbIssues.Location.Builder> getSecondaryBuilderList() { return getSecondaryFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilder< org.sonar.db.protobuf.DbIssues.Location, org.sonar.db.protobuf.DbIssues.Location.Builder, org.sonar.db.protobuf.DbIssues.LocationOrBuilder> getSecondaryFieldBuilder() { if (secondaryBuilder_ == null) { secondaryBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< org.sonar.db.protobuf.DbIssues.Location, org.sonar.db.protobuf.DbIssues.Location.Builder, org.sonar.db.protobuf.DbIssues.LocationOrBuilder>( secondary_, ((bitField0_ & 0x00000002) == 0x00000002), getParentForChildren(), isClean()); secondary_ = null; } return secondaryBuilder_; } private java.util.List<org.sonar.db.protobuf.DbIssues.ExecutionFlow> executionFlow_ = java.util.Collections.emptyList(); private void ensureExecutionFlowIsMutable() { if (!((bitField0_ & 0x00000004) == 0x00000004)) { executionFlow_ = new java.util.ArrayList<org.sonar.db.protobuf.DbIssues.ExecutionFlow>(executionFlow_); bitField0_ |= 0x00000004; } } private com.google.protobuf.RepeatedFieldBuilder< org.sonar.db.protobuf.DbIssues.ExecutionFlow, org.sonar.db.protobuf.DbIssues.ExecutionFlow.Builder, org.sonar.db.protobuf.DbIssues.ExecutionFlowOrBuilder> executionFlowBuilder_; /** * <code>repeated .sonarqube.db.issues.ExecutionFlow execution_flow = 3;</code> */ public java.util.List<org.sonar.db.protobuf.DbIssues.ExecutionFlow> getExecutionFlowList() { if (executionFlowBuilder_ == null) { return java.util.Collections.unmodifiableList(executionFlow_); } else { return executionFlowBuilder_.getMessageList(); } } /** * <code>repeated .sonarqube.db.issues.ExecutionFlow execution_flow = 3;</code> */ public int getExecutionFlowCount() { if (executionFlowBuilder_ == null) { return executionFlow_.size(); } else { return executionFlowBuilder_.getCount(); } } /** * <code>repeated .sonarqube.db.issues.ExecutionFlow execution_flow = 3;</code> */ public org.sonar.db.protobuf.DbIssues.ExecutionFlow getExecutionFlow(int index) { if (executionFlowBuilder_ == null) { return executionFlow_.get(index); } else { return executionFlowBuilder_.getMessage(index); } } /** * <code>repeated .sonarqube.db.issues.ExecutionFlow execution_flow = 3;</code> */ public Builder setExecutionFlow( int index, org.sonar.db.protobuf.DbIssues.ExecutionFlow value) { if (executionFlowBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureExecutionFlowIsMutable(); executionFlow_.set(index, value); onChanged(); } else { executionFlowBuilder_.setMessage(index, value); } return this; } /** * <code>repeated .sonarqube.db.issues.ExecutionFlow execution_flow = 3;</code> */ public Builder setExecutionFlow( int index, org.sonar.db.protobuf.DbIssues.ExecutionFlow.Builder builderForValue) { if (executionFlowBuilder_ == null) { ensureExecutionFlowIsMutable(); executionFlow_.set(index, builderForValue.build()); onChanged(); } else { executionFlowBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * <code>repeated .sonarqube.db.issues.ExecutionFlow execution_flow = 3;</code> */ public Builder addExecutionFlow(org.sonar.db.protobuf.DbIssues.ExecutionFlow value) { if (executionFlowBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureExecutionFlowIsMutable(); executionFlow_.add(value); onChanged(); } else { executionFlowBuilder_.addMessage(value); } return this; } /** * <code>repeated .sonarqube.db.issues.ExecutionFlow execution_flow = 3;</code> */ public Builder addExecutionFlow( int index, org.sonar.db.protobuf.DbIssues.ExecutionFlow value) { if (executionFlowBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureExecutionFlowIsMutable(); executionFlow_.add(index, value); onChanged(); } else { executionFlowBuilder_.addMessage(index, value); } return this; } /** * <code>repeated .sonarqube.db.issues.ExecutionFlow execution_flow = 3;</code> */ public Builder addExecutionFlow( org.sonar.db.protobuf.DbIssues.ExecutionFlow.Builder builderForValue) { if (executionFlowBuilder_ == null) { ensureExecutionFlowIsMutable(); executionFlow_.add(builderForValue.build()); onChanged(); } else { executionFlowBuilder_.addMessage(builderForValue.build()); } return this; } /** * <code>repeated .sonarqube.db.issues.ExecutionFlow execution_flow = 3;</code> */ public Builder addExecutionFlow( int index, org.sonar.db.protobuf.DbIssues.ExecutionFlow.Builder builderForValue) { if (executionFlowBuilder_ == null) { ensureExecutionFlowIsMutable(); executionFlow_.add(index, builderForValue.build()); onChanged(); } else { executionFlowBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * <code>repeated .sonarqube.db.issues.ExecutionFlow execution_flow = 3;</code> */ public Builder addAllExecutionFlow( java.lang.Iterable<? extends org.sonar.db.protobuf.DbIssues.ExecutionFlow> values) { if (executionFlowBuilder_ == null) { ensureExecutionFlowIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, executionFlow_); onChanged(); } else { executionFlowBuilder_.addAllMessages(values); } return this; } /** * <code>repeated .sonarqube.db.issues.ExecutionFlow execution_flow = 3;</code> */ public Builder clearExecutionFlow() { if (executionFlowBuilder_ == null) { executionFlow_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000004); onChanged(); } else { executionFlowBuilder_.clear(); } return this; } /** * <code>repeated .sonarqube.db.issues.ExecutionFlow execution_flow = 3;</code> */ public Builder removeExecutionFlow(int index) { if (executionFlowBuilder_ == null) { ensureExecutionFlowIsMutable(); executionFlow_.remove(index); onChanged(); } else { executionFlowBuilder_.remove(index); } return this; } /** * <code>repeated .sonarqube.db.issues.ExecutionFlow execution_flow = 3;</code> */ public org.sonar.db.protobuf.DbIssues.ExecutionFlow.Builder getExecutionFlowBuilder( int index) { return getExecutionFlowFieldBuilder().getBuilder(index); } /** * <code>repeated .sonarqube.db.issues.ExecutionFlow execution_flow = 3;</code> */ public org.sonar.db.protobuf.DbIssues.ExecutionFlowOrBuilder getExecutionFlowOrBuilder( int index) { if (executionFlowBuilder_ == null) { return executionFlow_.get(index); } else { return executionFlowBuilder_.getMessageOrBuilder(index); } } /** * <code>repeated .sonarqube.db.issues.ExecutionFlow execution_flow = 3;</code> */ public java.util.List<? extends org.sonar.db.protobuf.DbIssues.ExecutionFlowOrBuilder> getExecutionFlowOrBuilderList() { if (executionFlowBuilder_ != null) { return executionFlowBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(executionFlow_); } } /** * <code>repeated .sonarqube.db.issues.ExecutionFlow execution_flow = 3;</code> */ public org.sonar.db.protobuf.DbIssues.ExecutionFlow.Builder addExecutionFlowBuilder() { return getExecutionFlowFieldBuilder().addBuilder( org.sonar.db.protobuf.DbIssues.ExecutionFlow.getDefaultInstance()); } /** * <code>repeated .sonarqube.db.issues.ExecutionFlow execution_flow = 3;</code> */ public org.sonar.db.protobuf.DbIssues.ExecutionFlow.Builder addExecutionFlowBuilder( int index) { return getExecutionFlowFieldBuilder().addBuilder( index, org.sonar.db.protobuf.DbIssues.ExecutionFlow.getDefaultInstance()); } /** * <code>repeated .sonarqube.db.issues.ExecutionFlow execution_flow = 3;</code> */ public java.util.List<org.sonar.db.protobuf.DbIssues.ExecutionFlow.Builder> getExecutionFlowBuilderList() { return getExecutionFlowFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilder< org.sonar.db.protobuf.DbIssues.ExecutionFlow, org.sonar.db.protobuf.DbIssues.ExecutionFlow.Builder, org.sonar.db.protobuf.DbIssues.ExecutionFlowOrBuilder> getExecutionFlowFieldBuilder() { if (executionFlowBuilder_ == null) { executionFlowBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< org.sonar.db.protobuf.DbIssues.ExecutionFlow, org.sonar.db.protobuf.DbIssues.ExecutionFlow.Builder, org.sonar.db.protobuf.DbIssues.ExecutionFlowOrBuilder>( executionFlow_, ((bitField0_ & 0x00000004) == 0x00000004), getParentForChildren(), isClean()); executionFlow_ = null; } return executionFlowBuilder_; } // @@protoc_insertion_point(builder_scope:sonarqube.db.issues.Locations) } static { defaultInstance = new Locations(true); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:sonarqube.db.issues.Locations) } public interface ExecutionFlowOrBuilder extends // @@protoc_insertion_point(interface_extends:sonarqube.db.issues.ExecutionFlow) com.google.protobuf.MessageOrBuilder { /** * <code>repeated .sonarqube.db.issues.Location location = 1;</code> */ java.util.List<org.sonar.db.protobuf.DbIssues.Location> getLocationList(); /** * <code>repeated .sonarqube.db.issues.Location location = 1;</code> */ org.sonar.db.protobuf.DbIssues.Location getLocation(int index); /** * <code>repeated .sonarqube.db.issues.Location location = 1;</code> */ int getLocationCount(); /** * <code>repeated .sonarqube.db.issues.Location location = 1;</code> */ java.util.List<? extends org.sonar.db.protobuf.DbIssues.LocationOrBuilder> getLocationOrBuilderList(); /** * <code>repeated .sonarqube.db.issues.Location location = 1;</code> */ org.sonar.db.protobuf.DbIssues.LocationOrBuilder getLocationOrBuilder( int index); } /** * Protobuf type {@code sonarqube.db.issues.ExecutionFlow} */ public static final class ExecutionFlow extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:sonarqube.db.issues.ExecutionFlow) ExecutionFlowOrBuilder { // Use ExecutionFlow.newBuilder() to construct. private ExecutionFlow(com.google.protobuf.GeneratedMessage.Builder<?> builder) { super(builder); this.unknownFields = builder.getUnknownFields(); } private ExecutionFlow(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); } private static final ExecutionFlow defaultInstance; public static ExecutionFlow getDefaultInstance() { return defaultInstance; } public ExecutionFlow getDefaultInstanceForType() { return defaultInstance; } private final com.google.protobuf.UnknownFieldSet unknownFields; @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private ExecutionFlow( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { initFields(); int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 10: { if (!((mutable_bitField0_ & 0x00000001) == 0x00000001)) { location_ = new java.util.ArrayList<org.sonar.db.protobuf.DbIssues.Location>(); mutable_bitField0_ |= 0x00000001; } location_.add(input.readMessage(org.sonar.db.protobuf.DbIssues.Location.PARSER, extensionRegistry)); break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e.getMessage()).setUnfinishedMessage(this); } finally { if (((mutable_bitField0_ & 0x00000001) == 0x00000001)) { location_ = java.util.Collections.unmodifiableList(location_); } this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return org.sonar.db.protobuf.DbIssues.internal_static_sonarqube_db_issues_ExecutionFlow_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return org.sonar.db.protobuf.DbIssues.internal_static_sonarqube_db_issues_ExecutionFlow_fieldAccessorTable .ensureFieldAccessorsInitialized( org.sonar.db.protobuf.DbIssues.ExecutionFlow.class, org.sonar.db.protobuf.DbIssues.ExecutionFlow.Builder.class); } public static com.google.protobuf.Parser<ExecutionFlow> PARSER = new com.google.protobuf.AbstractParser<ExecutionFlow>() { public ExecutionFlow parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new ExecutionFlow(input, extensionRegistry); } }; @java.lang.Override public com.google.protobuf.Parser<ExecutionFlow> getParserForType() { return PARSER; } public static final int LOCATION_FIELD_NUMBER = 1; private java.util.List<org.sonar.db.protobuf.DbIssues.Location> location_; /** * <code>repeated .sonarqube.db.issues.Location location = 1;</code> */ public java.util.List<org.sonar.db.protobuf.DbIssues.Location> getLocationList() { return location_; } /** * <code>repeated .sonarqube.db.issues.Location location = 1;</code> */ public java.util.List<? extends org.sonar.db.protobuf.DbIssues.LocationOrBuilder> getLocationOrBuilderList() { return location_; } /** * <code>repeated .sonarqube.db.issues.Location location = 1;</code> */ public int getLocationCount() { return location_.size(); } /** * <code>repeated .sonarqube.db.issues.Location location = 1;</code> */ public org.sonar.db.protobuf.DbIssues.Location getLocation(int index) { return location_.get(index); } /** * <code>repeated .sonarqube.db.issues.Location location = 1;</code> */ public org.sonar.db.protobuf.DbIssues.LocationOrBuilder getLocationOrBuilder( int index) { return location_.get(index); } private void initFields() { location_ = java.util.Collections.emptyList(); } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); for (int i = 0; i < location_.size(); i++) { output.writeMessage(1, location_.get(i)); } getUnknownFields().writeTo(output); } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; for (int i = 0; i < location_.size(); i++) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(1, location_.get(i)); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } private static final long serialVersionUID = 0L; @java.lang.Override protected java.lang.Object writeReplace() throws java.io.ObjectStreamException { return super.writeReplace(); } public static org.sonar.db.protobuf.DbIssues.ExecutionFlow parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static org.sonar.db.protobuf.DbIssues.ExecutionFlow parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static org.sonar.db.protobuf.DbIssues.ExecutionFlow parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static org.sonar.db.protobuf.DbIssues.ExecutionFlow parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static org.sonar.db.protobuf.DbIssues.ExecutionFlow parseFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static org.sonar.db.protobuf.DbIssues.ExecutionFlow parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static org.sonar.db.protobuf.DbIssues.ExecutionFlow parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseDelimitedFrom(input); } public static org.sonar.db.protobuf.DbIssues.ExecutionFlow parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseDelimitedFrom(input, extensionRegistry); } public static org.sonar.db.protobuf.DbIssues.ExecutionFlow parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static org.sonar.db.protobuf.DbIssues.ExecutionFlow parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(org.sonar.db.protobuf.DbIssues.ExecutionFlow prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code sonarqube.db.issues.ExecutionFlow} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:sonarqube.db.issues.ExecutionFlow) org.sonar.db.protobuf.DbIssues.ExecutionFlowOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return org.sonar.db.protobuf.DbIssues.internal_static_sonarqube_db_issues_ExecutionFlow_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return org.sonar.db.protobuf.DbIssues.internal_static_sonarqube_db_issues_ExecutionFlow_fieldAccessorTable .ensureFieldAccessorsInitialized( org.sonar.db.protobuf.DbIssues.ExecutionFlow.class, org.sonar.db.protobuf.DbIssues.ExecutionFlow.Builder.class); } // Construct using org.sonar.db.protobuf.DbIssues.ExecutionFlow.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { getLocationFieldBuilder(); } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); if (locationBuilder_ == null) { location_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); } else { locationBuilder_.clear(); } return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return org.sonar.db.protobuf.DbIssues.internal_static_sonarqube_db_issues_ExecutionFlow_descriptor; } public org.sonar.db.protobuf.DbIssues.ExecutionFlow getDefaultInstanceForType() { return org.sonar.db.protobuf.DbIssues.ExecutionFlow.getDefaultInstance(); } public org.sonar.db.protobuf.DbIssues.ExecutionFlow build() { org.sonar.db.protobuf.DbIssues.ExecutionFlow result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public org.sonar.db.protobuf.DbIssues.ExecutionFlow buildPartial() { org.sonar.db.protobuf.DbIssues.ExecutionFlow result = new org.sonar.db.protobuf.DbIssues.ExecutionFlow(this); int from_bitField0_ = bitField0_; if (locationBuilder_ == null) { if (((bitField0_ & 0x00000001) == 0x00000001)) { location_ = java.util.Collections.unmodifiableList(location_); bitField0_ = (bitField0_ & ~0x00000001); } result.location_ = location_; } else { result.location_ = locationBuilder_.build(); } onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof org.sonar.db.protobuf.DbIssues.ExecutionFlow) { return mergeFrom((org.sonar.db.protobuf.DbIssues.ExecutionFlow)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(org.sonar.db.protobuf.DbIssues.ExecutionFlow other) { if (other == org.sonar.db.protobuf.DbIssues.ExecutionFlow.getDefaultInstance()) return this; if (locationBuilder_ == null) { if (!other.location_.isEmpty()) { if (location_.isEmpty()) { location_ = other.location_; bitField0_ = (bitField0_ & ~0x00000001); } else { ensureLocationIsMutable(); location_.addAll(other.location_); } onChanged(); } } else { if (!other.location_.isEmpty()) { if (locationBuilder_.isEmpty()) { locationBuilder_.dispose(); locationBuilder_ = null; location_ = other.location_; bitField0_ = (bitField0_ & ~0x00000001); locationBuilder_ = com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders ? getLocationFieldBuilder() : null; } else { locationBuilder_.addAllMessages(other.location_); } } } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { org.sonar.db.protobuf.DbIssues.ExecutionFlow parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (org.sonar.db.protobuf.DbIssues.ExecutionFlow) e.getUnfinishedMessage(); throw e; } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private java.util.List<org.sonar.db.protobuf.DbIssues.Location> location_ = java.util.Collections.emptyList(); private void ensureLocationIsMutable() { if (!((bitField0_ & 0x00000001) == 0x00000001)) { location_ = new java.util.ArrayList<org.sonar.db.protobuf.DbIssues.Location>(location_); bitField0_ |= 0x00000001; } } private com.google.protobuf.RepeatedFieldBuilder< org.sonar.db.protobuf.DbIssues.Location, org.sonar.db.protobuf.DbIssues.Location.Builder, org.sonar.db.protobuf.DbIssues.LocationOrBuilder> locationBuilder_; /** * <code>repeated .sonarqube.db.issues.Location location = 1;</code> */ public java.util.List<org.sonar.db.protobuf.DbIssues.Location> getLocationList() { if (locationBuilder_ == null) { return java.util.Collections.unmodifiableList(location_); } else { return locationBuilder_.getMessageList(); } } /** * <code>repeated .sonarqube.db.issues.Location location = 1;</code> */ public int getLocationCount() { if (locationBuilder_ == null) { return location_.size(); } else { return locationBuilder_.getCount(); } } /** * <code>repeated .sonarqube.db.issues.Location location = 1;</code> */ public org.sonar.db.protobuf.DbIssues.Location getLocation(int index) { if (locationBuilder_ == null) { return location_.get(index); } else { return locationBuilder_.getMessage(index); } } /** * <code>repeated .sonarqube.db.issues.Location location = 1;</code> */ public Builder setLocation( int index, org.sonar.db.protobuf.DbIssues.Location value) { if (locationBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureLocationIsMutable(); location_.set(index, value); onChanged(); } else { locationBuilder_.setMessage(index, value); } return this; } /** * <code>repeated .sonarqube.db.issues.Location location = 1;</code> */ public Builder setLocation( int index, org.sonar.db.protobuf.DbIssues.Location.Builder builderForValue) { if (locationBuilder_ == null) { ensureLocationIsMutable(); location_.set(index, builderForValue.build()); onChanged(); } else { locationBuilder_.setMessage(index, builderForValue.build()); } return this; } /** * <code>repeated .sonarqube.db.issues.Location location = 1;</code> */ public Builder addLocation(org.sonar.db.protobuf.DbIssues.Location value) { if (locationBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureLocationIsMutable(); location_.add(value); onChanged(); } else { locationBuilder_.addMessage(value); } return this; } /** * <code>repeated .sonarqube.db.issues.Location location = 1;</code> */ public Builder addLocation( int index, org.sonar.db.protobuf.DbIssues.Location value) { if (locationBuilder_ == null) { if (value == null) { throw new NullPointerException(); } ensureLocationIsMutable(); location_.add(index, value); onChanged(); } else { locationBuilder_.addMessage(index, value); } return this; } /** * <code>repeated .sonarqube.db.issues.Location location = 1;</code> */ public Builder addLocation( org.sonar.db.protobuf.DbIssues.Location.Builder builderForValue) { if (locationBuilder_ == null) { ensureLocationIsMutable(); location_.add(builderForValue.build()); onChanged(); } else { locationBuilder_.addMessage(builderForValue.build()); } return this; } /** * <code>repeated .sonarqube.db.issues.Location location = 1;</code> */ public Builder addLocation( int index, org.sonar.db.protobuf.DbIssues.Location.Builder builderForValue) { if (locationBuilder_ == null) { ensureLocationIsMutable(); location_.add(index, builderForValue.build()); onChanged(); } else { locationBuilder_.addMessage(index, builderForValue.build()); } return this; } /** * <code>repeated .sonarqube.db.issues.Location location = 1;</code> */ public Builder addAllLocation( java.lang.Iterable<? extends org.sonar.db.protobuf.DbIssues.Location> values) { if (locationBuilder_ == null) { ensureLocationIsMutable(); com.google.protobuf.AbstractMessageLite.Builder.addAll( values, location_); onChanged(); } else { locationBuilder_.addAllMessages(values); } return this; } /** * <code>repeated .sonarqube.db.issues.Location location = 1;</code> */ public Builder clearLocation() { if (locationBuilder_ == null) { location_ = java.util.Collections.emptyList(); bitField0_ = (bitField0_ & ~0x00000001); onChanged(); } else { locationBuilder_.clear(); } return this; } /** * <code>repeated .sonarqube.db.issues.Location location = 1;</code> */ public Builder removeLocation(int index) { if (locationBuilder_ == null) { ensureLocationIsMutable(); location_.remove(index); onChanged(); } else { locationBuilder_.remove(index); } return this; } /** * <code>repeated .sonarqube.db.issues.Location location = 1;</code> */ public org.sonar.db.protobuf.DbIssues.Location.Builder getLocationBuilder( int index) { return getLocationFieldBuilder().getBuilder(index); } /** * <code>repeated .sonarqube.db.issues.Location location = 1;</code> */ public org.sonar.db.protobuf.DbIssues.LocationOrBuilder getLocationOrBuilder( int index) { if (locationBuilder_ == null) { return location_.get(index); } else { return locationBuilder_.getMessageOrBuilder(index); } } /** * <code>repeated .sonarqube.db.issues.Location location = 1;</code> */ public java.util.List<? extends org.sonar.db.protobuf.DbIssues.LocationOrBuilder> getLocationOrBuilderList() { if (locationBuilder_ != null) { return locationBuilder_.getMessageOrBuilderList(); } else { return java.util.Collections.unmodifiableList(location_); } } /** * <code>repeated .sonarqube.db.issues.Location location = 1;</code> */ public org.sonar.db.protobuf.DbIssues.Location.Builder addLocationBuilder() { return getLocationFieldBuilder().addBuilder( org.sonar.db.protobuf.DbIssues.Location.getDefaultInstance()); } /** * <code>repeated .sonarqube.db.issues.Location location = 1;</code> */ public org.sonar.db.protobuf.DbIssues.Location.Builder addLocationBuilder( int index) { return getLocationFieldBuilder().addBuilder( index, org.sonar.db.protobuf.DbIssues.Location.getDefaultInstance()); } /** * <code>repeated .sonarqube.db.issues.Location location = 1;</code> */ public java.util.List<org.sonar.db.protobuf.DbIssues.Location.Builder> getLocationBuilderList() { return getLocationFieldBuilder().getBuilderList(); } private com.google.protobuf.RepeatedFieldBuilder< org.sonar.db.protobuf.DbIssues.Location, org.sonar.db.protobuf.DbIssues.Location.Builder, org.sonar.db.protobuf.DbIssues.LocationOrBuilder> getLocationFieldBuilder() { if (locationBuilder_ == null) { locationBuilder_ = new com.google.protobuf.RepeatedFieldBuilder< org.sonar.db.protobuf.DbIssues.Location, org.sonar.db.protobuf.DbIssues.Location.Builder, org.sonar.db.protobuf.DbIssues.LocationOrBuilder>( location_, ((bitField0_ & 0x00000001) == 0x00000001), getParentForChildren(), isClean()); location_ = null; } return locationBuilder_; } // @@protoc_insertion_point(builder_scope:sonarqube.db.issues.ExecutionFlow) } static { defaultInstance = new ExecutionFlow(true); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:sonarqube.db.issues.ExecutionFlow) } public interface LocationOrBuilder extends // @@protoc_insertion_point(interface_extends:sonarqube.db.issues.Location) com.google.protobuf.MessageOrBuilder { /** * <code>optional string component_id = 1;</code> */ boolean hasComponentId(); /** * <code>optional string component_id = 1;</code> */ java.lang.String getComponentId(); /** * <code>optional string component_id = 1;</code> */ com.google.protobuf.ByteString getComponentIdBytes(); /** * <code>optional .sonarqube.db.commons.TextRange text_range = 2;</code> * * <pre> * Only when component is a file. Can be empty for a file if this is an issue global to the file. * </pre> */ boolean hasTextRange(); /** * <code>optional .sonarqube.db.commons.TextRange text_range = 2;</code> * * <pre> * Only when component is a file. Can be empty for a file if this is an issue global to the file. * </pre> */ org.sonar.db.protobuf.DbCommons.TextRange getTextRange(); /** * <code>optional .sonarqube.db.commons.TextRange text_range = 2;</code> * * <pre> * Only when component is a file. Can be empty for a file if this is an issue global to the file. * </pre> */ org.sonar.db.protobuf.DbCommons.TextRangeOrBuilder getTextRangeOrBuilder(); /** * <code>optional string msg = 3;</code> */ boolean hasMsg(); /** * <code>optional string msg = 3;</code> */ java.lang.String getMsg(); /** * <code>optional string msg = 3;</code> */ com.google.protobuf.ByteString getMsgBytes(); } /** * Protobuf type {@code sonarqube.db.issues.Location} */ public static final class Location extends com.google.protobuf.GeneratedMessage implements // @@protoc_insertion_point(message_implements:sonarqube.db.issues.Location) LocationOrBuilder { // Use Location.newBuilder() to construct. private Location(com.google.protobuf.GeneratedMessage.Builder<?> builder) { super(builder); this.unknownFields = builder.getUnknownFields(); } private Location(boolean noInit) { this.unknownFields = com.google.protobuf.UnknownFieldSet.getDefaultInstance(); } private static final Location defaultInstance; public static Location getDefaultInstance() { return defaultInstance; } public Location getDefaultInstanceForType() { return defaultInstance; } private final com.google.protobuf.UnknownFieldSet unknownFields; @java.lang.Override public final com.google.protobuf.UnknownFieldSet getUnknownFields() { return this.unknownFields; } private Location( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { initFields(); int mutable_bitField0_ = 0; com.google.protobuf.UnknownFieldSet.Builder unknownFields = com.google.protobuf.UnknownFieldSet.newBuilder(); try { boolean done = false; while (!done) { int tag = input.readTag(); switch (tag) { case 0: done = true; break; default: { if (!parseUnknownField(input, unknownFields, extensionRegistry, tag)) { done = true; } break; } case 10: { com.google.protobuf.ByteString bs = input.readBytes(); bitField0_ |= 0x00000001; componentId_ = bs; break; } case 18: { org.sonar.db.protobuf.DbCommons.TextRange.Builder subBuilder = null; if (((bitField0_ & 0x00000002) == 0x00000002)) { subBuilder = textRange_.toBuilder(); } textRange_ = input.readMessage(org.sonar.db.protobuf.DbCommons.TextRange.PARSER, extensionRegistry); if (subBuilder != null) { subBuilder.mergeFrom(textRange_); textRange_ = subBuilder.buildPartial(); } bitField0_ |= 0x00000002; break; } case 26: { com.google.protobuf.ByteString bs = input.readBytes(); bitField0_ |= 0x00000004; msg_ = bs; break; } } } } catch (com.google.protobuf.InvalidProtocolBufferException e) { throw e.setUnfinishedMessage(this); } catch (java.io.IOException e) { throw new com.google.protobuf.InvalidProtocolBufferException( e.getMessage()).setUnfinishedMessage(this); } finally { this.unknownFields = unknownFields.build(); makeExtensionsImmutable(); } } public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return org.sonar.db.protobuf.DbIssues.internal_static_sonarqube_db_issues_Location_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return org.sonar.db.protobuf.DbIssues.internal_static_sonarqube_db_issues_Location_fieldAccessorTable .ensureFieldAccessorsInitialized( org.sonar.db.protobuf.DbIssues.Location.class, org.sonar.db.protobuf.DbIssues.Location.Builder.class); } public static com.google.protobuf.Parser<Location> PARSER = new com.google.protobuf.AbstractParser<Location>() { public Location parsePartialFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return new Location(input, extensionRegistry); } }; @java.lang.Override public com.google.protobuf.Parser<Location> getParserForType() { return PARSER; } private int bitField0_; public static final int COMPONENT_ID_FIELD_NUMBER = 1; private java.lang.Object componentId_; /** * <code>optional string component_id = 1;</code> */ public boolean hasComponentId() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * <code>optional string component_id = 1;</code> */ public java.lang.String getComponentId() { java.lang.Object ref = componentId_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { componentId_ = s; } return s; } } /** * <code>optional string component_id = 1;</code> */ public com.google.protobuf.ByteString getComponentIdBytes() { java.lang.Object ref = componentId_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); componentId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } public static final int TEXT_RANGE_FIELD_NUMBER = 2; private org.sonar.db.protobuf.DbCommons.TextRange textRange_; /** * <code>optional .sonarqube.db.commons.TextRange text_range = 2;</code> * * <pre> * Only when component is a file. Can be empty for a file if this is an issue global to the file. * </pre> */ public boolean hasTextRange() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * <code>optional .sonarqube.db.commons.TextRange text_range = 2;</code> * * <pre> * Only when component is a file. Can be empty for a file if this is an issue global to the file. * </pre> */ public org.sonar.db.protobuf.DbCommons.TextRange getTextRange() { return textRange_; } /** * <code>optional .sonarqube.db.commons.TextRange text_range = 2;</code> * * <pre> * Only when component is a file. Can be empty for a file if this is an issue global to the file. * </pre> */ public org.sonar.db.protobuf.DbCommons.TextRangeOrBuilder getTextRangeOrBuilder() { return textRange_; } public static final int MSG_FIELD_NUMBER = 3; private java.lang.Object msg_; /** * <code>optional string msg = 3;</code> */ public boolean hasMsg() { return ((bitField0_ & 0x00000004) == 0x00000004); } /** * <code>optional string msg = 3;</code> */ public java.lang.String getMsg() { java.lang.Object ref = msg_; if (ref instanceof java.lang.String) { return (java.lang.String) ref; } else { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { msg_ = s; } return s; } } /** * <code>optional string msg = 3;</code> */ public com.google.protobuf.ByteString getMsgBytes() { java.lang.Object ref = msg_; if (ref instanceof java.lang.String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); msg_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } private void initFields() { componentId_ = ""; textRange_ = org.sonar.db.protobuf.DbCommons.TextRange.getDefaultInstance(); msg_ = ""; } private byte memoizedIsInitialized = -1; public final boolean isInitialized() { byte isInitialized = memoizedIsInitialized; if (isInitialized == 1) return true; if (isInitialized == 0) return false; memoizedIsInitialized = 1; return true; } public void writeTo(com.google.protobuf.CodedOutputStream output) throws java.io.IOException { getSerializedSize(); if (((bitField0_ & 0x00000001) == 0x00000001)) { output.writeBytes(1, getComponentIdBytes()); } if (((bitField0_ & 0x00000002) == 0x00000002)) { output.writeMessage(2, textRange_); } if (((bitField0_ & 0x00000004) == 0x00000004)) { output.writeBytes(3, getMsgBytes()); } getUnknownFields().writeTo(output); } private int memoizedSerializedSize = -1; public int getSerializedSize() { int size = memoizedSerializedSize; if (size != -1) return size; size = 0; if (((bitField0_ & 0x00000001) == 0x00000001)) { size += com.google.protobuf.CodedOutputStream .computeBytesSize(1, getComponentIdBytes()); } if (((bitField0_ & 0x00000002) == 0x00000002)) { size += com.google.protobuf.CodedOutputStream .computeMessageSize(2, textRange_); } if (((bitField0_ & 0x00000004) == 0x00000004)) { size += com.google.protobuf.CodedOutputStream .computeBytesSize(3, getMsgBytes()); } size += getUnknownFields().getSerializedSize(); memoizedSerializedSize = size; return size; } private static final long serialVersionUID = 0L; @java.lang.Override protected java.lang.Object writeReplace() throws java.io.ObjectStreamException { return super.writeReplace(); } public static org.sonar.db.protobuf.DbIssues.Location parseFrom( com.google.protobuf.ByteString data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static org.sonar.db.protobuf.DbIssues.Location parseFrom( com.google.protobuf.ByteString data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static org.sonar.db.protobuf.DbIssues.Location parseFrom(byte[] data) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data); } public static org.sonar.db.protobuf.DbIssues.Location parseFrom( byte[] data, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws com.google.protobuf.InvalidProtocolBufferException { return PARSER.parseFrom(data, extensionRegistry); } public static org.sonar.db.protobuf.DbIssues.Location parseFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static org.sonar.db.protobuf.DbIssues.Location parseFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static org.sonar.db.protobuf.DbIssues.Location parseDelimitedFrom(java.io.InputStream input) throws java.io.IOException { return PARSER.parseDelimitedFrom(input); } public static org.sonar.db.protobuf.DbIssues.Location parseDelimitedFrom( java.io.InputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseDelimitedFrom(input, extensionRegistry); } public static org.sonar.db.protobuf.DbIssues.Location parseFrom( com.google.protobuf.CodedInputStream input) throws java.io.IOException { return PARSER.parseFrom(input); } public static org.sonar.db.protobuf.DbIssues.Location parseFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { return PARSER.parseFrom(input, extensionRegistry); } public static Builder newBuilder() { return Builder.create(); } public Builder newBuilderForType() { return newBuilder(); } public static Builder newBuilder(org.sonar.db.protobuf.DbIssues.Location prototype) { return newBuilder().mergeFrom(prototype); } public Builder toBuilder() { return newBuilder(this); } @java.lang.Override protected Builder newBuilderForType( com.google.protobuf.GeneratedMessage.BuilderParent parent) { Builder builder = new Builder(parent); return builder; } /** * Protobuf type {@code sonarqube.db.issues.Location} */ public static final class Builder extends com.google.protobuf.GeneratedMessage.Builder<Builder> implements // @@protoc_insertion_point(builder_implements:sonarqube.db.issues.Location) org.sonar.db.protobuf.DbIssues.LocationOrBuilder { public static final com.google.protobuf.Descriptors.Descriptor getDescriptor() { return org.sonar.db.protobuf.DbIssues.internal_static_sonarqube_db_issues_Location_descriptor; } protected com.google.protobuf.GeneratedMessage.FieldAccessorTable internalGetFieldAccessorTable() { return org.sonar.db.protobuf.DbIssues.internal_static_sonarqube_db_issues_Location_fieldAccessorTable .ensureFieldAccessorsInitialized( org.sonar.db.protobuf.DbIssues.Location.class, org.sonar.db.protobuf.DbIssues.Location.Builder.class); } // Construct using org.sonar.db.protobuf.DbIssues.Location.newBuilder() private Builder() { maybeForceBuilderInitialization(); } private Builder( com.google.protobuf.GeneratedMessage.BuilderParent parent) { super(parent); maybeForceBuilderInitialization(); } private void maybeForceBuilderInitialization() { if (com.google.protobuf.GeneratedMessage.alwaysUseFieldBuilders) { getTextRangeFieldBuilder(); } } private static Builder create() { return new Builder(); } public Builder clear() { super.clear(); componentId_ = ""; bitField0_ = (bitField0_ & ~0x00000001); if (textRangeBuilder_ == null) { textRange_ = org.sonar.db.protobuf.DbCommons.TextRange.getDefaultInstance(); } else { textRangeBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000002); msg_ = ""; bitField0_ = (bitField0_ & ~0x00000004); return this; } public Builder clone() { return create().mergeFrom(buildPartial()); } public com.google.protobuf.Descriptors.Descriptor getDescriptorForType() { return org.sonar.db.protobuf.DbIssues.internal_static_sonarqube_db_issues_Location_descriptor; } public org.sonar.db.protobuf.DbIssues.Location getDefaultInstanceForType() { return org.sonar.db.protobuf.DbIssues.Location.getDefaultInstance(); } public org.sonar.db.protobuf.DbIssues.Location build() { org.sonar.db.protobuf.DbIssues.Location result = buildPartial(); if (!result.isInitialized()) { throw newUninitializedMessageException(result); } return result; } public org.sonar.db.protobuf.DbIssues.Location buildPartial() { org.sonar.db.protobuf.DbIssues.Location result = new org.sonar.db.protobuf.DbIssues.Location(this); int from_bitField0_ = bitField0_; int to_bitField0_ = 0; if (((from_bitField0_ & 0x00000001) == 0x00000001)) { to_bitField0_ |= 0x00000001; } result.componentId_ = componentId_; if (((from_bitField0_ & 0x00000002) == 0x00000002)) { to_bitField0_ |= 0x00000002; } if (textRangeBuilder_ == null) { result.textRange_ = textRange_; } else { result.textRange_ = textRangeBuilder_.build(); } if (((from_bitField0_ & 0x00000004) == 0x00000004)) { to_bitField0_ |= 0x00000004; } result.msg_ = msg_; result.bitField0_ = to_bitField0_; onBuilt(); return result; } public Builder mergeFrom(com.google.protobuf.Message other) { if (other instanceof org.sonar.db.protobuf.DbIssues.Location) { return mergeFrom((org.sonar.db.protobuf.DbIssues.Location)other); } else { super.mergeFrom(other); return this; } } public Builder mergeFrom(org.sonar.db.protobuf.DbIssues.Location other) { if (other == org.sonar.db.protobuf.DbIssues.Location.getDefaultInstance()) return this; if (other.hasComponentId()) { bitField0_ |= 0x00000001; componentId_ = other.componentId_; onChanged(); } if (other.hasTextRange()) { mergeTextRange(other.getTextRange()); } if (other.hasMsg()) { bitField0_ |= 0x00000004; msg_ = other.msg_; onChanged(); } this.mergeUnknownFields(other.getUnknownFields()); return this; } public final boolean isInitialized() { return true; } public Builder mergeFrom( com.google.protobuf.CodedInputStream input, com.google.protobuf.ExtensionRegistryLite extensionRegistry) throws java.io.IOException { org.sonar.db.protobuf.DbIssues.Location parsedMessage = null; try { parsedMessage = PARSER.parsePartialFrom(input, extensionRegistry); } catch (com.google.protobuf.InvalidProtocolBufferException e) { parsedMessage = (org.sonar.db.protobuf.DbIssues.Location) e.getUnfinishedMessage(); throw e; } finally { if (parsedMessage != null) { mergeFrom(parsedMessage); } } return this; } private int bitField0_; private java.lang.Object componentId_ = ""; /** * <code>optional string component_id = 1;</code> */ public boolean hasComponentId() { return ((bitField0_ & 0x00000001) == 0x00000001); } /** * <code>optional string component_id = 1;</code> */ public java.lang.String getComponentId() { java.lang.Object ref = componentId_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { componentId_ = s; } return s; } else { return (java.lang.String) ref; } } /** * <code>optional string component_id = 1;</code> */ public com.google.protobuf.ByteString getComponentIdBytes() { java.lang.Object ref = componentId_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); componentId_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <code>optional string component_id = 1;</code> */ public Builder setComponentId( java.lang.String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000001; componentId_ = value; onChanged(); return this; } /** * <code>optional string component_id = 1;</code> */ public Builder clearComponentId() { bitField0_ = (bitField0_ & ~0x00000001); componentId_ = getDefaultInstance().getComponentId(); onChanged(); return this; } /** * <code>optional string component_id = 1;</code> */ public Builder setComponentIdBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000001; componentId_ = value; onChanged(); return this; } private org.sonar.db.protobuf.DbCommons.TextRange textRange_ = org.sonar.db.protobuf.DbCommons.TextRange.getDefaultInstance(); private com.google.protobuf.SingleFieldBuilder< org.sonar.db.protobuf.DbCommons.TextRange, org.sonar.db.protobuf.DbCommons.TextRange.Builder, org.sonar.db.protobuf.DbCommons.TextRangeOrBuilder> textRangeBuilder_; /** * <code>optional .sonarqube.db.commons.TextRange text_range = 2;</code> * * <pre> * Only when component is a file. Can be empty for a file if this is an issue global to the file. * </pre> */ public boolean hasTextRange() { return ((bitField0_ & 0x00000002) == 0x00000002); } /** * <code>optional .sonarqube.db.commons.TextRange text_range = 2;</code> * * <pre> * Only when component is a file. Can be empty for a file if this is an issue global to the file. * </pre> */ public org.sonar.db.protobuf.DbCommons.TextRange getTextRange() { if (textRangeBuilder_ == null) { return textRange_; } else { return textRangeBuilder_.getMessage(); } } /** * <code>optional .sonarqube.db.commons.TextRange text_range = 2;</code> * * <pre> * Only when component is a file. Can be empty for a file if this is an issue global to the file. * </pre> */ public Builder setTextRange(org.sonar.db.protobuf.DbCommons.TextRange value) { if (textRangeBuilder_ == null) { if (value == null) { throw new NullPointerException(); } textRange_ = value; onChanged(); } else { textRangeBuilder_.setMessage(value); } bitField0_ |= 0x00000002; return this; } /** * <code>optional .sonarqube.db.commons.TextRange text_range = 2;</code> * * <pre> * Only when component is a file. Can be empty for a file if this is an issue global to the file. * </pre> */ public Builder setTextRange( org.sonar.db.protobuf.DbCommons.TextRange.Builder builderForValue) { if (textRangeBuilder_ == null) { textRange_ = builderForValue.build(); onChanged(); } else { textRangeBuilder_.setMessage(builderForValue.build()); } bitField0_ |= 0x00000002; return this; } /** * <code>optional .sonarqube.db.commons.TextRange text_range = 2;</code> * * <pre> * Only when component is a file. Can be empty for a file if this is an issue global to the file. * </pre> */ public Builder mergeTextRange(org.sonar.db.protobuf.DbCommons.TextRange value) { if (textRangeBuilder_ == null) { if (((bitField0_ & 0x00000002) == 0x00000002) && textRange_ != org.sonar.db.protobuf.DbCommons.TextRange.getDefaultInstance()) { textRange_ = org.sonar.db.protobuf.DbCommons.TextRange.newBuilder(textRange_).mergeFrom(value).buildPartial(); } else { textRange_ = value; } onChanged(); } else { textRangeBuilder_.mergeFrom(value); } bitField0_ |= 0x00000002; return this; } /** * <code>optional .sonarqube.db.commons.TextRange text_range = 2;</code> * * <pre> * Only when component is a file. Can be empty for a file if this is an issue global to the file. * </pre> */ public Builder clearTextRange() { if (textRangeBuilder_ == null) { textRange_ = org.sonar.db.protobuf.DbCommons.TextRange.getDefaultInstance(); onChanged(); } else { textRangeBuilder_.clear(); } bitField0_ = (bitField0_ & ~0x00000002); return this; } /** * <code>optional .sonarqube.db.commons.TextRange text_range = 2;</code> * * <pre> * Only when component is a file. Can be empty for a file if this is an issue global to the file. * </pre> */ public org.sonar.db.protobuf.DbCommons.TextRange.Builder getTextRangeBuilder() { bitField0_ |= 0x00000002; onChanged(); return getTextRangeFieldBuilder().getBuilder(); } /** * <code>optional .sonarqube.db.commons.TextRange text_range = 2;</code> * * <pre> * Only when component is a file. Can be empty for a file if this is an issue global to the file. * </pre> */ public org.sonar.db.protobuf.DbCommons.TextRangeOrBuilder getTextRangeOrBuilder() { if (textRangeBuilder_ != null) { return textRangeBuilder_.getMessageOrBuilder(); } else { return textRange_; } } /** * <code>optional .sonarqube.db.commons.TextRange text_range = 2;</code> * * <pre> * Only when component is a file. Can be empty for a file if this is an issue global to the file. * </pre> */ private com.google.protobuf.SingleFieldBuilder< org.sonar.db.protobuf.DbCommons.TextRange, org.sonar.db.protobuf.DbCommons.TextRange.Builder, org.sonar.db.protobuf.DbCommons.TextRangeOrBuilder> getTextRangeFieldBuilder() { if (textRangeBuilder_ == null) { textRangeBuilder_ = new com.google.protobuf.SingleFieldBuilder< org.sonar.db.protobuf.DbCommons.TextRange, org.sonar.db.protobuf.DbCommons.TextRange.Builder, org.sonar.db.protobuf.DbCommons.TextRangeOrBuilder>( getTextRange(), getParentForChildren(), isClean()); textRange_ = null; } return textRangeBuilder_; } private java.lang.Object msg_ = ""; /** * <code>optional string msg = 3;</code> */ public boolean hasMsg() { return ((bitField0_ & 0x00000004) == 0x00000004); } /** * <code>optional string msg = 3;</code> */ public java.lang.String getMsg() { java.lang.Object ref = msg_; if (!(ref instanceof java.lang.String)) { com.google.protobuf.ByteString bs = (com.google.protobuf.ByteString) ref; java.lang.String s = bs.toStringUtf8(); if (bs.isValidUtf8()) { msg_ = s; } return s; } else { return (java.lang.String) ref; } } /** * <code>optional string msg = 3;</code> */ public com.google.protobuf.ByteString getMsgBytes() { java.lang.Object ref = msg_; if (ref instanceof String) { com.google.protobuf.ByteString b = com.google.protobuf.ByteString.copyFromUtf8( (java.lang.String) ref); msg_ = b; return b; } else { return (com.google.protobuf.ByteString) ref; } } /** * <code>optional string msg = 3;</code> */ public Builder setMsg( java.lang.String value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000004; msg_ = value; onChanged(); return this; } /** * <code>optional string msg = 3;</code> */ public Builder clearMsg() { bitField0_ = (bitField0_ & ~0x00000004); msg_ = getDefaultInstance().getMsg(); onChanged(); return this; } /** * <code>optional string msg = 3;</code> */ public Builder setMsgBytes( com.google.protobuf.ByteString value) { if (value == null) { throw new NullPointerException(); } bitField0_ |= 0x00000004; msg_ = value; onChanged(); return this; } // @@protoc_insertion_point(builder_scope:sonarqube.db.issues.Location) } static { defaultInstance = new Location(true); defaultInstance.initFields(); } // @@protoc_insertion_point(class_scope:sonarqube.db.issues.Location) } private static final com.google.protobuf.Descriptors.Descriptor internal_static_sonarqube_db_issues_Locations_descriptor; private static com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_sonarqube_db_issues_Locations_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_sonarqube_db_issues_ExecutionFlow_descriptor; private static com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_sonarqube_db_issues_ExecutionFlow_fieldAccessorTable; private static final com.google.protobuf.Descriptors.Descriptor internal_static_sonarqube_db_issues_Location_descriptor; private static com.google.protobuf.GeneratedMessage.FieldAccessorTable internal_static_sonarqube_db_issues_Location_fieldAccessorTable; public static com.google.protobuf.Descriptors.FileDescriptor getDescriptor() { return descriptor; } private static com.google.protobuf.Descriptors.FileDescriptor descriptor; static { java.lang.String[] descriptorData = { "\n\017db-issues.proto\022\023sonarqube.db.issues\032\020" + "db-commons.proto\"\253\001\n\tLocations\0220\n\007primar" + "y\030\001 \001(\0132\037.sonarqube.db.commons.TextRange" + "\0220\n\tsecondary\030\002 \003(\0132\035.sonarqube.db.issue" + "s.Location\022:\n\016execution_flow\030\003 \003(\0132\".son" + "arqube.db.issues.ExecutionFlow\"@\n\rExecut" + "ionFlow\022/\n\010location\030\001 \003(\0132\035.sonarqube.db" + ".issues.Location\"b\n\010Location\022\024\n\014componen" + "t_id\030\001 \001(\t\0223\n\ntext_range\030\002 \001(\0132\037.sonarqu" + "be.db.commons.TextRange\022\013\n\003msg\030\003 \001(\tB\031\n\025", "org.sonar.db.protobufH\001" }; com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner = new com.google.protobuf.Descriptors.FileDescriptor. InternalDescriptorAssigner() { public com.google.protobuf.ExtensionRegistry assignDescriptors( com.google.protobuf.Descriptors.FileDescriptor root) { descriptor = root; return null; } }; com.google.protobuf.Descriptors.FileDescriptor .internalBuildGeneratedFileFrom(descriptorData, new com.google.protobuf.Descriptors.FileDescriptor[] { org.sonar.db.protobuf.DbCommons.getDescriptor(), }, assigner); internal_static_sonarqube_db_issues_Locations_descriptor = getDescriptor().getMessageTypes().get(0); internal_static_sonarqube_db_issues_Locations_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_sonarqube_db_issues_Locations_descriptor, new java.lang.String[] { "Primary", "Secondary", "ExecutionFlow", }); internal_static_sonarqube_db_issues_ExecutionFlow_descriptor = getDescriptor().getMessageTypes().get(1); internal_static_sonarqube_db_issues_ExecutionFlow_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_sonarqube_db_issues_ExecutionFlow_descriptor, new java.lang.String[] { "Location", }); internal_static_sonarqube_db_issues_Location_descriptor = getDescriptor().getMessageTypes().get(2); internal_static_sonarqube_db_issues_Location_fieldAccessorTable = new com.google.protobuf.GeneratedMessage.FieldAccessorTable( internal_static_sonarqube_db_issues_Location_descriptor, new java.lang.String[] { "ComponentId", "TextRange", "Msg", }); org.sonar.db.protobuf.DbCommons.getDescriptor(); } // @@protoc_insertion_point(outer_class_scope) }
lgpl-3.0
JKatzwinkel/bts
org.eclipse.xtext.ui/src/org/eclipse/xtext/ui/editor/contentassist/PrefixMatcher.java
1968
/******************************************************************************* * Copyright (c) 2009 itemis AG (http://www.itemis.eu) and others. * All rights reserved. This program and the accompanying materials * are made available under the terms of the Eclipse Public License v1.0 * which accompanies this distribution, and is available at * http://www.eclipse.org/legal/epl-v10.html *******************************************************************************/ package org.eclipse.xtext.ui.editor.contentassist; import com.google.inject.ImplementedBy; /** * @author Sebastian Zarnekow - Initial contribution and API */ @ImplementedBy(PrefixMatcher.IgnoreCase.class) public abstract class PrefixMatcher { public abstract boolean isCandidateMatchingPrefix(String name, String prefix); @ImplementedBy(PrefixMatcher.CamelCase.class) public static class IgnoreCase extends PrefixMatcher { @Override public boolean isCandidateMatchingPrefix(String name, String prefix) { return name.regionMatches(true, 0, prefix, 0, prefix.length()); } } public static class CamelCase extends PrefixMatcher.IgnoreCase { private boolean canDoCamelCaseMatch = true; public CamelCase() { canDoCamelCaseMatch = isJdtAvailable(); } /** * @since 2.1 */ protected boolean isJdtAvailable() { try { org.eclipse.jdt.core.compiler.CharOperation.camelCaseMatch(null, null); return true; } catch(Throwable t) { return false; } } @Override public boolean isCandidateMatchingPrefix(String name, String prefix) { boolean result = super.isCandidateMatchingPrefix(name, prefix) || canDoCamelCaseMatch && prefix.length() < name.length() && camelCaseMatch(name, prefix); return result; } /** * @since 2.1 */ protected boolean camelCaseMatch(String name, String prefix) { return org.eclipse.jdt.core.compiler.CharOperation.camelCaseMatch(prefix.toCharArray(), name.toCharArray()); } } }
lgpl-3.0
joseliko7/Panic-Button
app/src/main/java/com/ghzmdr/panicbutton/PositionInfoDialog.java
1157
package com.ghzmdr.panicbutton; import android.app.Dialog; import android.content.Context; import android.location.Location; import android.widget.LinearLayout; import android.widget.TextView; /** * Created by ghzmdr on 19/01/15. */ public class PositionInfoDialog extends Dialog{ public PositionInfoDialog(Location l, Context context) { super(context); setTitle("You are here:"); TextView textLat = new TextView(context); textLat.setTextSize(20); textLat.setText("Latitude: " + l.getLatitude()); TextView textLon = new TextView(context); textLon.setTextSize(20); textLon.setText("Longitude: " + l.getLongitude()); TextView textAddr = new TextView(context); textAddr.setTextSize(20); textAddr.setText("Address: " + Locator.getAddressFromLocation(l, context)); LinearLayout ll = new LinearLayout(context); ll.setOrientation(LinearLayout.VERTICAL); ll.setPadding(30,30,30,30); ll.addView(textLat); ll.addView(textLon); ll.addView(textAddr); setContentView(ll); setCancelable(true); } }
unlicense
SleepyTrousers/EnderIO
enderio-base/src/main/java/crazypants/enderio/api/EnderIOAPIProps.java
158
package crazypants.enderio.api; public final class EnderIOAPIProps { private EnderIOAPIProps() {} public static final String VERSION = "4.0.0"; }
unlicense
SoftwareOnPurpose/validator4test
src/main/java/com/softwareonpurpose/validator4test/Reconciler.java
1858
/** * Copyright 2017 Craig A. Stockton * <p> * 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 * <p> * http://www.apache.org/licenses/LICENSE-2.0 * <p> * 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.softwareonpurpose.validator4test; @SuppressWarnings("SpellCheckingInspection") class Reconciler { private final static int RECONCILED = 0; private final static int EXPECTED_NULL = 1; private final static int ACTUAL_NULL = 2; private final static int DISCREPANCY = 3; private final Object actual; private final Object expected; private Reconciler(Object expected, Object actual) { this.expected = expected; this.actual = actual; } /** * Get an instance of a Reconciler * * @return An instance of Reconciler */ static Reconciler getInstance(Object expected, Object actual) { return new Reconciler(expected, actual); } /** * @return Integer value indicating the reconciliation result (0 - Reconciled; 1 - Expected is null; 2 - Actual is * null; 3 - Discrepancy exists) */ int reconcile() { if (expected == null && actual == null) return RECONCILED; if (expected == null) return EXPECTED_NULL; if (actual == null) return ACTUAL_NULL; return actual.equals(expected) ? RECONCILED : DISCREPANCY; } }
apache-2.0
nathancomstock/closure-templates
java/src/com/google/template/soy/passes/CheckCallingParamTypesVisitor.java
15012
/* * Copyright 2014 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.template.soy.passes; import com.google.common.base.Preconditions; import com.google.common.collect.HashMultimap; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableMultimap; import com.google.common.collect.Multimap; import com.google.template.soy.base.SourceLocation; import com.google.template.soy.data.SanitizedContent.ContentKind; import com.google.template.soy.error.ErrorReporter; import com.google.template.soy.error.SoyErrorKind; import com.google.template.soy.exprtree.ExprNode; import com.google.template.soy.passes.FindIndirectParamsVisitor.IndirectParamsInfo; import com.google.template.soy.soytree.AbstractSoyNodeVisitor; import com.google.template.soy.soytree.CallBasicNode; import com.google.template.soy.soytree.CallDelegateNode; import com.google.template.soy.soytree.CallNode; import com.google.template.soy.soytree.CallParamContentNode; import com.google.template.soy.soytree.CallParamNode; import com.google.template.soy.soytree.CallParamValueNode; import com.google.template.soy.soytree.SoyNode; import com.google.template.soy.soytree.SoyNode.ParentSoyNode; import com.google.template.soy.soytree.TemplateDelegateNode; import com.google.template.soy.soytree.TemplateNode; import com.google.template.soy.soytree.TemplateRegistry; import com.google.template.soy.soytree.defn.HeaderParam; import com.google.template.soy.soytree.defn.TemplateParam; import com.google.template.soy.soytree.defn.TemplateParam.DeclLoc; import com.google.template.soy.types.SoyType; import com.google.template.soy.types.SoyTypes; import com.google.template.soy.types.aggregate.UnionType; import com.google.template.soy.types.primitive.SanitizedType; import com.google.template.soy.types.primitive.StringType; import com.google.template.soy.types.proto.SoyProtoType; import java.util.Collection; import java.util.HashMap; import java.util.HashSet; import java.util.Map; import java.util.Set; /** * Visitor for checking that calling arguments match the declared parameter types * of the called template. Throws a SoySyntaxException if any problems are found. * Note that we don't check for missing parameters, that check is done by * CheckCallsVisitor. * * <p>In addition to checking that static types match and flagging errors, this * visitor also stores a set of TemplateParam object in each CallNode for all the * params that require runtime checking. * * Note: This pass requires that the ResolveExpressionTypesVisitor has already * been run. * */ final class CheckCallingParamTypesVisitor extends AbstractSoyNodeVisitor<Void> { private static final SoyErrorKind ARGUMENT_TYPE_MISMATCH = SoyErrorKind.of("Type mismatch on param {0}: expected: {1}, actual: {2}."); private static final SoyErrorKind PASSING_PROTOBUF_FROM_STRICT_TO_NON_STRICT = SoyErrorKind.of("Passing protobuf {0} of type {1} to non-strict template not allowed."); /** Registry of all templates in the Soy tree. */ private final TemplateRegistry templateRegistry; /** The current template being checked. */ private TemplateNode callerTemplate; /** Map of all template parameters, both explicit and implicit, organized by template. */ private final Map<TemplateNode, TemplateParamTypes> paramTypesMap = new HashMap<>(); private final ErrorReporter errorReporter; CheckCallingParamTypesVisitor(TemplateRegistry registry, ErrorReporter errorReporter) { this.templateRegistry = registry; this.errorReporter = errorReporter; } @Override protected void visitCallBasicNode(CallBasicNode node) { TemplateNode callee = templateRegistry.getBasicTemplate(node.getCalleeName()); if (callee != null) { Set<TemplateParam> paramsToRuntimeCheck = checkCallParamTypes(node, callee); node.setParamsToRuntimeCheck(paramsToRuntimeCheck); } visitChildren(node); } @Override protected void visitCallDelegateNode(CallDelegateNode node) { ImmutableMap.Builder<TemplateDelegateNode, ImmutableList<TemplateParam>> paramsToCheckByTemplate = ImmutableMap.builder(); ImmutableMultimap<String, TemplateDelegateNode> delTemplateNameToValues = templateRegistry.getDelTemplateSelector().delTemplateNameToValues(); for (TemplateDelegateNode delTemplate : delTemplateNameToValues.get(node.getDelCalleeName())) { Set<TemplateParam> params = checkCallParamTypes(node, delTemplate); paramsToCheckByTemplate.put(delTemplate, ImmutableList.copyOf(params)); } node.setParamsToRuntimeCheck(paramsToCheckByTemplate.build()); visitChildren(node); } @Override protected void visitSoyNode(SoyNode node) { if (node instanceof ParentSoyNode<?>) { visitChildren((ParentSoyNode<?>) node); } } @Override protected void visitTemplateNode(TemplateNode node) { callerTemplate = node; visitChildren(node); callerTemplate = null; } /** * Returns the subset of {@link TemplateNode#getParams() callee params} that require runtime type * checking. */ private Set<TemplateParam> checkCallParamTypes(CallNode call, TemplateNode callee) { TemplateParamTypes calleeParamTypes = getTemplateParamTypes(callee); // Explicit params being passed by the CallNode Set<String> explicitParams = new HashSet<>(); // The set of params the need runtime type checking at template call time. We start this with // all the params of the callee and remove each param that is statically verified. Set<String> paramNamesToRuntimeCheck = new HashSet<>(calleeParamTypes.params.keySet()); // indirect params should be checked at their callsites, not this one. paramNamesToRuntimeCheck.removeAll(calleeParamTypes.indirectParamNames); // First check all the {param} blocks of the caller to make sure that the types match. for (CallParamNode callerParam : call.getChildren()) { SoyType argType = null; if (callerParam.getKind() == SoyNode.Kind.CALL_PARAM_VALUE_NODE) { ExprNode expr = ((CallParamValueNode) callerParam).getValueExprUnion().getExpr(); if (expr != null) { argType = expr.getType(); } } else if (callerParam.getKind() == SoyNode.Kind.CALL_PARAM_CONTENT_NODE) { ContentKind contentKind = ((CallParamContentNode) callerParam).getContentKind(); argType = contentKind == null ? StringType.getInstance() : SanitizedType.getTypeForContentKind(contentKind); } String paramName = callerParam.getKey(); if (argType != null) { // The types of the parameters. If this is an explicitly declared parameter, // then this collection will have only one member; If it's an implicit // parameter then this may contain multiple types. Note we don't use // a union here because the rules are a bit different than the normal rules // for assigning union types. // It's possible that the set may be empty, because all of the callees // are external. In that case there's nothing we can do, so we don't // report anything. Collection<SoyType> declaredParamTypes = calleeParamTypes.params.get(paramName); boolean staticTypeSafe = true; for (SoyType formalType : declaredParamTypes) { staticTypeSafe &= checkArgumentAgainstParamType( callerParam.getSourceLocation(), paramName, argType, formalType, calleeParamTypes); } if (staticTypeSafe) { paramNamesToRuntimeCheck.remove(paramName); } } explicitParams.add(paramName); } // If the caller is passing data via data="all" then we look for matching static param // declarations in the callers template and see if there are type errors there. if (call.dataAttribute().isPassingData()) { if (call.dataAttribute().isPassingAllData() && callerTemplate.getParams() != null) { // Check indirect params that are passed via data="all". // We only need to check explicit params of calling template here. for (TemplateParam callerParam : callerTemplate.getParams()) { if (!(callerParam instanceof HeaderParam)) { continue; } String paramName = callerParam.name(); // The parameter is explicitly overridden with another value, which we // already checked. if (explicitParams.contains(paramName)) { continue; } Collection<SoyType> declaredParamTypes = calleeParamTypes.params.get(paramName); boolean staticTypeSafe = true; for (SoyType formalType : declaredParamTypes) { staticTypeSafe &= checkArgumentAgainstParamType( call.getSourceLocation(), paramName, callerParam.type(), formalType, calleeParamTypes); } if (staticTypeSafe) { paramNamesToRuntimeCheck.remove(paramName); } } } else { // TODO: Check if the fields of the type of data arg can be assigned to the params. // This is possible for some types, and never allowed for other types. } } // We track the set as names above and transform to TemplateParams here because the above loops // are over the {param}s of the caller and TemplateParams of the callers template, so all we // have are the names of the parameters. To convert them to a TemplateParam of the callee we // need to match the names and it is easier to do that as one pass at the end instead of // iteratively throughout. Set<TemplateParam> paramsToRuntimeCheck = new HashSet<>(); for (TemplateParam param : callee.getParams()) { if (paramNamesToRuntimeCheck.remove(param.name())) { paramsToRuntimeCheck.add(param); } } // sanity check Preconditions.checkState(paramNamesToRuntimeCheck.isEmpty(), "Unexpected callee params %s", paramNamesToRuntimeCheck); return paramsToRuntimeCheck; } /** * Check that the argument passed to the template is compatible with the template * parameter type. * @param location The location to report a type check error. * @param paramName the name of the parameter. * @param argType The type of the value being passed. * @param formalType The type of the parameter. * @param calleeParams metadata about the callee parameters * @return true if runtime type checks can be elided for this param */ private boolean checkArgumentAgainstParamType( SourceLocation location, String paramName, SoyType argType, SoyType formalType, TemplateParamTypes calleeParams) { if (!calleeParams.isStrictlyTyped && formalType.getKind() == SoyType.Kind.UNKNOWN || formalType.getKind() == SoyType.Kind.ANY) { // Special rules for unknown / any if (argType instanceof SoyProtoType) { errorReporter.report( location, PASSING_PROTOBUF_FROM_STRICT_TO_NON_STRICT, paramName, argType); } } else if (argType.getKind() == SoyType.Kind.UNKNOWN) { // Special rules for unknown / any // // This check disabled: We now allow maps created from protos to be passed // to a function accepting a proto, this makes migration easier. // (See GenJsCodeVisitor.genParamTypeChecks). // TODO(user): Re-enable at some future date? // if (formalType instanceof SoyProtoType) { // reportProtoArgumentTypeMismatch(call, paramName, formalType, argType); // } } else { if (!formalType.isAssignableFrom(argType)) { if (calleeParams.isIndirect(paramName) && argType.getKind() == SoyType.Kind.UNION && ((UnionType) argType).isNullable()) { if (SoyTypes.makeNullable(formalType).isAssignableFrom(argType)) { // Special case for indirect params: Allow a nullable type to be assigned // to a non-nullable type if the non-nullable type is an indirect parameter type. // The reason is because without flow analysis, we can't know whether or not // there are if-statements preventing null from being passed as an indirect // param, so we assume all indirect params are optional. return false; } } errorReporter.report(location, ARGUMENT_TYPE_MISMATCH, paramName, formalType, argType); } } return true; } /** * Get the parameter types for a callee. * @param node The template being called. * @return The set of template parameters, both explicit and implicit. */ private TemplateParamTypes getTemplateParamTypes(TemplateNode node) { TemplateParamTypes paramTypes = paramTypesMap.get(node); if (paramTypes == null) { paramTypes = new TemplateParamTypes(); // Store all of the explicitly declared param types if (node.getParams() != null) { for (TemplateParam param : node.getParams()) { if (param.declLoc() == DeclLoc.SOY_DOC) { paramTypes.isStrictlyTyped = false; } Preconditions.checkNotNull(param.type()); paramTypes.params.put(param.name(), param.type()); } } // Store indirect params where there's no conflict with explicit params. // Note that we don't check here whether the explicit type and the implicit // types are in agreement - that will be done when it's this template's // turn to be analyzed as a caller. IndirectParamsInfo ipi = new FindIndirectParamsVisitor(templateRegistry).exec(node); for (String indirectParamName: ipi.indirectParamTypes.keySet()) { if (paramTypes.params.containsKey(indirectParamName)) { continue; } paramTypes.params.putAll(indirectParamName, ipi.indirectParamTypes.get(indirectParamName)); paramTypes.indirectParamNames.add(indirectParamName); } // Save the param types map paramTypesMap.put(node, paramTypes); } return paramTypes; } private static class TemplateParamTypes { public boolean isStrictlyTyped = true; public final Multimap<String, SoyType> params = HashMultimap.create(); public final Set<String> indirectParamNames = new HashSet<>(); public boolean isIndirect(String paramName) { return indirectParamNames.contains(paramName); } } }
apache-2.0
apache/bval
bval-jsr/src/test/java/org/apache/bval/jsr/groups/inheritance/BillableUser.java
1852
/* * 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.bval.jsr.groups.inheritance; import org.apache.bval.jsr.groups.Billable; import org.apache.bval.jsr.groups.BillableCreditCard; import javax.validation.constraints.NotNull; import javax.validation.groups.Default; /** * Description: <br/> */ public class BillableUser { @NotNull private String firstname; @NotNull(groups = Default.class) private String lastname; @NotNull(groups = { Billable.class }) private BillableCreditCard defaultCreditCard; public String getFirstname() { return firstname; } public void setFirstname(String firstname) { this.firstname = firstname; } public String getLastname() { return lastname; } public void setLastname(String lastname) { this.lastname = lastname; } public BillableCreditCard getDefaultCreditCard() { return defaultCreditCard; } public void setDefaultCreditCard(BillableCreditCard defaultCreditCard) { this.defaultCreditCard = defaultCreditCard; } }
apache-2.0
linkedin/pinot
pinot-plugins/pinot-input-format/pinot-json/src/main/java/org/apache/pinot/plugin/inputformat/json/JSONRecordExtractor.java
2408
/** * 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.pinot.plugin.inputformat.json; import com.google.common.collect.ImmutableSet; import java.util.Collections; import java.util.Map; import java.util.Set; import javax.annotation.Nullable; import org.apache.pinot.spi.data.readers.BaseRecordExtractor; import org.apache.pinot.spi.data.readers.GenericRow; import org.apache.pinot.spi.data.readers.RecordExtractorConfig; /** * Extractor for JSON records */ public class JSONRecordExtractor extends BaseRecordExtractor<Map<String, Object>> { private Set<String> _fields; private boolean _extractAll = false; @Override public void init(Set<String> fields, @Nullable RecordExtractorConfig recordExtractorConfig) { if (fields == null || fields.isEmpty()) { _extractAll = true; _fields = Collections.emptySet(); } else { _fields = ImmutableSet.copyOf(fields); } } @Override public GenericRow extract(Map<String, Object> from, GenericRow to) { if (_extractAll) { for (Map.Entry<String, Object> fieldToVal : from.entrySet()) { Object value = fieldToVal.getValue(); if (value != null) { value = convert(value); } to.putValue(fieldToVal.getKey(), value); } } else { for (String fieldName : _fields) { Object value = from.get(fieldName); // NOTE about JSON behavior - cannot distinguish between INT/LONG and FLOAT/DOUBLE. // DataTypeTransformer fixes it. if (value != null) { value = convert(value); } to.putValue(fieldName, value); } } return to; } }
apache-2.0
lsmall/flowable-engine
modules/flowable-variable-service/src/main/java/org/flowable/variable/service/impl/persistence/entity/data/impl/cachematcher/HistoricVariableInstanceByProcInstMatcher.java
1298
/* 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.flowable.variable.service.impl.persistence.entity.data.impl.cachematcher; import org.flowable.common.engine.impl.persistence.cache.CachedEntityMatcherAdapter; import org.flowable.variable.service.impl.persistence.entity.HistoricVariableInstanceEntity; /** * @author Joram Barrez */ public class HistoricVariableInstanceByProcInstMatcher extends CachedEntityMatcherAdapter<HistoricVariableInstanceEntity> { @Override public boolean isRetained(HistoricVariableInstanceEntity historicVariableInstanceEntity, Object parameter) { return historicVariableInstanceEntity.getProcessInstanceId() != null && historicVariableInstanceEntity.getProcessInstanceId().equals((String) parameter); } }
apache-2.0
shs96c/buck
src/com/facebook/buck/features/ocaml/OcamlBuildStep.java
18133
/* * Copyright 2014-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.features.ocaml; import com.facebook.buck.core.build.context.BuildContext; import com.facebook.buck.core.sourcepath.SourcePath; import com.facebook.buck.core.sourcepath.resolver.SourcePathResolver; import com.facebook.buck.cxx.CxxPreprocessorInput; import com.facebook.buck.io.BuildCellRelativePath; import com.facebook.buck.io.filesystem.ProjectFilesystem; import com.facebook.buck.rules.args.Arg; import com.facebook.buck.rules.args.StringArg; import com.facebook.buck.step.ExecutionContext; import com.facebook.buck.step.Step; import com.facebook.buck.step.StepExecutionResult; import com.facebook.buck.step.StepExecutionResults; import com.facebook.buck.step.fs.MakeCleanDirectoryStep; import com.google.common.collect.FluentIterable; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableMap; import com.google.common.collect.ImmutableSet; import java.io.IOException; import java.nio.file.Path; import java.nio.file.Paths; /** A step that preprocesses, compiles, and assembles OCaml sources. */ public class OcamlBuildStep implements Step { private final BuildContext buildContext; private final ProjectFilesystem filesystem; private final OcamlBuildContext ocamlContext; private final ImmutableMap<String, String> cCompilerEnvironment; private final ImmutableList<String> cCompiler; private final ImmutableMap<String, String> cxxCompilerEnvironment; private final ImmutableList<String> cxxCompiler; private final boolean bytecodeOnly; private final boolean hasGeneratedSources; private final OcamlDepToolStep depToolStep; public OcamlBuildStep( BuildContext buildContext, ProjectFilesystem filesystem, OcamlBuildContext ocamlContext, ImmutableMap<String, String> cCompilerEnvironment, ImmutableList<String> cCompiler, ImmutableMap<String, String> cxxCompilerEnvironment, ImmutableList<String> cxxCompiler, boolean bytecodeOnly) { this.buildContext = buildContext; this.filesystem = filesystem; this.ocamlContext = ocamlContext; this.cCompilerEnvironment = cCompilerEnvironment; this.cCompiler = cCompiler; this.cxxCompilerEnvironment = cxxCompilerEnvironment; this.cxxCompiler = cxxCompiler; this.bytecodeOnly = bytecodeOnly; hasGeneratedSources = ocamlContext.getLexInput().size() > 0 || ocamlContext.getYaccInput().size() > 0; ImmutableList<String> ocamlDepFlags = ImmutableList.<String>builder() .addAll( this.ocamlContext.getIncludeFlags(/* isBytecode */ false, /* excludeDeps */ true)) .addAll(this.ocamlContext.getOcamlDepFlags()) .build(); this.depToolStep = new OcamlDepToolStep( filesystem.getRootPath(), this.ocamlContext.getSourcePathResolver(), this.ocamlContext.getOcamlDepTool().get(), ocamlContext.getMLInput(), ocamlDepFlags); } @Override public String getShortName() { return "OCaml compile"; } @Override public String getDescription(ExecutionContext context) { return depToolStep.getDescription(context); } @Override public StepExecutionResult execute(ExecutionContext context) throws IOException, InterruptedException { if (hasGeneratedSources) { StepExecutionResult genExecutionResult = generateSources(context, filesystem.getRootPath()); if (!genExecutionResult.isSuccess()) { return genExecutionResult; } } StepExecutionResult depToolExecutionResult = depToolStep.execute(context); if (!depToolExecutionResult.isSuccess()) { return depToolExecutionResult; } // OCaml requires module A to be present in command line to ocamlopt or ocamlc before // module B if B depends on A. In OCaml circular dependencies are prohibited, so all // dependency relations among modules form DAG. Topologically sorting this graph satisfies the // requirement. // // To get the DAG we launch ocamldep tool which provides the direct dependency information, like // module A depends on modules B, C, D. ImmutableList<Path> sortedInput = sortDependency( depToolStep.getStdout(), ocamlContext.getSourcePathResolver().getAllAbsolutePaths(ocamlContext.getMLInput())); ImmutableList.Builder<Path> nativeLinkerInputs = ImmutableList.builder(); if (!bytecodeOnly) { StepExecutionResult mlCompileNativeExecutionResult = executeMLNativeCompilation( context, filesystem.getRootPath(), sortedInput, nativeLinkerInputs); if (!mlCompileNativeExecutionResult.isSuccess()) { return mlCompileNativeExecutionResult; } } ImmutableList.Builder<Path> bytecodeLinkerInputs = ImmutableList.builder(); StepExecutionResult mlCompileBytecodeExecutionResult = executeMLBytecodeCompilation( context, filesystem.getRootPath(), sortedInput, bytecodeLinkerInputs); if (!mlCompileBytecodeExecutionResult.isSuccess()) { return mlCompileBytecodeExecutionResult; } ImmutableList.Builder<Path> cLinkerInputs = ImmutableList.builder(); StepExecutionResult cCompileExecutionResult = executeCCompilation(context, cLinkerInputs); if (!cCompileExecutionResult.isSuccess()) { return cCompileExecutionResult; } ImmutableList<Path> cObjects = cLinkerInputs.build(); if (!bytecodeOnly) { nativeLinkerInputs.addAll(cObjects); StepExecutionResult nativeLinkExecutionResult = executeNativeLinking(context, nativeLinkerInputs.build()); if (!nativeLinkExecutionResult.isSuccess()) { return nativeLinkExecutionResult; } } bytecodeLinkerInputs.addAll(cObjects); StepExecutionResult bytecodeLinkExecutionResult = executeBytecodeLinking(context, bytecodeLinkerInputs.build()); if (!bytecodeLinkExecutionResult.isSuccess()) { return bytecodeLinkExecutionResult; } if (!ocamlContext.isLibrary()) { Step debugLauncher = new OcamlDebugLauncherStep( filesystem, getResolver(), new OcamlDebugLauncherStep.Args( ocamlContext.getOcamlDebug().get(), ocamlContext.getBytecodeOutput(), ocamlContext.getTransitiveBytecodeIncludes(), ocamlContext.getBytecodeIncludeFlags())); return debugLauncher.execute(context); } else { return StepExecutionResults.SUCCESS; } } private StepExecutionResult executeCCompilation( ExecutionContext context, ImmutableList.Builder<Path> linkerInputs) throws IOException, InterruptedException { ImmutableList.Builder<Arg> cCompileFlags = ImmutableList.builder(); cCompileFlags.addAll(ocamlContext.getCCompileFlags()); cCompileFlags.addAll(StringArg.from(ocamlContext.getCommonCFlags())); CxxPreprocessorInput cxxPreprocessorInput = ocamlContext.getCxxPreprocessorInput(); for (SourcePath cSrc : ocamlContext.getCInput()) { Path outputPath = ocamlContext.getCOutput(getResolver().getAbsolutePath(cSrc)); linkerInputs.add(outputPath); Step compileStep = new OcamlCCompileStep( getResolver(), filesystem.getRootPath(), new OcamlCCompileStep.Args( cCompilerEnvironment, cCompiler, ocamlContext.getOcamlCompiler().get(), ocamlContext.getOcamlInteropIncludesDir(), outputPath, cSrc, cCompileFlags.build(), cxxPreprocessorInput.getIncludes())); StepExecutionResult compileExecutionResult = compileStep.execute(context); if (!compileExecutionResult.isSuccess()) { return compileExecutionResult; } } return StepExecutionResults.SUCCESS; } private StepExecutionResult executeNativeLinking( ExecutionContext context, ImmutableList<Path> linkerInputs) throws IOException, InterruptedException { ImmutableList.Builder<Arg> flags = ImmutableList.builder(); flags.addAll(ocamlContext.getFlags()); flags.addAll(StringArg.from(ocamlContext.getCommonCLinkerFlags())); OcamlLinkStep linkStep = OcamlLinkStep.create( filesystem.getRootPath(), cxxCompilerEnvironment, cxxCompiler, ocamlContext.getOcamlCompiler().get().getCommandPrefix(getResolver()), flags.build(), ocamlContext.getOcamlInteropIncludesDir(), ocamlContext.getNativeOutput(), ocamlContext.getNativeLinkableInput().getArgs(), ocamlContext.getCLinkableInput().getArgs(), linkerInputs, ocamlContext.isLibrary(), /* isBytecode */ false, getResolver()); return linkStep.execute(context); } private StepExecutionResult executeBytecodeLinking( ExecutionContext context, ImmutableList<Path> linkerInputs) throws IOException, InterruptedException { ImmutableList.Builder<Arg> flags = ImmutableList.builder(); flags.addAll(ocamlContext.getFlags()); flags.addAll(StringArg.from(ocamlContext.getCommonCLinkerFlags())); OcamlLinkStep linkStep = OcamlLinkStep.create( filesystem.getRootPath(), cxxCompilerEnvironment, cxxCompiler, ocamlContext.getOcamlBytecodeCompiler().get().getCommandPrefix(getResolver()), flags.build(), ocamlContext.getOcamlInteropIncludesDir(), ocamlContext.getBytecodeOutput(), ocamlContext.getBytecodeLinkableInput().getArgs(), ocamlContext.getCLinkableInput().getArgs(), linkerInputs, ocamlContext.isLibrary(), /* isBytecode */ true, getResolver()); return linkStep.execute(context); } private ImmutableList<Arg> getCompileFlags(boolean isBytecode, boolean excludeDeps) { String output = isBytecode ? ocamlContext.getCompileBytecodeOutputDir().toString() : ocamlContext.getCompileNativeOutputDir().toString(); ImmutableList.Builder<Arg> flagBuilder = ImmutableList.builder(); flagBuilder.addAll( StringArg.from(ocamlContext.getIncludeFlags(isBytecode, /* excludeDeps */ excludeDeps))); flagBuilder.addAll(ocamlContext.getFlags()); flagBuilder.add(StringArg.of(OcamlCompilables.OCAML_INCLUDE_FLAG), StringArg.of(output)); return flagBuilder.build(); } private StepExecutionResult executeMLNativeCompilation( ExecutionContext context, Path workingDirectory, ImmutableList<Path> sortedInput, ImmutableList.Builder<Path> linkerInputs) throws IOException, InterruptedException { for (Step step : MakeCleanDirectoryStep.of( BuildCellRelativePath.fromCellRelativePath( context.getBuildCellRootPath(), filesystem, ocamlContext.getCompileNativeOutputDir()))) { StepExecutionResult mkDirExecutionResult = step.execute(context); if (!mkDirExecutionResult.isSuccess()) { return mkDirExecutionResult; } } for (Path inputOutput : sortedInput) { String inputFileName = inputOutput.getFileName().toString(); String outputFileName = inputFileName .replaceFirst(OcamlCompilables.OCAML_ML_REGEX, OcamlCompilables.OCAML_CMX) .replaceFirst(OcamlCompilables.OCAML_RE_REGEX, OcamlCompilables.OCAML_CMX) .replaceFirst(OcamlCompilables.OCAML_MLI_REGEX, OcamlCompilables.OCAML_CMI) .replaceFirst(OcamlCompilables.OCAML_REI_REGEX, OcamlCompilables.OCAML_CMI); Path outputPath = ocamlContext.getCompileNativeOutputDir().resolve(outputFileName); if (!outputFileName.endsWith(OcamlCompilables.OCAML_CMI)) { linkerInputs.add(outputPath); } ImmutableList<Arg> compileFlags = getCompileFlags(/* isBytecode */ false, /* excludeDeps */ false); Step compileStep = new OcamlMLCompileStep( workingDirectory, getResolver(), new OcamlMLCompileStep.Args( cCompilerEnvironment, cCompiler, ocamlContext.getOcamlCompiler().get(), ocamlContext.getOcamlInteropIncludesDir(), outputPath, inputOutput, compileFlags)); StepExecutionResult compileExecutionResult = compileStep.execute(context); if (!compileExecutionResult.isSuccess()) { return compileExecutionResult; } } return StepExecutionResults.SUCCESS; } private StepExecutionResult executeMLBytecodeCompilation( ExecutionContext context, Path workingDirectory, ImmutableList<Path> sortedInput, ImmutableList.Builder<Path> linkerInputs) throws IOException, InterruptedException { for (Step step : MakeCleanDirectoryStep.of( BuildCellRelativePath.fromCellRelativePath( context.getBuildCellRootPath(), filesystem, ocamlContext.getCompileBytecodeOutputDir()))) { StepExecutionResult mkDirExecutionResult = step.execute(context); if (!mkDirExecutionResult.isSuccess()) { return mkDirExecutionResult; } } for (Path inputOutput : sortedInput) { String inputFileName = inputOutput.getFileName().toString(); String outputFileName = inputFileName .replaceFirst(OcamlCompilables.OCAML_ML_REGEX, OcamlCompilables.OCAML_CMO) .replaceFirst(OcamlCompilables.OCAML_RE_REGEX, OcamlCompilables.OCAML_CMO) .replaceFirst(OcamlCompilables.OCAML_MLI_REGEX, OcamlCompilables.OCAML_CMI) .replaceFirst(OcamlCompilables.OCAML_REI_REGEX, OcamlCompilables.OCAML_CMI); Path outputPath = ocamlContext.getCompileBytecodeOutputDir().resolve(outputFileName); if (!outputFileName.endsWith(OcamlCompilables.OCAML_CMI)) { linkerInputs.add(outputPath); } ImmutableList<Arg> compileFlags = getCompileFlags(/* isBytecode */ true, /* excludeDeps */ false); Step compileBytecodeStep = new OcamlMLCompileStep( workingDirectory, getResolver(), new OcamlMLCompileStep.Args( cCompilerEnvironment, cCompiler, ocamlContext.getOcamlBytecodeCompiler().get(), ocamlContext.getOcamlInteropIncludesDir(), outputPath, inputOutput, compileFlags)); StepExecutionResult compileExecutionResult = compileBytecodeStep.execute(context); if (!compileExecutionResult.isSuccess()) { return compileExecutionResult; } } return StepExecutionResults.SUCCESS; } private StepExecutionResult generateSources(ExecutionContext context, Path workingDirectory) throws IOException, InterruptedException { for (Step step : MakeCleanDirectoryStep.of( BuildCellRelativePath.fromCellRelativePath( context.getBuildCellRootPath(), filesystem, ocamlContext.getGeneratedSourceDir()))) { StepExecutionResult mkDirExecutionResult = step.execute(context); if (!mkDirExecutionResult.isSuccess()) { return mkDirExecutionResult; } } for (SourcePath yaccSource : ocamlContext.getYaccInput()) { SourcePath output = ocamlContext.getYaccOutput(ImmutableSet.of(yaccSource)).get(0); OcamlYaccStep yaccStep = new OcamlYaccStep( workingDirectory, getResolver(), new OcamlYaccStep.Args( ocamlContext.getYaccCompiler().get(), getResolver().getAbsolutePath(output), getResolver().getAbsolutePath(yaccSource))); StepExecutionResult yaccExecutionResult = yaccStep.execute(context); if (!yaccExecutionResult.isSuccess()) { return yaccExecutionResult; } } for (SourcePath lexSource : ocamlContext.getLexInput()) { SourcePath output = ocamlContext.getLexOutput(ImmutableSet.of(lexSource)).get(0); OcamlLexStep lexStep = new OcamlLexStep( workingDirectory, getResolver(), new OcamlLexStep.Args( ocamlContext.getLexCompiler().get(), getResolver().getAbsolutePath(output), getResolver().getAbsolutePath(lexSource))); StepExecutionResult lexExecutionResult = lexStep.execute(context); if (!lexExecutionResult.isSuccess()) { return lexExecutionResult; } } return StepExecutionResults.SUCCESS; } private ImmutableList<Path> sortDependency( String depOutput, ImmutableSet<Path> mlInput) { // NOPMD doesn't understand method reference OcamlDependencyGraphGenerator graphGenerator = new OcamlDependencyGraphGenerator(); return FluentIterable.from(graphGenerator.generate(depOutput)) .transform(Paths::get) // The output of generate needs to be filtered as .cmo dependencies // are generated as both .ml and .re files. .filter(mlInput::contains) .toList(); } private SourcePathResolver getResolver() { return buildContext.getSourcePathResolver(); } }
apache-2.0
informatics-architecture/OTF-Query-Services--OLD
query-integration-tests/src/test/java/org/ihtsdo/otf/query/integration/tests/IsChildOfTest.java
1785
package org.ihtsdo.otf.query.integration.tests; /* * Copyright 2013 International Health Terminology Standards Development Organisation. * * 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 java.io.IOException; import org.ihtsdo.otf.tcc.api.coordinate.StandardViewCoordinates; import org.ihtsdo.otf.tcc.api.metadata.binding.Snomed; import org.ihtsdo.otf.tcc.api.nid.NativeIdSetBI; import org.ihtsdo.otf.query.implementation.Clause; import org.ihtsdo.otf.query.implementation.Query; import org.ihtsdo.otf.tcc.api.store.Ts; /** * Creates a test for the * <code>ConceptIsChildOf</code> clause. * * @author dylangrald * */ public class IsChildOfTest extends QueryClauseTest { public IsChildOfTest() throws IOException { this.q = new Query(StandardViewCoordinates.getSnomedInferredLatest()) { @Override protected NativeIdSetBI For() throws IOException { return Ts.get().getAllConceptNids(); } @Override public void Let() throws IOException { let("Physical force", Snomed.PHYSICAL_FORCE); } @Override public Clause Where() { return And(ConceptIsChildOf("Physical force")); } }; } }
apache-2.0
aol/cyclops
cyclops-reactor-integration/src/test/java/cyclops/streams/syncflux/SyncJDKStreamTest.java
6807
package cyclops.streams.syncflux; import cyclops.reactive.FluxReactiveSeq; import cyclops.reactive.ReactiveSeq; import org.junit.Test; import reactor.core.publisher.Flux; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.stream.Collectors; import static java.util.Arrays.asList; import static org.hamcrest.Matchers.equalTo; import static org.hamcrest.Matchers.hasItem; import static org.junit.Assert.assertThat; public class SyncJDKStreamTest { protected <U> ReactiveSeq<U> of(U... array){ return FluxReactiveSeq.reactiveSeq(Flux.just(array)); } @Test public void testAnyMatch(){ assertThat(of(1,2,3,4,5).anyMatch(it-> it.equals(3)),equalTo(true)); } @Test public void testAllMatch(){ assertThat(of(1,2,3,4,5).allMatch(it-> it>0 && it <6),equalTo(true)); } @Test public void testNoneMatch(){ assertThat(of(1,2,3,4,5).noneMatch(it-> it==5000),equalTo(true)); } @Test public void testAnyMatchFalse(){ assertThat(of(1,2,3,4,5).anyMatch(it-> it.equals(8)),equalTo(false)); } @Test public void testAllMatchFalse(){ assertThat(of(1,2,3,4,5).allMatch(it-> it<0 && it >6),equalTo(false)); } @Test public void testFlatMap(){ System.out.println("Result = " + of( asList("1","10"), asList("2"),asList("3"),asList("4")) .flatMapStream( list -> list.stream() ).collect(Collectors.toList())); assertThat(of( asList("1","10"), asList("2"),asList("3"),asList("4")).flatMapStream( list -> list.stream() ).collect(Collectors.toList() ),hasItem("10")); } @Test public void testFlatMap2(){ System.out.println(of( asList("1","10"), asList("2"),asList("3"),asList("4")).flatMap( list -> list.stream() ).collect(Collectors.toList())); assertThat(of( asList("1","10"), asList("2"),asList("3"),asList("4")).flatMap( list -> list.stream() ).collect(Collectors.toList() ),hasItem("10")); } @Test public void testMapReduce(){ assertThat(of(1,2,3,4,5).map(it -> it*100).reduce( (acc,next) -> acc+next).get(),equalTo(1500)); } @Test public void testMapReduceSeed(){ assertThat(of(1,2,3,4,5).map(it -> it*100).reduce( 50,(acc,next) -> acc+next),equalTo(1550)); } @Test public void testMapReduceCombiner(){ assertThat(of(1,2,3,4,5).map(it -> it*100).reduce( 0, (acc, next) -> acc+next, Integer::sum),equalTo(1500)); } @Test public void testFindFirst(){ assertThat(Arrays.asList(1,2,3),hasItem(of(1,2,3,4,5).filter(it -> it <3).findFirst().get())); } @Test public void testFindAny(){ assertThat(Arrays.asList(1,2,3),hasItem(of(1,2,3,4,5).filter(it -> it <3).findAny().get())); } @Test public void testDistinct(){ assertThat(of(1,1,1,2,1).distinct().collect(Collectors.toList()).size(),equalTo(2)); assertThat(of(1,1,1,2,1).distinct().collect(Collectors.toList()),hasItem(1)); assertThat(of(1,1,1,2,1).distinct().collect(Collectors.toList()),hasItem(2)); } @Test public void testLimit(){ assertThat(of(1,2,3,4,5).limit(2).collect(Collectors.toList()).size(),equalTo(2)); } @Test public void testSkip(){ assertThat(of(1,2,3,4,5).skip(2).collect(Collectors.toList()).size(),equalTo(3)); } @Test public void testTake(){ assertThat(of(1,2,3,4,5).take(2).collect(Collectors.toList()).size(),equalTo(2)); } @Test public void testDrop(){ assertThat(of(1,2,3,4,5).drop(2).collect(Collectors.toList()).size(),equalTo(3)); } @Test public void testMax(){ assertThat(of(1,2,3,4,5).maximum((t1, t2) -> t1-t2).orElse(-1),equalTo(5)); } @Test public void testMin(){ assertThat(of(1,2,3,4,5).minimum((t1, t2) -> t1-t2).orElse(-1),equalTo(1)); } @Test public void testMapToInt(){ assertThat(of("1","2","3","4").mapToInt(it -> Integer.valueOf(it)).max().getAsInt(),equalTo(4)); } @Test public void mapToLong() { assertThat(of("1","2","3","4").mapToLong(it -> Long.valueOf(it)).max().getAsLong(),equalTo(4l)); } @Test public void mapToDouble() { assertThat(of("1","2","3","4").mapToDouble(it -> Double.valueOf(it)).max().getAsDouble(),equalTo(4d)); } @Test public void flatMapToInt() { assertThat(of( asList("1","10"), asList("2"),asList("3"),asList("4")) .flatMapToInt(list ->list.stream() .mapToInt(Integer::valueOf)).max().getAsInt(),equalTo(10)); } @Test public void flatMapToLong() { assertThat(of( asList("1","10"), asList("2"),asList("3"),asList("4")) .flatMapToLong(list ->list.stream().mapToLong(Long::valueOf)).max().getAsLong(),equalTo(10l)); } @Test public void flatMapToDouble(){ assertThat(of( asList("1","10"), asList("2"),asList("3"),asList("4")) .flatMapToDouble(list ->list.stream() .mapToDouble(Double::valueOf)) .max().getAsDouble(),equalTo(10d)); } @Test public void sorted() { assertThat(of(1,5,3,4,2).sorted().collect(Collectors.toList()),equalTo(Arrays.asList(1,2,3,4,5))); } @Test public void sortedComparator() { assertThat(of(1,5,3,4,2).sorted((t1,t2) -> t2-t1).collect(Collectors.toList()),equalTo(Arrays.asList(5,4,3,2,1))); } @Test public void forEach() throws InterruptedException { List<Integer> list = new ArrayList<>(); of(1,5,3,4,2).forEach(it-> list.add(it)); Thread.sleep(500l); assertThat(list,hasItem(1)); assertThat(list,hasItem(2)); assertThat(list,hasItem(3)); assertThat(list,hasItem(4)); assertThat(list,hasItem(5)); } @Test public void forEachOrderedx() { List<Integer> list = new ArrayList<>(); of(1,5,3,4,2).forEachOrdered(it-> list.add(it)); assertThat(list,hasItem(1)); assertThat(list,hasItem(2)); assertThat(list,hasItem(3)); assertThat(list,hasItem(4)); assertThat(list,hasItem(5)); } @Test public void testToArray() { assertThat( Arrays.asList(1,2,3,4,5),hasItem(of(1,5,3,4,2).toArray()[0])); } @Test public void testToArrayGenerator() { assertThat( Arrays.asList(1,2,3,4,5),hasItem(of(1,5,3,4,2).toArray(it->new Integer[it])[0])); } @Test public void testCount(){ assertThat(of(1,5,3,4,2).count(),equalTo(5L)); } @Test public void collectSBB(){ List<Integer> list = of(1,2,3,4,5).collect(ArrayList::new, ArrayList::add, ArrayList::addAll); assertThat(list.size(),equalTo(5)); } @Test public void collect(){ assertThat(of(1,2,3,4,5).collect(Collectors.toList()).size(),equalTo(5)); assertThat(of(1,1,1,2).collect(Collectors.toSet()).size(),equalTo(2)); } @Test public void testFilter(){ assertThat(of(1,1,1,2).filter(it -> it==1).collect(Collectors.toList()).size(),equalTo(3)); } @Test public void testMap(){ assertThat(of(1).map(it->it+100).collect(Collectors.toList()).get(0),equalTo(101)); } Object val; @Test public void testPeek(){ val = null; of(1).map(it->it+100).peek(it -> val=it).collect(Collectors.toList()); assertThat(val,equalTo(101)); } }
apache-2.0
networknt/undertow-server
health/src/test/java/com/networknt/health/HealthGetHandlerTest.java
4452
/* * Copyright (c) 2016 Network New Technologies Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.networknt.health; import com.networknt.client.Http2Client; import com.networknt.config.Config; import com.networknt.config.JsonMapper; import com.networknt.exception.ClientException; import io.undertow.Handlers; import io.undertow.Undertow; import io.undertow.client.ClientConnection; import io.undertow.client.ClientRequest; import io.undertow.client.ClientResponse; import io.undertow.server.HttpHandler; import io.undertow.server.RoutingHandler; import io.undertow.util.Headers; import io.undertow.util.Methods; import org.junit.AfterClass; import org.junit.Assert; import org.junit.BeforeClass; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.xnio.IoUtils; import org.xnio.OptionMap; import java.net.URI; import java.util.concurrent.CountDownLatch; import java.util.concurrent.atomic.AtomicReference; /** * Created by steve on 01/09/16. */ public class HealthGetHandlerTest { static final Logger logger = LoggerFactory.getLogger(HealthGetHandlerTest.class); static Undertow server = null; static final HealthConfig config = (HealthConfig) Config.getInstance().getJsonObjectConfig(HealthGetHandler.CONFIG_NAME, HealthConfig.class); @BeforeClass public static void setUp() { if(server == null) { logger.info("starting server"); HttpHandler handler = getTestHandler(); server = Undertow.builder() .addHttpListener(8080, "localhost") .setHandler(handler) .build(); server.start(); } } @AfterClass public static void tearDown() throws Exception { if(server != null) { try { Thread.sleep(100); } catch (InterruptedException ignored) { } server.stop(); logger.info("The server is stopped."); } } static RoutingHandler getTestHandler() { return Handlers.routing().add(Methods.GET, "/server/health", new HealthGetHandler()); } @Test public void testHealth() throws Exception { testHealth(false); } @Test public void testHealthJson() throws Exception { testHealth(true); } public void testHealth(boolean useJson) throws Exception { config.setUseJson(useJson); final Http2Client client = Http2Client.getInstance(); final CountDownLatch latch = new CountDownLatch(1); final ClientConnection connection; try { connection = client.connect(new URI("http://localhost:8080"), Http2Client.WORKER, Http2Client.BUFFER_POOL, OptionMap.EMPTY).get(); } catch (Exception e) { throw new ClientException(e); } final AtomicReference<ClientResponse> reference = new AtomicReference<>(); try { ClientRequest request = new ClientRequest().setPath("/server/health").setMethod(Methods.GET); request.getRequestHeaders().put(Headers.HOST, "localhost"); connection.sendRequest(request, client.createClientCallback(reference, latch)); latch.await(); } catch (Exception e) { logger.error("Exception: ", e); throw new ClientException(e); } finally { IoUtils.safeClose(connection); } int statusCode = reference.get().getResponseCode(); String body = reference.get().getAttachment(Http2Client.RESPONSE_BODY); Assert.assertEquals(200, statusCode); Assert.assertEquals(useJson ? HealthGetHandler.HEALTH_RESULT_OK_JSON : HealthGetHandler.HEALTH_RESULT_OK, body); if (useJson) { Assert.assertEquals("application/json", reference.get().getResponseHeaders().get(Headers.CONTENT_TYPE).getFirst()); } } }
apache-2.0
samuto/Terasology
engine/src/main/java/org/terasology/logic/nameTags/NameTagClientSystem.java
4839
/* * Copyright 2014 MovingBlocks * * 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.terasology.logic.nameTags; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.terasology.entitySystem.entity.EntityBuilder; import org.terasology.entitySystem.entity.EntityManager; import org.terasology.entitySystem.entity.EntityRef; import org.terasology.entitySystem.entity.lifecycleEvents.BeforeDeactivateComponent; import org.terasology.entitySystem.entity.lifecycleEvents.OnActivatedComponent; import org.terasology.entitySystem.entity.lifecycleEvents.OnChangedComponent; import org.terasology.entitySystem.event.ReceiveEvent; import org.terasology.entitySystem.systems.BaseComponentSystem; import org.terasology.entitySystem.systems.RegisterMode; import org.terasology.entitySystem.systems.RegisterSystem; import org.terasology.logic.location.Location; import org.terasology.logic.location.LocationComponent; import org.terasology.math.geom.Quat4f; import org.terasology.math.geom.Vector3f; import org.terasology.registry.In; import org.terasology.rendering.logic.FloatingTextComponent; import java.util.HashMap; import java.util.Map; @RegisterSystem(RegisterMode.CLIENT) public class NameTagClientSystem extends BaseComponentSystem { private static final Logger logger = LoggerFactory.getLogger(NameTagClientSystem.class); private Map<EntityRef, EntityRef> nameTagEntityToFloatingTextMap = new HashMap<>(); @In private EntityManager entityManager; @ReceiveEvent(components = {NameTagComponent.class, LocationComponent.class}) public void onNameTagOwnerActivated(OnActivatedComponent event, EntityRef entity, NameTagComponent nameTagComponent) { createOrUpdateNameTagFor(entity, nameTagComponent); } @ReceiveEvent(components = {NameTagComponent.class }) public void onDisplayNameChange(OnChangedComponent event, EntityRef entity, NameTagComponent nameTagComponent) { createOrUpdateNameTagFor(entity, nameTagComponent); } private void createOrUpdateNameTagFor(EntityRef entity, NameTagComponent nameTagComponent) { EntityRef nameTag = nameTagEntityToFloatingTextMap.get(entity); Vector3f offset = new Vector3f(0, nameTagComponent.yOffset, 0); if (nameTag != null) { FloatingTextComponent floatingText = nameTag.getComponent(FloatingTextComponent.class); floatingText.text = nameTagComponent.text; floatingText.textColor = nameTagComponent.textColor; nameTag.saveComponent(floatingText); LocationComponent nameTagLoc = nameTag.getComponent(LocationComponent.class); nameTagLoc.setLocalPosition(offset); nameTag.saveComponent(nameTagLoc); } else { EntityBuilder nameTagBuilder = entityManager.newBuilder(); FloatingTextComponent floatingTextComponent = new FloatingTextComponent(); nameTagBuilder.addComponent(floatingTextComponent); LocationComponent locationComponent = new LocationComponent(); nameTagBuilder.addComponent(locationComponent); floatingTextComponent.text = nameTagComponent.text; floatingTextComponent.textColor = nameTagComponent.textColor; nameTagBuilder.setOwner(entity); nameTagBuilder.setPersistent(false); nameTag = nameTagBuilder.build(); nameTagEntityToFloatingTextMap.put(entity, nameTag); Location.attachChild(entity, nameTag, offset, new Quat4f(1, 0, 0, 0)); } } private void destroyNameTagOf(EntityRef entity) { EntityRef nameTag = nameTagEntityToFloatingTextMap.remove(entity); if (nameTag != null) { nameTag.destroy(); } } @ReceiveEvent(components = {NameTagComponent.class }) public void onNameTagOwnerRemoved(BeforeDeactivateComponent event, EntityRef entity) { destroyNameTagOf(entity); } @Override public void shutdown() { /* Explicitly no deletion of name tag entities as some system might not be in the right state anymore. * Since they aren't persistent it does not make any difference anyway. */ nameTagEntityToFloatingTextMap.clear(); } }
apache-2.0
PeterIJia/android_xlight
cloudsdk/src/main/java/io/particle/android/sdk/cloud/models/DeviceStateChange.java
1835
package io.particle.android.sdk.cloud.models; import android.os.Parcel; import android.os.Parcelable; import android.support.annotation.NonNull; import javax.annotation.ParametersAreNonnullByDefault; import io.particle.android.sdk.cloud.ParticleDevice; @ParametersAreNonnullByDefault public class DeviceStateChange implements Parcelable { private final ParticleDevice device; @NonNull private final ParticleDevice.ParticleDeviceState state; public DeviceStateChange(ParticleDevice device, @NonNull ParticleDevice.ParticleDeviceState state) { this.device = device; this.state = state; } @Override public int describeContents() { return 0; } @Override public void writeToParcel(Parcel dest, int flags) { dest.writeParcelable(this.device, flags); dest.writeInt(this.state == ParticleDevice.ParticleDeviceState.UNKNOWN ? -1 : this.state.ordinal()); } protected DeviceStateChange(Parcel in) { this.device = in.readParcelable(ParticleDevice.class.getClassLoader()); int tmpState = in.readInt(); this.state = tmpState == -1 ? ParticleDevice.ParticleDeviceState.UNKNOWN : ParticleDevice.ParticleDeviceState.values()[tmpState]; } public static final Parcelable.Creator<DeviceStateChange> CREATOR = new Parcelable.Creator<DeviceStateChange>() { @Override public DeviceStateChange createFromParcel(Parcel source) { return new DeviceStateChange(source); } @Override public DeviceStateChange[] newArray(int size) { return new DeviceStateChange[size]; } }; public ParticleDevice getDevice() { return device; } @NonNull public ParticleDevice.ParticleDeviceState getState() { return state; } }
apache-2.0
todotobe1/SensorStorm
ExternalStormConfiguration/src/nl/tno/storm/configuration/api/StormConfigurationFactory.java
1306
package nl.tno.storm.configuration.api; import java.io.Closeable; import java.util.Map; public interface StormConfigurationFactory extends Closeable { /** * Get the StormConfiguration for a specific topology based on the ToplogyId * and the Zookeeper ConnectionString * * @param topologyId * toplogyId as used in the configuration * @param connectionString * Zookeeper connection string * @return StormConfiguration instance for this topology * @throws StormConfigurationException * Probably something is wrong with Zookeeper */ public ExternalStormConfiguration getStormConfiguration(String topologyId, String connectionString) throws StormConfigurationException; /** * Get the StormConfiguration for a specific topology based on the Storm * configuration map * * This is a convenience method with gets the necessary information from the * Storm configuration map. * * @param Map * Storm configuration map * @return StormConfiguration instance for this topology * @throws StormConfigurationException * Probably something is wrong with Zookeeper */ public ExternalStormConfiguration getStormConfiguration(@SuppressWarnings("rawtypes") Map config) throws StormConfigurationException; }
apache-2.0
MindorksOpenSource/android-mvp-architecture
app/src/main/java/com/mindorks/framework/mvp/ui/splash/SplashActivity.java
2382
/* * Copyright (C) 2017 MINDORKS NEXTGEN PRIVATE LIMITED * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * https://mindorks.com/license/apache-v2 * * 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.mindorks.framework.mvp.ui.splash; import android.content.Context; import android.content.Intent; import android.os.Bundle; import com.mindorks.framework.mvp.R; import com.mindorks.framework.mvp.ui.base.BaseActivity; import com.mindorks.framework.mvp.ui.login.LoginActivity; import com.mindorks.framework.mvp.ui.main.MainActivity; import javax.inject.Inject; import butterknife.ButterKnife; /** * Created by janisharali on 27/01/17. */ public class SplashActivity extends BaseActivity implements SplashMvpView { @Inject SplashMvpPresenter<SplashMvpView> mPresenter; public static Intent getStartIntent(Context context) { Intent intent = new Intent(context, SplashActivity.class); return intent; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_splash); getActivityComponent().inject(this); setUnBinder(ButterKnife.bind(this)); mPresenter.onAttach(SplashActivity.this); } /** * Making the screen wait so that the branding can be shown */ @Override public void openLoginActivity() { Intent intent = LoginActivity.getStartIntent(SplashActivity.this); startActivity(intent); finish(); } @Override public void openMainActivity() { Intent intent = MainActivity.getStartIntent(SplashActivity.this); startActivity(intent); finish(); } @Override public void startSyncService() { // SyncService.start(this); } @Override protected void onDestroy() { mPresenter.onDetach(); super.onDestroy(); } @Override protected void setUp() { } }
apache-2.0
deleidos/digitaledge-platform
webapp-repository/src/main/java/com/deleidos/rtws/webapp/repository/rest/TenantMgmtService.java
13477
/** * Apache License * Version 2.0, January 2004 * http://www.apache.org/licenses/ * * TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION * * 1. Definitions. * * "License" shall mean the terms and conditions for use, reproduction, * and distribution as defined by Sections 1 through 9 of this document. * * "Licensor" shall mean the copyright owner or entity authorized by * the copyright owner that is granting the License. * * "Legal Entity" shall mean the union of the acting entity and all * other entities that control, are controlled by, or are under common * control with that entity. For the purposes of this definition, * "control" means (i) the power, direct or indirect, to cause the * direction or management of such entity, whether by contract or * otherwise, or (ii) ownership of fifty percent (50%) or more of the * outstanding shares, or (iii) beneficial ownership of such entity. * * "You" (or "Your") shall mean an individual or Legal Entity * exercising permissions granted by this License. * * "Source" form shall mean the preferred form for making modifications, * including but not limited to software source code, documentation * source, and configuration files. * * "Object" form shall mean any form resulting from mechanical * transformation or translation of a Source form, including but * not limited to compiled object code, generated documentation, * and conversions to other media types. * * "Work" shall mean the work of authorship, whether in Source or * Object form, made available under the License, as indicated by a * copyright notice that is included in or attached to the work * (an example is provided in the Appendix below). * * "Derivative Works" shall mean any work, whether in Source or Object * form, that is based on (or derived from) the Work and for which the * editorial revisions, annotations, elaborations, or other modifications * represent, as a whole, an original work of authorship. For the purposes * of this License, Derivative Works shall not include works that remain * separable from, or merely link (or bind by name) to the interfaces of, * the Work and Derivative Works thereof. * * "Contribution" shall mean any work of authorship, including * the original version of the Work and any modifications or additions * to that Work or Derivative Works thereof, that is intentionally * submitted to Licensor for inclusion in the Work by the copyright owner * or by an individual or Legal Entity authorized to submit on behalf of * the copyright owner. For the purposes of this definition, "submitted" * means any form of electronic, verbal, or written communication sent * to the Licensor or its representatives, including but not limited to * communication on electronic mailing lists, source code control systems, * and issue tracking systems that are managed by, or on behalf of, the * Licensor for the purpose of discussing and improving the Work, but * excluding communication that is conspicuously marked or otherwise * designated in writing by the copyright owner as "Not a Contribution." * * "Contributor" shall mean Licensor and any individual or Legal Entity * on behalf of whom a Contribution has been received by Licensor and * subsequently incorporated within the Work. * * 2. Grant of Copyright License. Subject to the terms and conditions of * this License, each Contributor hereby grants to You a perpetual, * worldwide, non-exclusive, no-charge, royalty-free, irrevocable * copyright license to reproduce, prepare Derivative Works of, * publicly display, publicly perform, sublicense, and distribute the * Work and such Derivative Works in Source or Object form. * * 3. Grant of Patent License. Subject to the terms and conditions of * this License, each Contributor hereby grants to You a perpetual, * worldwide, non-exclusive, no-charge, royalty-free, irrevocable * (except as stated in this section) patent license to make, have made, * use, offer to sell, sell, import, and otherwise transfer the Work, * where such license applies only to those patent claims licensable * by such Contributor that are necessarily infringed by their * Contribution(s) alone or by combination of their Contribution(s) * with the Work to which such Contribution(s) was submitted. If You * institute patent litigation against any entity (including a * cross-claim or counterclaim in a lawsuit) alleging that the Work * or a Contribution incorporated within the Work constitutes direct * or contributory patent infringement, then any patent licenses * granted to You under this License for that Work shall terminate * as of the date such litigation is filed. * * 4. Redistribution. You may reproduce and distribute copies of the * Work or Derivative Works thereof in any medium, with or without * modifications, and in Source or Object form, provided that You * meet the following conditions: * * (a) You must give any other recipients of the Work or * Derivative Works a copy of this License; and * * (b) You must cause any modified files to carry prominent notices * stating that You changed the files; and * * (c) You must retain, in the Source form of any Derivative Works * that You distribute, all copyright, patent, trademark, and * attribution notices from the Source form of the Work, * excluding those notices that do not pertain to any part of * the Derivative Works; and * * (d) If the Work includes a "NOTICE" text file as part of its * distribution, then any Derivative Works that You distribute must * include a readable copy of the attribution notices contained * within such NOTICE file, excluding those notices that do not * pertain to any part of the Derivative Works, in at least one * of the following places: within a NOTICE text file distributed * as part of the Derivative Works; within the Source form or * documentation, if provided along with the Derivative Works; or, * within a display generated by the Derivative Works, if and * wherever such third-party notices normally appear. The contents * of the NOTICE file are for informational purposes only and * do not modify the License. You may add Your own attribution * notices within Derivative Works that You distribute, alongside * or as an addendum to the NOTICE text from the Work, provided * that such additional attribution notices cannot be construed * as modifying the License. * * You may add Your own copyright statement to Your modifications and * may provide additional or different license terms and conditions * for use, reproduction, or distribution of Your modifications, or * for any such Derivative Works as a whole, provided Your use, * reproduction, and distribution of the Work otherwise complies with * the conditions stated in this License. * * 5. Submission of Contributions. Unless You explicitly state otherwise, * any Contribution intentionally submitted for inclusion in the Work * by You to the Licensor shall be under the terms and conditions of * this License, without any additional terms or conditions. * Notwithstanding the above, nothing herein shall supersede or modify * the terms of any separate license agreement you may have executed * with Licensor regarding such Contributions. * * 6. Trademarks. This License does not grant permission to use the trade * names, trademarks, service marks, or product names of the Licensor, * except as required for reasonable and customary use in describing the * origin of the Work and reproducing the content of the NOTICE file. * * 7. Disclaimer of Warranty. Unless required by applicable law or * agreed to in writing, Licensor provides the Work (and each * Contributor provides its Contributions) on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or * implied, including, without limitation, any warranties or conditions * of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A * PARTICULAR PURPOSE. You are solely responsible for determining the * appropriateness of using or redistributing the Work and assume any * risks associated with Your exercise of permissions under this License. * * 8. Limitation of Liability. In no event and under no legal theory, * whether in tort (including negligence), contract, or otherwise, * unless required by applicable law (such as deliberate and grossly * negligent acts) or agreed to in writing, shall any Contributor be * liable to You for damages, including any direct, indirect, special, * incidental, or consequential damages of any character arising as a * result of this License or out of the use or inability to use the * Work (including but not limited to damages for loss of goodwill, * work stoppage, computer failure or malfunction, or any and all * other commercial damages or losses), even if such Contributor * has been advised of the possibility of such damages. * * 9. Accepting Warranty or Additional Liability. While redistributing * the Work or Derivative Works thereof, You may choose to offer, * and charge a fee for, acceptance of support, warranty, indemnity, * or other liability obligations and/or rights consistent with this * License. However, in accepting such obligations, You may act only * on Your own behalf and on Your sole responsibility, not on behalf * of any other Contributor, and only if You agree to indemnify, * defend, and hold each Contributor harmless for any liability * incurred by, or claims asserted against, such Contributor by reason * of your accepting any such warranty or additional liability. * * END OF TERMS AND CONDITIONS * * APPENDIX: How to apply the Apache License to your work. * * To apply the Apache License to your work, attach the following * boilerplate notice, with the fields enclosed by brackets "{}" * replaced with your own identifying information. (Don't include * the brackets!) The text should be enclosed in the appropriate * comment syntax for the file format. We also recommend that a * file or class name and description of purpose be included on the * same "printed page" as the copyright notice for easier * identification within third-party archives. * * Copyright {yyyy} {name of copyright owner} * * 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.deleidos.rtws.webapp.repository.rest; import javax.ws.rs.Consumes; import javax.ws.rs.DELETE; import javax.ws.rs.FormParam; import javax.ws.rs.GET; import javax.ws.rs.POST; import javax.ws.rs.Path; import javax.ws.rs.PathParam; import javax.ws.rs.Produces; import javax.ws.rs.QueryParam; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; /** * Interface defining supported HTTP operations for the tenant management service. */ public interface TenantMgmtService { @Path("/create/tenant") @POST @Consumes(MediaType.APPLICATION_FORM_URLENCODED) public Response createTenant( @FormParam("userId") String userId, @FormParam("password") String password, @FormParam("tenantId") String tenantId, @FormParam("tenantPassword") String tenantPassword); @Path("/delete/tenant/{tenantId}") @DELETE public Response deleteTenant( @QueryParam("userId") String userId, @QueryParam("password") String password, @PathParam("tenantId") String tenantId); @Path("/change/password") @POST @Consumes(MediaType.APPLICATION_FORM_URLENCODED) public Response changePassword( @FormParam("userId") String userId, @FormParam("password") String password, @FormParam("tenantId") String tenantId, @FormParam("tenantPassword") String tenantPassword); @Path("/list/tenants") @GET @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON}) public Response listTenants( @QueryParam("userId") String userId, @QueryParam("password") String password); }
apache-2.0
emrahkocaman/hazelcast-cloudfoundry
service-broker/src/main/java/org/hazelcast/cloudfoundry/servicebroker/Application.java
1067
/* * Copyright (c) 2008-2016, Hazelcast, Inc. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.hazelcast.cloudfoundry.servicebroker; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.context.annotation.ComponentScan; /* * Spring boot starter */ @ComponentScan @EnableAutoConfiguration public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } }
apache-2.0
CIRDLES/ET_Redux
src/main/java/org/earthtime/ratioDataModels/initialPbModelsET/commonLeadLossCorrectionSchemes/CommonLeadLossCorrectionSchemeNONE.java
2334
/* * CommonLeadLossCorrectionSchemeNONE.java * * * Copyright 2006-2018 James F. Bowring, CIRDLES.org, and Earth-Time.org * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.earthtime.ratioDataModels.initialPbModelsET.commonLeadLossCorrectionSchemes; import java.math.BigDecimal; import java.util.SortedMap; import org.earthtime.UPb_Redux.valueModels.ValueModel; /** * * @author James F. Bowring */ public class CommonLeadLossCorrectionSchemeNONE extends AbstractCommonLeadLossCorrectionScheme { // Class variables private static final long serialVersionUID = -898481500928425738L; private static CommonLeadLossCorrectionSchemeNONE instance = null; private CommonLeadLossCorrectionSchemeNONE() { super("NONE", false); } /** * * @return */ public static CommonLeadLossCorrectionSchemeNONE getInstance() { if (instance == null) { instance = new CommonLeadLossCorrectionSchemeNONE(); } return instance; } /** * * @param parameters the value of parameterz * @param staceyKramerCorrectionParameters the value of staceyKramerCorrectionParameters * @param useStaceyKramer the value of useStaceyKramer * @param r238_235sVM the value of parameters * @param lambda235VM the value of r238_235s * @param lambda238VM the value of lambda235 * @return */ @Override public ValueModel calculatePbCorrectedAge(SortedMap<String, ValueModel> parameters, SortedMap<String,BigDecimal> staceyKramerCorrectionParameters, boolean useStaceyKramer, ValueModel r238_235sVM, ValueModel lambda235VM, ValueModel lambda238VM) { throw new UnsupportedOperationException("Not supported yet."); //To change body of generated methods, choose Tools | Templates. } }
apache-2.0
ilya-klyuchnikov/buck
src/com/facebook/buck/util/MoreSuppliers.java
3182
/* * Copyright 2016-present Facebook, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. You may obtain * a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations * under the License. */ package com.facebook.buck.util; import com.google.common.base.Preconditions; import java.lang.ref.WeakReference; import java.util.function.Supplier; import javax.annotation.Nullable; public final class MoreSuppliers { private MoreSuppliers() {} /** * Returns a supplier which caches the instance retrieved during the first call to {@code get()} * and returns that value on subsequent calls to {@code get()}. * * <p>Unlike Guava's {@link * com.google.common.base.Suppliers#memoize(com.google.common.base.Supplier)}, this version * removes the reference to the underlying Supplier once the value is computed. This frees up * memory used in lambda captures, at the cost of causing the supplier to be not Serializable. */ public static <T> Supplier<T> memoize(Supplier<T> delegate) { return (delegate instanceof MemoizingSupplier) ? delegate : new MemoizingSupplier<T>(delegate); } private static class MemoizingSupplier<T> implements Supplier<T> { // This field doubles as a marker of whether the value has been initialized. Once the value is // initialized, this field becomes null. @Nullable private volatile Supplier<T> delegate; @Nullable private T value; public MemoizingSupplier(Supplier<T> delegate) { this.delegate = delegate; } @Override public T get() { if (delegate != null) { synchronized (this) { if (delegate != null) { T t = Preconditions.checkNotNull(delegate.get()); value = t; delegate = null; return t; } } } return Preconditions.checkNotNull(value); } } public static <T> Supplier<T> weakMemoize(Supplier<T> delegate) { return (delegate instanceof WeakMemoizingSupplier) ? delegate : new WeakMemoizingSupplier<>(delegate); } private static class WeakMemoizingSupplier<T> implements Supplier<T> { private final Supplier<T> delegate; private WeakReference<T> valueRef; public WeakMemoizingSupplier(Supplier<T> delegate) { this.delegate = delegate; this.valueRef = new WeakReference<>(null); } @Override public T get() { @Nullable T value = valueRef.get(); if (value == null) { synchronized (this) { // Check again in case someone else has populated the cache. value = valueRef.get(); if (value == null) { value = delegate.get(); valueRef = new WeakReference<>(value); } } } return value; } } }
apache-2.0
trivium-io/trivium-core
src/io/trivium/dep/com/google/common/cache/RemovalNotification.java
3413
/* * Copyright (C) 2011 The Guava 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 io.trivium.dep.com.google.common.cache; import static io.trivium.dep.com.google.common.base.Preconditions.checkNotNull; import io.trivium.dep.com.google.common.annotations.GwtCompatible; import io.trivium.dep.com.google.common.base.Objects; import java.util.Map.Entry; import javax.annotation.Nullable; /** * A notification of the removal of a single entry. The key and/or value may be null if they were * already garbage collected. * * <p>Like other {@code Map.Entry} instances associated with {@code CacheBuilder}, this class holds * strong references to the key and value, regardless of the type of references the cache may be * using. * * @author Charles Fry * @since 10.0 */ @GwtCompatible public final class RemovalNotification<K, V> implements Entry<K, V> { @Nullable private final K key; @Nullable private final V value; private final RemovalCause cause; /** * Creates a new {@code RemovalNotification} for the given {@code key}/{@code value} pair, with * the given {@code cause} for the removal. The {@code key} and/or {@code value} may be * {@code null} if they were already garbage collected. * * @since 19.0 */ public static <K, V> RemovalNotification<K, V> create( @Nullable K key, @Nullable V value, RemovalCause cause) { return new RemovalNotification(key, value, cause); } private RemovalNotification(@Nullable K key, @Nullable V value, RemovalCause cause) { this.key = key; this.value = value; this.cause = checkNotNull(cause); } /** * Returns the cause for which the entry was removed. */ public RemovalCause getCause() { return cause; } /** * Returns {@code true} if there was an automatic removal due to eviction (the cause is neither * {@link RemovalCause#EXPLICIT} nor {@link RemovalCause#REPLACED}). */ public boolean wasEvicted() { return cause.wasEvicted(); } @Nullable @Override public K getKey() { return key; } @Nullable @Override public V getValue() { return value; } @Override public final V setValue(V value) { throw new UnsupportedOperationException(); } @Override public boolean equals(@Nullable Object object) { if (object instanceof Entry) { Entry<?, ?> that = (Entry<?, ?>) object; return Objects.equal(this.getKey(), that.getKey()) && Objects.equal(this.getValue(), that.getValue()); } return false; } @Override public int hashCode() { K k = getKey(); V v = getValue(); return ((k == null) ? 0 : k.hashCode()) ^ ((v == null) ? 0 : v.hashCode()); } /** * Returns a string representation of the form <code>{key}={value}</code>. */ @Override public String toString() { return getKey() + "=" + getValue(); } private static final long serialVersionUID = 0; }
apache-2.0
philliprower/cas
support/cas-server-support-saml-idp-metadata-couchdb/src/main/java/org/apereo/cas/support/saml/idp/metadata/CouchDbSamlIdPMetadataGenerator.java
2619
package org.apereo.cas.support.saml.idp.metadata; import org.apereo.cas.couchdb.saml.CouchDbSamlIdPMetadataDocument; import org.apereo.cas.couchdb.saml.SamlIdPMetadataCouchDbRepository; import org.apereo.cas.support.saml.idp.metadata.generator.BaseSamlIdPMetadataGenerator; import org.apereo.cas.support.saml.idp.metadata.generator.SamlIdPMetadataGeneratorConfigurationContext; import org.apereo.cas.support.saml.services.idp.metadata.SamlIdPMetadataDocument; import lombok.SneakyThrows; import lombok.val; import org.apache.commons.lang3.tuple.Pair; /** * This is {@link CouchDbSamlIdPMetadataGenerator}. * * @author Timur Duehr * @since 6.0.0 */ public class CouchDbSamlIdPMetadataGenerator extends BaseSamlIdPMetadataGenerator { private final SamlIdPMetadataCouchDbRepository couchDb; public CouchDbSamlIdPMetadataGenerator(final SamlIdPMetadataGeneratorConfigurationContext samlIdPMetadataGeneratorConfigurationContext, final SamlIdPMetadataCouchDbRepository couchDb) { super(samlIdPMetadataGeneratorConfigurationContext); this.couchDb = couchDb; } @Override @SneakyThrows public Pair<String, String> buildSelfSignedEncryptionCert() { val results = generateCertificateAndKey(); val doc = getSamlIdPMetadataDocument(); doc.setEncryptionCertificate(results.getKey()); doc.setEncryptionKey(results.getValue()); saveSamlIdPMetadataDocument(doc); return results; } @Override @SneakyThrows public Pair<String, String> buildSelfSignedSigningCert() { val results = generateCertificateAndKey(); val doc = getSamlIdPMetadataDocument(); doc.setSigningCertificate(results.getKey()); doc.setSigningKey(results.getValue()); saveSamlIdPMetadataDocument(doc); return results; } @Override protected String writeMetadata(final String metadata) { val doc = getSamlIdPMetadataDocument(); doc.setMetadata(metadata); saveSamlIdPMetadataDocument(doc); return metadata; } private void saveSamlIdPMetadataDocument(final SamlIdPMetadataDocument doc) { val couchDoc = couchDb.getOne(); if (couchDoc == null) { couchDb.add(new CouchDbSamlIdPMetadataDocument(doc)); } else { couchDb.update(couchDoc.merge(doc)); } } private CouchDbSamlIdPMetadataDocument getSamlIdPMetadataDocument() { val metadata = couchDb.getOne(); if (metadata == null) { return new CouchDbSamlIdPMetadataDocument(); } return metadata; } }
apache-2.0
apache/tomcat
java/org/apache/tomcat/util/http/parser/Host.java
4293
/* * 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.tomcat.util.http.parser; import java.io.IOException; import java.io.Reader; import java.io.StringReader; import org.apache.tomcat.util.buf.ByteChunk; import org.apache.tomcat.util.buf.MessageBytes; public class Host { private Host() { // Utility class. Hide default constructor. } /** * Parse the given input as an HTTP Host header value. * * @param mb The host header value * * @return The position of ':' that separates the host from the port or -1 * if it is not present * * @throws IllegalArgumentException If the host header value is not * specification compliant */ public static int parse(MessageBytes mb) { return parse(new MessageBytesReader(mb)); } /** * Parse the given input as an HTTP Host header value. * * @param string The host header value * * @return The position of ':' that separates the host from the port or -1 * if it is not present * * @throws IllegalArgumentException If the host header value is not * specification compliant */ public static int parse(String string) { return parse(new StringReader(string)); } private static int parse(Reader reader) { try { reader.mark(1); int first = reader.read(); reader.reset(); if (HttpParser.isAlpha(first)) { return HttpParser.readHostDomainName(reader); } else if (HttpParser.isNumeric(first)) { return HttpParser.readHostIPv4(reader, false); } else if ('[' == first) { return HttpParser.readHostIPv6(reader); } else { // Invalid throw new IllegalArgumentException(); } } catch (IOException ioe) { // Should never happen throw new IllegalArgumentException(ioe); } } private static class MessageBytesReader extends Reader { private final byte[] bytes; private final int end; private int pos; private int mark; public MessageBytesReader(MessageBytes mb) { ByteChunk bc = mb.getByteChunk(); bytes = bc.getBytes(); pos = bc.getOffset(); end = bc.getEnd(); } @Override public int read(char[] cbuf, int off, int len) throws IOException { for (int i = off; i < off + len; i++) { // Want output in range 0 to 255, not -128 to 127 cbuf[i] = (char) (bytes[pos++] & 0xFF); } return len; } @Override public void close() throws IOException { // NO-OP } // Over-ridden methods to improve performance @Override public int read() throws IOException { if (pos < end) { // Want output in range 0 to 255, not -128 to 127 return bytes[pos++] & 0xFF; } else { return -1; } } // Methods to support mark/reset @Override public boolean markSupported() { return true; } @Override public void mark(int readAheadLimit) throws IOException { mark = pos; } @Override public void reset() throws IOException { pos = mark; } } }
apache-2.0
spring-io/initializr
initializr-generator/src/test/java/io/spring/initializr/generator/buildsystem/DependencyContainerTests.java
2553
/* * Copyright 2012-2019 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 * * https://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 io.spring.initializr.generator.buildsystem; import io.spring.initializr.generator.version.VersionReference; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; /** * Tests for {@link DependencyContainer}. * * @author Stephane Nicoll */ class DependencyContainerTests { @Test void addDependency() { DependencyContainer container = createTestContainer(); container.add("web", "org.springframework.boot", "spring-boot-starter-web", DependencyScope.COMPILE); assertThat(container.ids()).containsOnly("web"); assertThat(container.items()).hasSize(1); assertThat(container.isEmpty()).isFalse(); assertThat(container.has("web")).isTrue(); Dependency web = container.get("web"); assertThat(web).isNotNull(); assertThat(web.getGroupId()).isEqualTo("org.springframework.boot"); assertThat(web.getArtifactId()).isEqualTo("spring-boot-starter-web"); assertThat(web.getVersion()).isNull(); assertThat(web.getScope()).isEqualTo(DependencyScope.COMPILE); } @Test void addDependencyWithVersion() { DependencyContainer container = createTestContainer(); container.add("custom", Dependency.withCoordinates("com.example", "acme") .version(VersionReference.ofValue("1.0.0")).scope(DependencyScope.COMPILE)); assertThat(container.ids()).containsOnly("custom"); assertThat(container.items()).hasSize(1); assertThat(container.isEmpty()).isFalse(); assertThat(container.has("custom")).isTrue(); Dependency custom = container.get("custom"); assertThat(custom).isNotNull(); assertThat(custom.getGroupId()).isEqualTo("com.example"); assertThat(custom.getArtifactId()).isEqualTo("acme"); assertThat(custom.getVersion()).isEqualTo(VersionReference.ofValue("1.0.0")); assertThat(custom.getScope()).isEqualTo(DependencyScope.COMPILE); } private DependencyContainer createTestContainer() { return new DependencyContainer((id) -> null); } }
apache-2.0
akirakw/asakusafw
sandbox-project/asakusa-directio-dmdl-ext/src/main/java/com/asakusafw/dmdl/directio/tsv/driver/package-info.java
707
/** * Copyright 2011-2019 Asakusa Framework Team. * * 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. */ /** * Special TSV support for Direct I/O. */ package com.asakusafw.dmdl.directio.tsv.driver;
apache-2.0
wendal/alipay-sdk
src/main/java/com/alipay/api/request/AlipayUserContractGetRequest.java
2975
package com.alipay.api.request; import java.util.Map; import com.alipay.api.AlipayRequest; import com.alipay.api.internal.util.AlipayHashMap; import com.alipay.api.response.AlipayUserContractGetResponse; import com.alipay.api.AlipayObject; /** * ALIPAY API: alipay.user.contract.get request * * @author auto create * @since 1.0, 2016-06-06 20:23:18 */ public class AlipayUserContractGetRequest implements AlipayRequest<AlipayUserContractGetResponse> { private AlipayHashMap udfParams; // add user-defined text parameters private String apiVersion="1.0"; /** * 订购者支付宝ID。session与subscriber_user_id二选一即可。 */ private String subscriberUserId; public void setSubscriberUserId(String subscriberUserId) { this.subscriberUserId = subscriberUserId; } public String getSubscriberUserId() { return this.subscriberUserId; } private String terminalType; private String terminalInfo; private String prodCode; private String notifyUrl; private String returnUrl; private boolean needEncrypt=false; private AlipayObject bizModel=null; public String getNotifyUrl() { return this.notifyUrl; } public void setNotifyUrl(String notifyUrl) { this.notifyUrl = notifyUrl; } public String getReturnUrl() { return this.returnUrl; } public void setReturnUrl(String returnUrl) { this.returnUrl = returnUrl; } public String getApiVersion() { return this.apiVersion; } public void setApiVersion(String apiVersion) { this.apiVersion = apiVersion; } public void setTerminalType(String terminalType){ this.terminalType=terminalType; } public String getTerminalType(){ return this.terminalType; } public void setTerminalInfo(String terminalInfo){ this.terminalInfo=terminalInfo; } public String getTerminalInfo(){ return this.terminalInfo; } public void setProdCode(String prodCode) { this.prodCode=prodCode; } public String getProdCode() { return this.prodCode; } public String getApiMethodName() { return "alipay.user.contract.get"; } public Map<String, String> getTextParams() { AlipayHashMap txtParams = new AlipayHashMap(); txtParams.put("subscriber_user_id", this.subscriberUserId); if(udfParams != null) { txtParams.putAll(this.udfParams); } return txtParams; } public void putOtherTextParam(String key, String value) { if(this.udfParams == null) { this.udfParams = new AlipayHashMap(); } this.udfParams.put(key, value); } public Class<AlipayUserContractGetResponse> getResponseClass() { return AlipayUserContractGetResponse.class; } public boolean isNeedEncrypt() { return this.needEncrypt; } public void setNeedEncrypt(boolean needEncrypt) { this.needEncrypt=needEncrypt; } public AlipayObject getBizModel() { return this.bizModel; } public void setBizModel(AlipayObject bizModel) { this.bizModel=bizModel; } }
apache-2.0
rajubairishetti/lens
lens-server/src/main/java/org/apache/lens/server/query/QueryEndNotifier.java
7639
/** * 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.lens.server.query; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.hive.conf.HiveConf; import org.apache.lens.api.query.QueryStatus; import org.apache.lens.server.LensServices; import org.apache.lens.server.api.LensConfConstants; import org.apache.lens.server.api.events.AsyncEventListener; import org.apache.lens.server.api.metrics.MetricsService; import org.apache.lens.server.api.query.QueryContext; import org.apache.lens.server.api.query.QueryEnded; import javax.mail.*; import javax.mail.internet.InternetAddress; import javax.mail.internet.MimeBodyPart; import javax.mail.internet.MimeMessage; import javax.mail.internet.MimeMultipart; import java.util.Date; import java.util.Properties; /** * The Class QueryEndNotifier. */ public class QueryEndNotifier extends AsyncEventListener<QueryEnded> { /** The query service. */ private final QueryExecutionServiceImpl queryService; /** The Constant LOG. */ public static final Log LOG = LogFactory.getLog(QueryEndNotifier.class); /** The Constant EMAIL_ERROR_COUNTER. */ public static final String EMAIL_ERROR_COUNTER = "email-send-errors"; /** The conf. */ private final HiveConf conf; /** The from. */ private final String from; /** The host. */ private final String host; /** The port. */ private final String port; /** The mail smtp timeout. */ private final int mailSmtpTimeout; /** The mail smtp connection timeout. */ private final int mailSmtpConnectionTimeout; /** * Instantiates a new query end notifier. * * @param queryService * the query service * @param hiveConf * the hive conf */ public QueryEndNotifier(QueryExecutionServiceImpl queryService, HiveConf hiveConf) { this.queryService = queryService; this.conf = hiveConf; from = conf.get(LensConfConstants.MAIL_FROM_ADDRESS); host = conf.get(LensConfConstants.MAIL_HOST); port = conf.get(LensConfConstants.MAIL_PORT); mailSmtpTimeout = Integer.parseInt(conf.get(LensConfConstants.MAIL_SMTP_TIMEOUT, LensConfConstants.MAIL_DEFAULT_SMTP_TIMEOUT)); mailSmtpConnectionTimeout = Integer.parseInt(conf.get(LensConfConstants.MAIL_SMTP_CONNECTIONTIMEOUT, LensConfConstants.MAIL_DEFAULT_SMTP_CONNECTIONTIMEOUT)); } /* * (non-Javadoc) * * @see org.apache.lens.server.api.events.AsyncEventListener#process(org.apache.lens.server.api.events.LensEvent) */ @Override public void process(QueryEnded event) { if (event.getCurrentValue() == QueryStatus.Status.CLOSED) { return; } QueryContext queryContext = queryService.getQueryContext(event.getQueryHandle()); if (queryContext == null) { LOG.warn("Could not find the context for " + event.getQueryHandle() + " for event:" + event.getCurrentValue() + ". No email generated"); return; } boolean whetherMailNotify = Boolean.parseBoolean(queryContext.getConf().get(LensConfConstants.QUERY_MAIL_NOTIFY, LensConfConstants.WHETHER_MAIL_NOTIFY_DEFAULT)); if (!whetherMailNotify) { return; } String queryName = queryContext.getQueryName(); queryName = queryName == null ? "" : queryName; String mailSubject = "Query " + queryName + " " + queryContext.getStatus().getStatus() + ": " + event.getQueryHandle(); String mailMessage = createMailMessage(queryContext); String to = queryContext.getSubmittedUser() + "@" + queryService.getServerDomain(); String cc = queryContext.getConf().get(LensConfConstants.QUERY_RESULT_EMAIL_CC, LensConfConstants.QUERY_RESULT_DEFAULT_EMAIL_CC); LOG.info("Sending completion email for query handle: " + event.getQueryHandle()); sendMail(host, port, from, to, cc, mailSubject, mailMessage, mailSmtpTimeout, mailSmtpConnectionTimeout); } /** * Creates the mail message. * * @param queryContext * the query context * @return the string */ private String createMailMessage(QueryContext queryContext) { StringBuilder msgBuilder = new StringBuilder(); switch (queryContext.getStatus().getStatus()) { case SUCCESSFUL: msgBuilder.append("Result available at "); String baseURI = conf.get(LensConfConstants.SERVER_BASE_URL, LensConfConstants.DEFAULT_SERVER_BASE_URL); msgBuilder.append(baseURI); msgBuilder.append("queryapi/queries/"); msgBuilder.append(queryContext.getQueryHandle()); msgBuilder.append("/httpresultset"); break; case FAILED: msgBuilder.append(queryContext.getStatus().getErrorMessage()); break; case CANCELED: case CLOSED: default: break; } return msgBuilder.toString(); } /** * Send mail. * * @param host * the host * @param port * the port * @param from * the from * @param to * the to * @param cc * the cc * @param subject * the subject * @param mailMessage * the mail message * @param mailSmtpTimeout * the mail smtp timeout * @param mailSmtpConnectionTimeout * the mail smtp connection timeout */ public static void sendMail(String host, String port, String from, String to, String cc, String subject, String mailMessage, int mailSmtpTimeout, int mailSmtpConnectionTimeout) { Properties props = System.getProperties(); props.put("mail.smtp.host", host); props.put("mail.smtp.port", port); props.put("mail.smtp.timeout", mailSmtpTimeout); props.put("mail.smtp.connectiontimeout", mailSmtpConnectionTimeout); Session session = Session.getDefaultInstance(props, null); try { MimeMessage message = new MimeMessage(session); message.setFrom(new InternetAddress(from)); for(String recipient: to.trim().split("\\s*,\\s*")) { message.addRecipients(Message.RecipientType.TO, InternetAddress.parse(recipient)); } if (cc != null && cc.length() > 0) { for(String recipient: cc.trim().split("\\s*,\\s*")) { message.addRecipients(Message.RecipientType.CC, InternetAddress.parse(recipient)); } } message.setSubject(subject); message.setSentDate(new Date()); MimeBodyPart messagePart = new MimeBodyPart(); messagePart.setText(mailMessage); Multipart multipart = new MimeMultipart(); multipart.addBodyPart(messagePart); message.setContent(multipart); Transport.send(message); } catch (Exception e) { MetricsService metricsService = (MetricsService) LensServices.get().getService(MetricsService.NAME); metricsService.incrCounter(QueryEndNotifier.class, EMAIL_ERROR_COUNTER); LOG.error("Error sending query end email", e); } } }
apache-2.0
webmetrics/browsermob-proxy
src/main/java/org/browsermob/proxy/jetty/jetty/servlet/jmx/SessionManagerMBean.java
1662
// ======================================================================== // $Id: SessionManagerMBean.java,v 1.4 2004/05/09 20:32:35 gregwilkins Exp $ // Copyright 2003-2004 Mort Bay Consulting Pty. Ltd. // ------------------------------------------------------------------------ // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ======================================================================== package org.browsermob.proxy.jetty.jetty.servlet.jmx; import org.browsermob.proxy.jetty.jetty.servlet.SessionManager; import org.browsermob.proxy.jetty.util.jmx.LifeCycleMBean; import javax.management.MBeanException; /* ------------------------------------------------------------ */ /** * * @version $Revision: 1.4 $ * @author Greg Wilkins (gregw) */ public class SessionManagerMBean extends LifeCycleMBean { /* ------------------------------------------------------------ */ public SessionManagerMBean() throws MBeanException {} /* ------------------------------------------------------------ */ public SessionManagerMBean(SessionManager object) throws MBeanException { super(object); } }
apache-2.0
strongbox/strongbox
strongbox-storage/strongbox-storage-api/src/main/java/org/carlspring/strongbox/domain/ArtifactEntry.java
5411
package org.carlspring.strongbox.domain; import org.carlspring.strongbox.artifact.ArtifactTag; import org.carlspring.strongbox.artifact.coordinates.AbstractArtifactCoordinates; import org.carlspring.strongbox.artifact.coordinates.ArtifactCoordinates; import org.carlspring.strongbox.data.domain.GenericEntity; import javax.persistence.CascadeType; import javax.persistence.Embedded; import javax.persistence.Entity; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.Transient; import java.util.Date; import java.util.HashSet; import java.util.Optional; import java.util.Set; import java.util.Map; import java.util.HashMap; /** * @author carlspring */ @Entity public class ArtifactEntry extends GenericEntity { private String storageId; private String repositoryId; // if you have to rename this field please update ArtifactEntryServiceImpl.findByCoordinates() implementation @ManyToOne(cascade = { CascadeType.DETACH, CascadeType.MERGE, CascadeType.PERSIST, CascadeType.REFRESH }) private AbstractArtifactCoordinates artifactCoordinates; @ManyToMany(targetEntity = ArtifactTagEntry.class) private Set<ArtifactTag> tagSet; private Map<String, String> checksums; @Embedded private ArtifactArchiveListing artifactArchiveListing; private Long sizeInBytes; private Date lastUpdated; private Date lastUsed; private Date created; private Integer downloadCount = Integer.valueOf(0); public ArtifactEntry() { } public String getStorageId() { return storageId; } public void setStorageId(String storageId) { this.storageId = storageId; } public String getRepositoryId() { return repositoryId; } public void setRepositoryId(String repositoryId) { this.repositoryId = repositoryId; } public ArtifactCoordinates getArtifactCoordinates() { return artifactCoordinates; } public void setArtifactCoordinates(ArtifactCoordinates artifactCoordinates) { this.artifactCoordinates = (AbstractArtifactCoordinates) artifactCoordinates; } public Set<ArtifactTag> getTagSet() { return tagSet = Optional.ofNullable(tagSet).orElse(new HashSet<>()); } protected void setTagSet(Set<ArtifactTag> tagSet) { this.tagSet = tagSet; } public Map<String, String> getChecksums() { return checksums = Optional.ofNullable(checksums).orElse(new HashMap<>()); } protected void setChecksums(Map<String, String> checksums) { this.checksums = checksums; } public Long getSizeInBytes() { return sizeInBytes; } public void setSizeInBytes(Long sizeInBytes) { this.sizeInBytes = sizeInBytes; } public Date getLastUpdated() { return lastUpdated != null ? new Date(lastUpdated.getTime()) : null; } public void setLastUpdated(Date lastUpdated) { this.lastUpdated = lastUpdated != null ? new Date(lastUpdated.getTime()) : null; } public Date getLastUsed() { return lastUsed != null ? new Date(lastUsed.getTime()) : null; } public void setLastUsed(Date lastUsed) { this.lastUsed = lastUsed != null ? new Date(lastUsed.getTime()) : null; } public Date getCreated() { return created; } public void setCreated(Date created) { this.created = created; } public Integer getDownloadCount() { return downloadCount; } public void setDownloadCount(Integer downloadCount) { this.downloadCount = downloadCount; } public ArtifactArchiveListing getArtifactArchiveListing() { return artifactArchiveListing; } public void setArtifactArchiveListing(final ArtifactArchiveListing artifactArchiveListing) { this.artifactArchiveListing = artifactArchiveListing; } @Transient public String getArtifactPath() { return Optional.of(getArtifactCoordinates()) .map(c -> c.toPath()) .orElseThrow(() -> new IllegalStateException("ArtifactCoordinates required to be set.")); } @Override public String toString() { final StringBuilder sb = new StringBuilder("\nArtifactEntry{"); sb.append("storageId='").append(storageId).append('\''); sb.append(", repositoryId='").append(repositoryId).append('\''); sb.append(", artifactCoordinates=").append(artifactCoordinates).append('\n'); sb.append(", tagSet=").append(tagSet); sb.append(", checksums=").append(checksums); sb.append(", objectId='").append(objectId).append('\''); sb.append(", uuid='").append(uuid).append('\''); sb.append(", artifactArchiveListing=").append(artifactArchiveListing); sb.append(", entityVersion=").append(entityVersion); sb.append(", sizeInBytes=").append(sizeInBytes); sb.append(", lastUpdated=").append(lastUpdated); sb.append(", lastUsed=").append(lastUsed); sb.append(", created=").append(created); sb.append(", downloadCount=").append(downloadCount); sb.append('}').append('\n'); return sb.toString(); } }
apache-2.0
apache/continuum
continuum-api/src/main/java/org/apache/maven/continuum/execution/ContinuumBuildCancelledException.java
1327
package org.apache.maven.continuum.execution; /* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ /** * @author <a href="mailto:trygvis@inamo.no">Trygve Laugst&oslash;l</a> */ public class ContinuumBuildCancelledException extends ContinuumBuildExecutorException { private static final long serialVersionUID = 6658199253278756183L; public ContinuumBuildCancelledException( String message ) { super( message ); } public ContinuumBuildCancelledException( String message, Throwable cause ) { super( message, cause ); } }
apache-2.0
Tinker-S/FaceBarCodeDemo
src/com/google/zxing/ChecksumException.java
1107
/* * Copyright 2007 ZXing authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.zxing; /** * Thrown when a barcode was successfully detected and decoded, but was not * returned because its checksum feature failed. * * @author Sean Owen */ public final class ChecksumException extends ReaderException { private static final long serialVersionUID = 1L; private static final ChecksumException instance = new ChecksumException(); private ChecksumException() { // do nothing } public static ChecksumException getChecksumInstance() { return instance; } }
apache-2.0
tebriel/elasticsearch
core/src/main/java/org/elasticsearch/rest/action/search/RestMultiSearchAction.java
10384
/* * Licensed to Elasticsearch under one or more contributor * license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright * ownership. Elasticsearch licenses this file to you under * the Apache License, Version 2.0 (the "License"); you may * not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ package org.elasticsearch.rest.action.search; import org.elasticsearch.action.search.MultiSearchRequest; import org.elasticsearch.action.search.SearchRequest; import org.elasticsearch.action.support.IndicesOptions; import org.elasticsearch.client.Client; import org.elasticsearch.common.Nullable; import org.elasticsearch.common.ParseFieldMatcher; import org.elasticsearch.common.Strings; import org.elasticsearch.common.bytes.BytesReference; import org.elasticsearch.common.inject.Inject; import org.elasticsearch.common.settings.Settings; import org.elasticsearch.common.xcontent.XContent; import org.elasticsearch.common.xcontent.XContentFactory; import org.elasticsearch.common.xcontent.XContentParser; import org.elasticsearch.index.query.QueryParseContext; import org.elasticsearch.index.query.TemplateQueryParser; import org.elasticsearch.indices.query.IndicesQueriesRegistry; import org.elasticsearch.rest.BaseRestHandler; import org.elasticsearch.rest.RestChannel; import org.elasticsearch.rest.RestController; import org.elasticsearch.rest.RestRequest; import org.elasticsearch.rest.action.support.RestActions; import org.elasticsearch.rest.action.support.RestToXContentListener; import org.elasticsearch.script.Template; import org.elasticsearch.search.builder.SearchSourceBuilder; import java.util.Map; import static org.elasticsearch.common.xcontent.support.XContentMapValues.lenientNodeBooleanValue; import static org.elasticsearch.common.xcontent.support.XContentMapValues.nodeStringArrayValue; import static org.elasticsearch.common.xcontent.support.XContentMapValues.nodeStringValue; import static org.elasticsearch.rest.RestRequest.Method.GET; import static org.elasticsearch.rest.RestRequest.Method.POST; /** */ public class RestMultiSearchAction extends BaseRestHandler { private final boolean allowExplicitIndex; private final IndicesQueriesRegistry indicesQueriesRegistry; @Inject public RestMultiSearchAction(Settings settings, RestController controller, Client client, IndicesQueriesRegistry indicesQueriesRegistry) { super(settings, client); controller.registerHandler(GET, "/_msearch", this); controller.registerHandler(POST, "/_msearch", this); controller.registerHandler(GET, "/{index}/_msearch", this); controller.registerHandler(POST, "/{index}/_msearch", this); controller.registerHandler(GET, "/{index}/{type}/_msearch", this); controller.registerHandler(POST, "/{index}/{type}/_msearch", this); controller.registerHandler(GET, "/_msearch/template", this); controller.registerHandler(POST, "/_msearch/template", this); controller.registerHandler(GET, "/{index}/_msearch/template", this); controller.registerHandler(POST, "/{index}/_msearch/template", this); controller.registerHandler(GET, "/{index}/{type}/_msearch/template", this); controller.registerHandler(POST, "/{index}/{type}/_msearch/template", this); this.allowExplicitIndex = MULTI_ALLOW_EXPLICIT_INDEX.get(settings); this.indicesQueriesRegistry = indicesQueriesRegistry; } @Override public void handleRequest(final RestRequest request, final RestChannel channel, final Client client) throws Exception { MultiSearchRequest multiSearchRequest = new MultiSearchRequest(); String[] indices = Strings.splitStringByCommaToArray(request.param("index")); String[] types = Strings.splitStringByCommaToArray(request.param("type")); String path = request.path(); boolean isTemplateRequest = isTemplateRequest(path); IndicesOptions indicesOptions = IndicesOptions.fromRequest(request, multiSearchRequest.indicesOptions()); parseRequest(multiSearchRequest, RestActions.getRestContent(request), isTemplateRequest, indices, types, request.param("search_type"), request.param("routing"), indicesOptions, allowExplicitIndex, indicesQueriesRegistry, parseFieldMatcher); client.multiSearch(multiSearchRequest, new RestToXContentListener<>(channel)); } private boolean isTemplateRequest(String path) { return (path != null && path.endsWith("/template")); } public static MultiSearchRequest parseRequest(MultiSearchRequest msr, BytesReference data, boolean isTemplateRequest, @Nullable String[] indices, @Nullable String[] types, @Nullable String searchType, @Nullable String routing, IndicesOptions indicesOptions, boolean allowExplicitIndex, IndicesQueriesRegistry indicesQueriesRegistry, ParseFieldMatcher parseFieldMatcher) throws Exception { XContent xContent = XContentFactory.xContent(data); int from = 0; int length = data.length(); byte marker = xContent.streamSeparator(); final QueryParseContext queryParseContext = new QueryParseContext(indicesQueriesRegistry); while (true) { int nextMarker = findNextMarker(marker, from, data, length); if (nextMarker == -1) { break; } // support first line with \n if (nextMarker == 0) { from = nextMarker + 1; continue; } SearchRequest searchRequest = new SearchRequest(); if (indices != null) { searchRequest.indices(indices); } if (indicesOptions != null) { searchRequest.indicesOptions(indicesOptions); } if (types != null && types.length > 0) { searchRequest.types(types); } if (routing != null) { searchRequest.routing(routing); } searchRequest.searchType(searchType); IndicesOptions defaultOptions = IndicesOptions.strictExpandOpenAndForbidClosed(); // now parse the action if (nextMarker - from > 0) { try (XContentParser parser = xContent.createParser(data.slice(from, nextMarker - from))) { Map<String, Object> source = parser.map(); for (Map.Entry<String, Object> entry : source.entrySet()) { Object value = entry.getValue(); if ("index".equals(entry.getKey()) || "indices".equals(entry.getKey())) { if (!allowExplicitIndex) { throw new IllegalArgumentException("explicit index in multi percolate is not allowed"); } searchRequest.indices(nodeStringArrayValue(value)); } else if ("type".equals(entry.getKey()) || "types".equals(entry.getKey())) { searchRequest.types(nodeStringArrayValue(value)); } else if ("search_type".equals(entry.getKey()) || "searchType".equals(entry.getKey())) { searchRequest.searchType(nodeStringValue(value, null)); } else if ("request_cache".equals(entry.getKey()) || "requestCache".equals(entry.getKey())) { searchRequest.requestCache(lenientNodeBooleanValue(value)); } else if ("preference".equals(entry.getKey())) { searchRequest.preference(nodeStringValue(value, null)); } else if ("routing".equals(entry.getKey())) { searchRequest.routing(nodeStringValue(value, null)); } } defaultOptions = IndicesOptions.fromMap(source, defaultOptions); } } searchRequest.indicesOptions(defaultOptions); // move pointers from = nextMarker + 1; // now for the body nextMarker = findNextMarker(marker, from, data, length); if (nextMarker == -1) { break; } final BytesReference slice = data.slice(from, nextMarker - from); if (isTemplateRequest) { try (XContentParser parser = XContentFactory.xContent(slice).createParser(slice)) { queryParseContext.reset(parser); queryParseContext.parseFieldMatcher(parseFieldMatcher); Template template = TemplateQueryParser.parse(parser, queryParseContext.parseFieldMatcher(), "params", "template"); searchRequest.template(template); } } else { try (XContentParser requestParser = XContentFactory.xContent(slice).createParser(slice)) { queryParseContext.reset(requestParser); searchRequest.source(SearchSourceBuilder.parseSearchSource(requestParser, queryParseContext)); } } // move pointers from = nextMarker + 1; msr.add(searchRequest); } return msr; } private static int findNextMarker(byte marker, int from, BytesReference data, int length) { for (int i = from; i < length; i++) { if (data.get(i) == marker) { return i; } } return -1; } }
apache-2.0
apache/incubator-taverna-workbench-common-activities
taverna-external-tool-activity-ui/src/main/java/org/apache/taverna/activities/externaltool/menu/AddExternalToolContextualMenuAction.java
3911
package org.apache.taverna.activities.externaltool.menu; /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import java.awt.event.ActionEvent; import java.net.URI; import javax.swing.AbstractAction; import javax.swing.Action; import org.apache.log4j.Logger; import org.apache.taverna.activities.externaltool.servicedescriptions.ExternalToolTemplateServiceDescription; import org.apache.taverna.services.ServiceRegistry; import org.apache.taverna.ui.menu.AbstractContextualMenuAction; import org.apache.taverna.ui.menu.MenuManager; import org.apache.taverna.workbench.activityicons.ActivityIconManager; import org.apache.taverna.workbench.edits.EditManager; import org.apache.taverna.workbench.selection.SelectionManager; import org.apache.taverna.workbench.ui.workflowview.WorkflowView; import org.apache.taverna.workflowmodel.Dataflow; import static org.apache.taverna.activities.externaltool.servicedescriptions.ExternalToolServiceDescription.TOOL_ACTIVITY_URI; /** * An action to add an external tool + a wrapping processor to the workflow. * * @author Alex Nenadic * @author Alan Williamns * */ @SuppressWarnings("serial") public class AddExternalToolContextualMenuAction extends AbstractContextualMenuAction { private static final String ADD_EXTERNAL_TOOL = "Tool"; private static final URI insertSection = URI .create("http://taverna.sf.net/2009/contextMenu/insert"); private static Logger logger = Logger.getLogger(AddExternalToolMenuAction.class); private EditManager editManager; private MenuManager menuManager; private SelectionManager selectionManager; private ActivityIconManager activityIconManager; private ServiceRegistry serviceRegistry; public AddExternalToolContextualMenuAction() { super(insertSection, 900); } @Override public boolean isEnabled() { return super.isEnabled() && getContextualSelection().getSelection() instanceof Dataflow; } @Override protected Action createAction() { return new AddExternalToolAction(); } protected class AddExternalToolAction extends AbstractAction { AddExternalToolAction() { super(ADD_EXTERNAL_TOOL, activityIconManager.iconForActivity(TOOL_ACTIVITY_URI)); } public void actionPerformed(ActionEvent e) { WorkflowView.importServiceDescription( ExternalToolTemplateServiceDescription.getServiceDescription(), false, editManager, menuManager, selectionManager, getServiceRegistry()); } } public void setEditManager(EditManager editManager) { this.editManager = editManager; } public void setMenuManager(MenuManager menuManager) { this.menuManager = menuManager; } public void setSelectionManager(SelectionManager selectionManager) { this.selectionManager = selectionManager; } public void setActivityIconManager(ActivityIconManager activityIconManager) { this.activityIconManager = activityIconManager; } public ServiceRegistry getServiceRegistry() { return serviceRegistry; } public void setServiceRegistry(ServiceRegistry serviceRegistry) { this.serviceRegistry = serviceRegistry; } }
apache-2.0
dropbox/bazel
src/main/java/com/google/devtools/build/docgen/skylark/SkylarkBuiltinMethodDoc.java
2837
// Copyright 2014 The Bazel Authors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. package com.google.devtools.build.docgen.skylark; import com.google.devtools.build.lib.skylarkinterface.SkylarkSignature; import com.google.devtools.build.lib.syntax.BaseFunction; import com.google.devtools.build.lib.syntax.EvalUtils; import java.util.List; /** * A class representing a Skylark built-in object or method. */ public final class SkylarkBuiltinMethodDoc extends SkylarkMethodDoc { private final SkylarkModuleDoc module; private final SkylarkSignature annotation; private final Class<?> fieldClass; private List<SkylarkParamDoc> params; public SkylarkBuiltinMethodDoc(SkylarkModuleDoc module, SkylarkSignature annotation, Class<?> fieldClass) { this.module = module; this.annotation = annotation; this.fieldClass = fieldClass; this.params = SkylarkDocUtils.determineParams( this, withoutSelfParam(annotation), annotation.extraPositionals(), annotation.extraKeywords()); } public SkylarkSignature getAnnotation() { return annotation; } @Override public boolean documented() { return annotation.documented(); } @Override public String getName() { return annotation.name(); } @Override public String getDocumentation() { return SkylarkDocUtils.substituteVariables(annotation.doc()); } /** * Returns a string representing the method signature with links to the types if * available. * * <p>If the built-in method is a function, the construct the method signature. Otherwise, * return a string containing the return type of the method. */ @Override public String getSignature() { if (BaseFunction.class.isAssignableFrom(fieldClass)) { return getSignature(module.getName(), annotation); } if (!annotation.returnType().equals(Object.class)) { return getTypeAnchor(annotation.returnType()); } return ""; } @Override public String getReturnType() { return EvalUtils.getDataTypeNameFromClass(annotation.returnType()); } @Override public Boolean isCallable() { return BaseFunction.class.isAssignableFrom(fieldClass); } @Override public List<SkylarkParamDoc> getParams() { return params; } }
apache-2.0
apixandru/intellij-community
java/java-psi-impl/src/com/intellij/psi/controlFlow/ControlFlowAnalyzer.java
64028
/* * Copyright 2000-2016 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.psi.controlFlow; import com.intellij.codeInsight.ExceptionUtil; import com.intellij.codeInsight.daemon.JavaErrorMessages; import com.intellij.openapi.diagnostic.Logger; import com.intellij.openapi.progress.ProgressManager; import com.intellij.openapi.project.Project; import com.intellij.openapi.util.Comparing; import com.intellij.psi.*; import com.intellij.psi.tree.IElementType; import com.intellij.psi.util.PsiTreeUtil; import com.intellij.psi.util.PsiUtil; import com.intellij.util.containers.Stack; import gnu.trove.THashMap; import gnu.trove.TIntArrayList; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import java.util.*; class ControlFlowAnalyzer extends JavaElementVisitor { private static final Logger LOG = Logger.getInstance("#com.intellij.psi.controlFlow.ControlFlowAnalyzer"); private final PsiElement myCodeFragment; private final ControlFlowPolicy myPolicy; private ControlFlowImpl myCurrentFlow; private final ControlFlowStack myStack = new ControlFlowStack(); private final Stack<PsiParameter> myCatchParameters = new Stack<>();// stack of PsiParameter for catch private final Stack<PsiElement> myCatchBlocks = new Stack<>(); private final Stack<FinallyBlockSubroutine> myFinallyBlocks = new Stack<>(); private final Stack<PsiElement> myUnhandledExceptionCatchBlocks = new Stack<>(); // element to jump to from inner (sub)expression in "jump to begin" situation. // E.g. we should jump to "then" branch if condition expression evaluated to true inside if statement private final StatementStack myStartStatementStack = new StatementStack(); // element to jump to from inner (sub)expression in "jump to end" situation. // E.g. we should jump to "else" branch if condition expression evaluated to false inside if statement private final StatementStack myEndStatementStack = new StatementStack(); private final Stack<BranchingInstruction.Role> myStartJumpRoles = new Stack<>(); private final Stack<BranchingInstruction.Role> myEndJumpRoles = new Stack<>(); // true if generate direct jumps for short-circuited operations, // e.g. jump to else branch of if statement after each calculation of '&&' operand in condition private final boolean myEnabledShortCircuit; // true if evaluate constant expression inside 'if' statement condition and alter control flow accordingly // in case of unreachable statement analysis must be false private final boolean myEvaluateConstantIfCondition; private final boolean myAssignmentTargetsAreElements; private final Stack<TIntArrayList> intArrayPool = new Stack<>(); // map: PsiElement element -> TIntArrayList instructionOffsetsToPatch with getStartOffset(element) private final Map<PsiElement, TIntArrayList> offsetsAddElementStart = new THashMap<>(); // map: PsiElement element -> TIntArrayList instructionOffsetsToPatch with getEndOffset(element) private final Map<PsiElement, TIntArrayList> offsetsAddElementEnd = new THashMap<>(); private final ControlFlowFactory myControlFlowFactory; private final Map<PsiElement, ControlFlowSubRange> mySubRanges = new THashMap<>(); private final PsiConstantEvaluationHelper myConstantEvaluationHelper; ControlFlowAnalyzer(@NotNull PsiElement codeFragment, @NotNull ControlFlowPolicy policy, boolean enabledShortCircuit, boolean evaluateConstantIfCondition) { this(codeFragment, policy, enabledShortCircuit, evaluateConstantIfCondition, false); } private ControlFlowAnalyzer(@NotNull PsiElement codeFragment, @NotNull ControlFlowPolicy policy, boolean enabledShortCircuit, boolean evaluateConstantIfCondition, boolean assignmentTargetsAreElements) { myCodeFragment = codeFragment; myPolicy = policy; myEnabledShortCircuit = enabledShortCircuit; myEvaluateConstantIfCondition = evaluateConstantIfCondition; myAssignmentTargetsAreElements = assignmentTargetsAreElements; Project project = codeFragment.getProject(); myControlFlowFactory = ControlFlowFactory.getInstance(project); myConstantEvaluationHelper = JavaPsiFacade.getInstance(project).getConstantEvaluationHelper(); } @NotNull ControlFlow buildControlFlow() throws AnalysisCanceledException { // push guard outer statement offsets in case when nested expression is incorrect myStartJumpRoles.push(BranchingInstruction.Role.END); myEndJumpRoles.push(BranchingInstruction.Role.END); myCurrentFlow = new ControlFlowImpl(); // guard elements myStartStatementStack.pushStatement(myCodeFragment, false); myEndStatementStack.pushStatement(myCodeFragment, false); try { myCodeFragment.accept(this); cleanup(); } catch (AnalysisCanceledSoftException e) { throw new AnalysisCanceledException(e.getErrorElement()); } return myCurrentFlow; } private static class StatementStack { private final Stack<PsiElement> myStatements = new Stack<>(); private final TIntArrayList myAtStart = new TIntArrayList(); private void popStatement() { myAtStart.remove(myAtStart.size() - 1); myStatements.pop(); } @NotNull private PsiElement peekElement() { return myStatements.peek(); } private boolean peekAtStart() { return myAtStart.get(myAtStart.size() - 1) == 1; } private void pushStatement(@NotNull PsiElement statement, boolean atStart) { myStatements.push(statement); myAtStart.add(atStart ? 1 : 0); } } @NotNull private TIntArrayList getEmptyIntArray() { if (intArrayPool.isEmpty()) { return new TIntArrayList(1); } TIntArrayList list = intArrayPool.pop(); list.clear(); return list; } private void poolIntArray(@NotNull TIntArrayList list) { intArrayPool.add(list); } // patch instruction currently added to control flow so that its jump offset corrected on getStartOffset(element) or getEndOffset(element) // when corresponding element offset become available private void addElementOffsetLater(@NotNull PsiElement element, boolean atStart) { Map<PsiElement, TIntArrayList> offsetsAddElement = atStart ? offsetsAddElementStart : offsetsAddElementEnd; TIntArrayList offsets = offsetsAddElement.get(element); if (offsets == null) { offsets = getEmptyIntArray(); offsetsAddElement.put(element, offsets); } int offset = myCurrentFlow.getSize() - 1; offsets.add(offset); if (myCurrentFlow.getEndOffset(element) != -1) { patchInstructionOffsets(element); } } private void patchInstructionOffsets(@NotNull PsiElement element) { patchInstructionOffsets(offsetsAddElementStart.get(element), myCurrentFlow.getStartOffset(element)); offsetsAddElementStart.put(element, null); patchInstructionOffsets(offsetsAddElementEnd.get(element), myCurrentFlow.getEndOffset(element)); offsetsAddElementEnd.put(element, null); } private void patchInstructionOffsets(@Nullable TIntArrayList offsets, int add) { if (offsets == null) return; for (int i = 0; i < offsets.size(); i++) { int offset = offsets.get(i); BranchingInstruction instruction = (BranchingInstruction)myCurrentFlow.getInstructions().get(offset); instruction.offset += add; LOG.assertTrue(instruction.offset >= 0); } poolIntArray(offsets); } private void cleanup() { // make all non patched goto instructions jump to the end of control flow for (TIntArrayList offsets : offsetsAddElementStart.values()) { patchInstructionOffsets(offsets, myCurrentFlow.getEndOffset(myCodeFragment)); } for (TIntArrayList offsets : offsetsAddElementEnd.values()) { patchInstructionOffsets(offsets, myCurrentFlow.getEndOffset(myCodeFragment)); } // register all sub ranges for (Map.Entry<PsiElement, ControlFlowSubRange> entry : mySubRanges.entrySet()) { ProgressManager.checkCanceled(); ControlFlowSubRange subRange = entry.getValue(); PsiElement element = entry.getKey(); myControlFlowFactory.registerSubRange(element, subRange, myEvaluateConstantIfCondition, myEnabledShortCircuit, myPolicy); } } private void startElement(@NotNull PsiElement element) { for (PsiElement child = element.getFirstChild(); child != null; child = child.getNextSibling()) { ProgressManager.checkCanceled(); if (child instanceof PsiErrorElement && !Comparing.strEqual(((PsiErrorElement)child).getErrorDescription(), JavaErrorMessages.message("expected.semicolon"))) { // do not perform control flow analysis for incomplete code throw new AnalysisCanceledSoftException(element); } } ProgressManager.checkCanceled(); myCurrentFlow.startElement(element); generateUncheckedExceptionJumpsIfNeeded(element, true); } private void generateUncheckedExceptionJumpsIfNeeded(@NotNull PsiElement element, boolean atStart) { // optimization: reduce number of instructions boolean isGeneratingStatement = element instanceof PsiStatement && !(element instanceof PsiSwitchLabelStatement); boolean isGeneratingCodeBlock = element instanceof PsiCodeBlock && !(element.getParent() instanceof PsiSwitchStatement); if (isGeneratingStatement || isGeneratingCodeBlock) { generateUncheckedExceptionJumps(element, atStart); } } private void finishElement(@NotNull PsiElement element) { generateUncheckedExceptionJumpsIfNeeded(element, false); myCurrentFlow.finishElement(element); patchInstructionOffsets(element); } private void generateUncheckedExceptionJumps(@NotNull PsiElement element, boolean atStart) { // optimization: if we just generated all necessary jumps, do not generate it once again if (atStart && element instanceof PsiStatement && element.getParent() instanceof PsiCodeBlock && element.getPrevSibling() != null) { return; } for (int i = myUnhandledExceptionCatchBlocks.size() - 1; i >= 0; i--) { ProgressManager.checkCanceled(); PsiElement block = myUnhandledExceptionCatchBlocks.get(i); // cannot jump to outer catch blocks (belonging to outer try stmt) if current try{} has finally block if (block == null) { if (!myFinallyBlocks.isEmpty()) { break; } else { continue; } } ConditionalThrowToInstruction throwToInstruction = new ConditionalThrowToInstruction(-1); // -1 for init parameter myCurrentFlow.addInstruction(throwToInstruction); if (!patchUncheckedThrowInstructionIfInsideFinally(throwToInstruction, element, block)) { addElementOffsetLater(block, true); } } // generate jump to the top finally block if (!myFinallyBlocks.isEmpty()) { final PsiElement finallyBlock = myFinallyBlocks.peek().getElement(); ConditionalThrowToInstruction throwToInstruction = new ConditionalThrowToInstruction(-2); myCurrentFlow.addInstruction(throwToInstruction); if (!patchUncheckedThrowInstructionIfInsideFinally(throwToInstruction, element, finallyBlock)) { addElementOffsetLater(finallyBlock, true); } } } private void generateCheckedExceptionJumps(@NotNull PsiElement element) { //generate jumps to all handled exception handlers Collection<PsiClassType> unhandledExceptions = ExceptionUtil.collectUnhandledExceptions(element, element.getParent()); for (PsiClassType unhandledException : unhandledExceptions) { ProgressManager.checkCanceled(); generateThrow(unhandledException, element); } } private void generateThrow(@NotNull PsiClassType unhandledException, @NotNull PsiElement throwingElement) { final List<PsiElement> catchBlocks = findThrowToBlocks(unhandledException); for (PsiElement block : catchBlocks) { ProgressManager.checkCanceled(); ConditionalThrowToInstruction instruction = new ConditionalThrowToInstruction(0); myCurrentFlow.addInstruction(instruction); if (!patchCheckedThrowInstructionIfInsideFinally(instruction, throwingElement, block)) { if (block == null) { addElementOffsetLater(myCodeFragment, false); } else { instruction.offset--; // -1 for catch block param init addElementOffsetLater(block, true); } } } } private final Map<PsiElement, List<PsiElement>> finallyBlockToUnhandledExceptions = new HashMap<>(); private boolean patchCheckedThrowInstructionIfInsideFinally(@NotNull ConditionalThrowToInstruction instruction, @NotNull PsiElement throwingElement, PsiElement elementToJumpTo) { final PsiElement finallyBlock = findEnclosingFinallyBlockElement(throwingElement, elementToJumpTo); if (finallyBlock == null) return false; List<PsiElement> unhandledExceptionCatchBlocks = finallyBlockToUnhandledExceptions.get(finallyBlock); if (unhandledExceptionCatchBlocks == null) { unhandledExceptionCatchBlocks = new ArrayList<>(); finallyBlockToUnhandledExceptions.put(finallyBlock, unhandledExceptionCatchBlocks); } int index = unhandledExceptionCatchBlocks.indexOf(elementToJumpTo); if (index == -1) { index = unhandledExceptionCatchBlocks.size(); unhandledExceptionCatchBlocks.add(elementToJumpTo); } // first three return instructions are for normal completion, return statement call completion and unchecked exception throwing completion resp. instruction.offset = 3 + index; addElementOffsetLater(finallyBlock, false); return true; } private boolean patchUncheckedThrowInstructionIfInsideFinally(@NotNull ConditionalThrowToInstruction instruction, @NotNull PsiElement throwingElement, @NotNull PsiElement elementToJumpTo) { final PsiElement finallyBlock = findEnclosingFinallyBlockElement(throwingElement, elementToJumpTo); if (finallyBlock == null) return false; // first three return instructions are for normal completion, return statement call completion and unchecked exception throwing completion resp. instruction.offset = 2; addElementOffsetLater(finallyBlock, false); return true; } @Override public void visitCodeFragment(JavaCodeFragment codeFragment) { startElement(codeFragment); int prevOffset = myCurrentFlow.getSize(); PsiElement[] children = codeFragment.getChildren(); for (PsiElement child : children) { ProgressManager.checkCanceled(); child.accept(this); } finishElement(codeFragment); registerSubRange(codeFragment, prevOffset); } private void registerSubRange(@NotNull PsiElement codeFragment, final int startOffset) { // cache child code block in hope it will be needed ControlFlowSubRange flow = new ControlFlowSubRange(myCurrentFlow, startOffset, myCurrentFlow.getSize()); // register it later since offset may not have been patched yet mySubRanges.put(codeFragment, flow); } @Override public void visitCodeBlock(PsiCodeBlock block) { startElement(block); int prevOffset = myCurrentFlow.getSize(); PsiStatement[] statements = block.getStatements(); for (PsiStatement statement : statements) { ProgressManager.checkCanceled(); statement.accept(this); } //each statement should contain at least one instruction in order to getElement(offset) work int nextOffset = myCurrentFlow.getSize(); if (!(block.getParent() instanceof PsiSwitchStatement) && prevOffset == nextOffset) { emitEmptyInstruction(); } finishElement(block); if (prevOffset != 0) { registerSubRange(block, prevOffset); } } private void emitEmptyInstruction() { myCurrentFlow.addInstruction(EmptyInstruction.INSTANCE); } @Override public void visitFile(PsiFile file) { visitChildren(file); } @Override public void visitBlockStatement(PsiBlockStatement statement) { startElement(statement); final PsiCodeBlock codeBlock = statement.getCodeBlock(); codeBlock.accept(this); finishElement(statement); } @Override public void visitBreakStatement(PsiBreakStatement statement) { startElement(statement); PsiStatement exitedStatement = statement.findExitedStatement(); if (exitedStatement != null) { callFinallyBlocksOnExit(exitedStatement); final Instruction instruction; final PsiElement finallyBlock = findEnclosingFinallyBlockElement(statement, exitedStatement); final int finallyStartOffset = finallyBlock == null ? -1 : myCurrentFlow.getStartOffset(finallyBlock); if (finallyBlock != null && finallyStartOffset != -1) { // go out of finally, use return CallInstruction callInstruction = (CallInstruction)myCurrentFlow.getInstructions().get(finallyStartOffset - 2); instruction = new ReturnInstruction(0, myStack, callInstruction); } else { instruction = new GoToInstruction(0); } myCurrentFlow.addInstruction(instruction); // exited statement might be out of control flow analyzed addElementOffsetLater(exitedStatement, false); } finishElement(statement); } private void callFinallyBlocksOnExit(PsiStatement exitedStatement) { for (final ListIterator<FinallyBlockSubroutine> it = myFinallyBlocks.listIterator(myFinallyBlocks.size()); it.hasPrevious(); ) { final FinallyBlockSubroutine finallyBlockSubroutine = it.previous(); PsiElement finallyBlock = finallyBlockSubroutine.getElement(); final PsiElement enclosingTryStatement = finallyBlock.getParent(); if (enclosingTryStatement == null || !PsiTreeUtil.isAncestor(exitedStatement, enclosingTryStatement, false)) { break; } CallInstruction instruction = new CallInstruction(0, 0, myStack); finallyBlockSubroutine.addCall(instruction); myCurrentFlow.addInstruction(instruction); addElementOffsetLater(finallyBlock, true); } } private PsiElement findEnclosingFinallyBlockElement(@NotNull PsiElement sourceElement, @Nullable PsiElement jumpElement) { PsiElement element = sourceElement; while (element != null && !(element instanceof PsiFile)) { if (element instanceof PsiCodeBlock && element.getParent() instanceof PsiTryStatement && ((PsiTryStatement)element.getParent()).getFinallyBlock() == element) { // element maybe out of scope to be analyzed if (myCurrentFlow.getStartOffset(element.getParent()) == -1) return null; if (jumpElement == null || !PsiTreeUtil.isAncestor(element, jumpElement, false)) return element; } element = element.getParent(); } return null; } @Override public void visitContinueStatement(PsiContinueStatement statement) { startElement(statement); PsiStatement continuedStatement = statement.findContinuedStatement(); if (continuedStatement != null) { PsiElement body = null; if (continuedStatement instanceof PsiLoopStatement) { body = ((PsiLoopStatement)continuedStatement).getBody(); } if (body == null) { body = myCodeFragment; } callFinallyBlocksOnExit(continuedStatement); final Instruction instruction; final PsiElement finallyBlock = findEnclosingFinallyBlockElement(statement, continuedStatement); final int finallyStartOffset = finallyBlock == null ? -1 : myCurrentFlow.getStartOffset(finallyBlock); if (finallyBlock != null && finallyStartOffset != -1) { // go out of finally, use return CallInstruction callInstruction = (CallInstruction)myCurrentFlow.getInstructions().get(finallyStartOffset - 2); instruction = new ReturnInstruction(0, myStack, callInstruction); } else { instruction = new GoToInstruction(0); } myCurrentFlow.addInstruction(instruction); addElementOffsetLater(body, false); } finishElement(statement); } @Override public void visitDeclarationStatement(PsiDeclarationStatement statement) { startElement(statement); int pc = myCurrentFlow.getSize(); PsiElement[] elements = statement.getDeclaredElements(); for (PsiElement element : elements) { ProgressManager.checkCanceled(); if (element instanceof PsiClass) { element.accept(this); } else if (element instanceof PsiVariable) { processVariable((PsiVariable)element); } } if (pc == myCurrentFlow.getSize()) { // generate at least one instruction for declaration emitEmptyInstruction(); } finishElement(statement); } private void processVariable(@NotNull PsiVariable element) { final PsiExpression initializer = element.getInitializer(); if (initializer != null) { myStartStatementStack.pushStatement(initializer, false); myEndStatementStack.pushStatement(initializer, false); initializer.accept(this); myStartStatementStack.popStatement(); myEndStatementStack.popStatement(); } if (element instanceof PsiLocalVariable && initializer != null || element instanceof PsiField) { if (element instanceof PsiLocalVariable && !myPolicy.isLocalVariableAccepted((PsiLocalVariable)element)) return; if (myAssignmentTargetsAreElements) { startElement(element); } generateWriteInstruction(element); if (myAssignmentTargetsAreElements) { finishElement(element); } } } @Override public void visitDoWhileStatement(PsiDoWhileStatement statement) { startElement(statement); PsiStatement body = statement.getBody(); myStartStatementStack.pushStatement(body == null ? statement : body, true); myEndStatementStack.pushStatement(statement, false); if (body != null) { body.accept(this); } PsiExpression condition = statement.getCondition(); if (condition != null) { condition.accept(this); } int offset = myCurrentFlow.getStartOffset(statement); Object loopCondition = myConstantEvaluationHelper.computeConstantExpression(statement.getCondition()); if (loopCondition instanceof Boolean) { if (((Boolean)loopCondition).booleanValue()) { myCurrentFlow.addInstruction(new GoToInstruction(offset)); } else { emitEmptyInstruction(); } } else { Instruction instruction = new ConditionalGoToInstruction(offset, statement.getCondition()); myCurrentFlow.addInstruction(instruction); } myStartStatementStack.popStatement(); myEndStatementStack.popStatement(); finishElement(statement); } @Override public void visitEmptyStatement(PsiEmptyStatement statement) { startElement(statement); emitEmptyInstruction(); finishElement(statement); } @Override public void visitExpressionStatement(PsiExpressionStatement statement) { startElement(statement); final PsiExpression expression = statement.getExpression(); expression.accept(this); for (PsiParameter catchParameter : myCatchParameters) { ProgressManager.checkCanceled(); PsiType type = catchParameter.getType(); if (type instanceof PsiClassType) { generateThrow((PsiClassType)type, statement); } } finishElement(statement); } @Override public void visitExpressionListStatement(PsiExpressionListStatement statement) { startElement(statement); PsiExpression[] expressions = statement.getExpressionList().getExpressions(); for (PsiExpression expr : expressions) { ProgressManager.checkCanceled(); expr.accept(this); } finishElement(statement); } @Override public void visitField(PsiField field) { final PsiExpression initializer = field.getInitializer(); if (initializer != null) { startElement(field); initializer.accept(this); finishElement(field); } } @Override public void visitForStatement(PsiForStatement statement) { startElement(statement); PsiStatement body = statement.getBody(); myStartStatementStack.pushStatement(body == null ? statement : body, false); myEndStatementStack.pushStatement(statement, false); PsiStatement initialization = statement.getInitialization(); if (initialization != null) { initialization.accept(this); } PsiExpression condition = statement.getCondition(); if (condition != null) { condition.accept(this); } Object loopCondition = myConstantEvaluationHelper.computeConstantExpression(condition); if (loopCondition instanceof Boolean || condition == null) { boolean value = condition == null || ((Boolean)loopCondition).booleanValue(); if (value) { emitEmptyInstruction(); } else { myCurrentFlow.addInstruction(new GoToInstruction(0)); addElementOffsetLater(statement, false); } } else { Instruction instruction = new ConditionalGoToInstruction(0, statement.getCondition()); myCurrentFlow.addInstruction(instruction); addElementOffsetLater(statement, false); } if (body != null) { body.accept(this); } PsiStatement update = statement.getUpdate(); if (update != null) { update.accept(this); } int offset = initialization != null ? myCurrentFlow.getEndOffset(initialization) : myCurrentFlow.getStartOffset(statement); Instruction instruction = new GoToInstruction(offset); myCurrentFlow.addInstruction(instruction); myStartStatementStack.popStatement(); myEndStatementStack.popStatement(); finishElement(statement); } @Override public void visitForeachStatement(PsiForeachStatement statement) { startElement(statement); final PsiStatement body = statement.getBody(); myStartStatementStack.pushStatement(body == null ? statement : body, false); myEndStatementStack.pushStatement(statement, false); final PsiExpression iteratedValue = statement.getIteratedValue(); if (iteratedValue != null) { iteratedValue.accept(this); } final int gotoTarget = myCurrentFlow.getSize(); Instruction instruction = new ConditionalGoToInstruction(0, statement.getIteratedValue()); myCurrentFlow.addInstruction(instruction); addElementOffsetLater(statement, false); final PsiParameter iterationParameter = statement.getIterationParameter(); if (myPolicy.isParameterAccepted(iterationParameter)) { generateWriteInstruction(iterationParameter); } if (body != null) { body.accept(this); } final GoToInstruction gotoInstruction = new GoToInstruction(gotoTarget); myCurrentFlow.addInstruction(gotoInstruction); myStartStatementStack.popStatement(); myEndStatementStack.popStatement(); finishElement(statement); } @Override public void visitIfStatement(PsiIfStatement statement) { startElement(statement); final PsiStatement elseBranch = statement.getElseBranch(); final PsiStatement thenBranch = statement.getThenBranch(); PsiExpression conditionExpression = statement.getCondition(); generateConditionalStatementInstructions(statement, conditionExpression, thenBranch, elseBranch); finishElement(statement); } private void generateConditionalStatementInstructions(@NotNull PsiElement statement, @Nullable PsiExpression conditionExpression, final PsiElement thenBranch, final PsiElement elseBranch) { if (thenBranch == null) { myStartStatementStack.pushStatement(statement, false); } else { myStartStatementStack.pushStatement(thenBranch, true); } if (elseBranch == null) { myEndStatementStack.pushStatement(statement, false); } else { myEndStatementStack.pushStatement(elseBranch, true); } myEndJumpRoles.push(elseBranch == null ? BranchingInstruction.Role.END : BranchingInstruction.Role.ELSE); myStartJumpRoles.push(thenBranch == null ? BranchingInstruction.Role.END : BranchingInstruction.Role.THEN); if (conditionExpression != null) { conditionExpression.accept(this); } boolean generateElseFlow = true; boolean generateThenFlow = true; boolean generateConditionalJump = true; /* * if() statement generated instructions outline: * 'if (C) { A } [ else { B } ]' : * generate (C) * cond_goto else * generate (A) * [ goto end ] * :else * [ generate (B) ] * :end */ if (myEvaluateConstantIfCondition) { final Object value = myConstantEvaluationHelper.computeConstantExpression(conditionExpression); if (value instanceof Boolean) { boolean condition = ((Boolean)value).booleanValue(); generateThenFlow = condition; generateElseFlow = !condition; generateConditionalJump = false; myCurrentFlow.setConstantConditionOccurred(true); } } if (generateConditionalJump) { BranchingInstruction.Role role = elseBranch == null ? BranchingInstruction.Role.END : BranchingInstruction.Role.ELSE; Instruction instruction = new ConditionalGoToInstruction(0, role, conditionExpression); myCurrentFlow.addInstruction(instruction); if (elseBranch == null) { addElementOffsetLater(statement, false); } else { addElementOffsetLater(elseBranch, true); } } if (thenBranch != null && generateThenFlow) { thenBranch.accept(this); } if (elseBranch != null && generateElseFlow) { if (generateThenFlow) { // make jump to end after then branch (only if it has been generated) Instruction instruction = new GoToInstruction(0); myCurrentFlow.addInstruction(instruction); addElementOffsetLater(statement, false); } elseBranch.accept(this); } myStartJumpRoles.pop(); myEndJumpRoles.pop(); myStartStatementStack.popStatement(); myEndStatementStack.popStatement(); } @Override public void visitLabeledStatement(PsiLabeledStatement statement) { startElement(statement); final PsiStatement innerStatement = statement.getStatement(); if (innerStatement != null) { innerStatement.accept(this); } finishElement(statement); } @Override public void visitReturnStatement(PsiReturnStatement statement) { startElement(statement); PsiExpression returnValue = statement.getReturnValue(); if (returnValue != null) { myStartStatementStack.pushStatement(returnValue, false); myEndStatementStack.pushStatement(returnValue, false); returnValue.accept(this); } addReturnInstruction(statement); if (returnValue != null) { myStartStatementStack.popStatement(); myEndStatementStack.popStatement(); } finishElement(statement); } private void addReturnInstruction(@NotNull PsiElement statement) { BranchingInstruction instruction; final PsiElement finallyBlock = findEnclosingFinallyBlockElement(statement, null); final int finallyStartOffset = finallyBlock == null ? -1 : myCurrentFlow.getStartOffset(finallyBlock); if (finallyBlock != null && finallyStartOffset != -1) { // go out of finally, go to 2nd return after finally block // second return is for return statement called completion instruction = new GoToInstruction(1, BranchingInstruction.Role.END, true); myCurrentFlow.addInstruction(instruction); addElementOffsetLater(finallyBlock, false); } else { instruction = new GoToInstruction(0, BranchingInstruction.Role.END, true); myCurrentFlow.addInstruction(instruction); if (myFinallyBlocks.isEmpty()) { addElementOffsetLater(myCodeFragment, false); } else { instruction.offset = -4; // -4 for return addElementOffsetLater(myFinallyBlocks.peek().getElement(), true); } } } @Override public void visitSwitchLabelStatement(PsiSwitchLabelStatement statement) { startElement(statement); PsiExpression caseValue = statement.getCaseValue(); if (caseValue != null) { myStartStatementStack.pushStatement(caseValue, false); myEndStatementStack.pushStatement(caseValue, false); caseValue.accept(this); myStartStatementStack.popStatement(); myEndStatementStack.popStatement(); } finishElement(statement); } @Override public void visitSwitchStatement(PsiSwitchStatement statement) { startElement(statement); PsiExpression expr = statement.getExpression(); if (expr != null) { expr.accept(this); } PsiCodeBlock body = statement.getBody(); if (body != null) { PsiStatement[] statements = body.getStatements(); PsiSwitchLabelStatement defaultLabel = null; for (PsiStatement aStatement : statements) { ProgressManager.checkCanceled(); if (aStatement instanceof PsiSwitchLabelStatement) { if (((PsiSwitchLabelStatement)aStatement).isDefaultCase()) { defaultLabel = (PsiSwitchLabelStatement)aStatement; } Instruction instruction = new ConditionalGoToInstruction(0, expr); myCurrentFlow.addInstruction(instruction); addElementOffsetLater(aStatement, true); } } if (defaultLabel == null) { Instruction instruction = new GoToInstruction(0); myCurrentFlow.addInstruction(instruction); addElementOffsetLater(body, false); } body.accept(this); } finishElement(statement); } @Override public void visitSynchronizedStatement(PsiSynchronizedStatement statement) { startElement(statement); PsiExpression lock = statement.getLockExpression(); if (lock != null) { lock.accept(this); } PsiCodeBlock body = statement.getBody(); if (body != null) { body.accept(this); } finishElement(statement); } @Override public void visitThrowStatement(PsiThrowStatement statement) { startElement(statement); PsiExpression exception = statement.getException(); if (exception != null) { exception.accept(this); } final List<PsiElement> blocks = findThrowToBlocks(statement); PsiElement element; if (blocks.isEmpty() || blocks.get(0) == null) { ThrowToInstruction instruction = new ThrowToInstruction(0); myCurrentFlow.addInstruction(instruction); if (myFinallyBlocks.isEmpty()) { element = myCodeFragment; addElementOffsetLater(element, false); } else { instruction.offset = -2; // -2 to rethrow exception element = myFinallyBlocks.peek().getElement(); addElementOffsetLater(element, true); } } else { for (int i = 0; i < blocks.size(); i++) { ProgressManager.checkCanceled(); element = blocks.get(i); BranchingInstruction instruction = i == blocks.size() - 1 ? new ThrowToInstruction(0) : new ConditionalThrowToInstruction(0); myCurrentFlow.addInstruction(instruction); instruction.offset = -1; // -1 to init catch param addElementOffsetLater(element, true); } } finishElement(statement); } /** * find offsets of catch(es) corresponding to this throw statement * myCatchParameters and myCatchBlocks arrays should be sorted in ascending scope order (from outermost to innermost) * * @return offset or -1 if not found */ @NotNull private List<PsiElement> findThrowToBlocks(@NotNull PsiThrowStatement statement) { final PsiExpression exceptionExpr = statement.getException(); if (exceptionExpr == null) return Collections.emptyList(); final PsiType throwType = exceptionExpr.getType(); if (!(throwType instanceof PsiClassType)) return Collections.emptyList(); return findThrowToBlocks((PsiClassType)throwType); } @NotNull private List<PsiElement> findThrowToBlocks(@NotNull PsiClassType throwType) { List<PsiElement> blocks = new ArrayList<>(); for (int i = myCatchParameters.size() - 1; i >= 0; i--) { ProgressManager.checkCanceled(); PsiParameter parameter = myCatchParameters.get(i); PsiType catchType = parameter.getType(); if (ControlFlowUtil.isCaughtExceptionType(throwType, catchType)) { blocks.add(myCatchBlocks.get(i)); } } if (blocks.isEmpty()) { // consider it as throw at the end of the control flow blocks.add(null); } return blocks; } @Override public void visitAssertStatement(PsiAssertStatement statement) { startElement(statement); myStartStatementStack.pushStatement(statement, false); myEndStatementStack.pushStatement(statement, false); Instruction passByWhenAssertionsDisabled = new ConditionalGoToInstruction(0, BranchingInstruction.Role.END, null); myCurrentFlow.addInstruction(passByWhenAssertionsDisabled); addElementOffsetLater(statement, false); // should not try to compute constant expression within assert // since assertions can be disabled/enabled at any moment via JVM flags final PsiExpression condition = statement.getAssertCondition(); if (condition != null) { myStartStatementStack.pushStatement(statement, false); myEndStatementStack.pushStatement(statement, false); myEndJumpRoles.push(BranchingInstruction.Role.END); myStartJumpRoles.push(BranchingInstruction.Role.END); condition.accept(this); myStartJumpRoles.pop(); myEndJumpRoles.pop(); myStartStatementStack.popStatement(); myEndStatementStack.popStatement(); } PsiExpression description = statement.getAssertDescription(); if (description != null) { description.accept(this); } Instruction instruction = new ConditionalThrowToInstruction(0, statement.getAssertCondition()); myCurrentFlow.addInstruction(instruction); addElementOffsetLater(myCodeFragment, false); myStartStatementStack.popStatement(); myEndStatementStack.popStatement(); finishElement(statement); } @Override public void visitTryStatement(PsiTryStatement statement) { startElement(statement); PsiCodeBlock[] catchBlocks = statement.getCatchBlocks(); PsiParameter[] catchBlockParameters = statement.getCatchBlockParameters(); int catchNum = Math.min(catchBlocks.length, catchBlockParameters.length); myUnhandledExceptionCatchBlocks.push(null); for (int i = catchNum - 1; i >= 0; i--) { ProgressManager.checkCanceled(); myCatchParameters.push(catchBlockParameters[i]); myCatchBlocks.push(catchBlocks[i]); final PsiType type = catchBlockParameters[i].getType(); // todo cast param if (type instanceof PsiClassType && ExceptionUtil.isUncheckedExceptionOrSuperclass((PsiClassType)type)) { myUnhandledExceptionCatchBlocks.push(catchBlocks[i]); } else if (type instanceof PsiDisjunctionType) { final PsiType lub = ((PsiDisjunctionType)type).getLeastUpperBound(); if (lub instanceof PsiClassType && ExceptionUtil.isUncheckedExceptionOrSuperclass((PsiClassType)lub)) { myUnhandledExceptionCatchBlocks.push(catchBlocks[i]); } else if (lub instanceof PsiIntersectionType) { for (PsiType conjunct : ((PsiIntersectionType)lub).getConjuncts()) { if (conjunct instanceof PsiClassType && ExceptionUtil.isUncheckedExceptionOrSuperclass((PsiClassType)conjunct)) { myUnhandledExceptionCatchBlocks.push(catchBlocks[i]); break; } } } } } PsiCodeBlock finallyBlock = statement.getFinallyBlock(); FinallyBlockSubroutine finallyBlockSubroutine = null; if (finallyBlock != null) { finallyBlockSubroutine = new FinallyBlockSubroutine(finallyBlock); myFinallyBlocks.push(finallyBlockSubroutine); } PsiResourceList resourceList = statement.getResourceList(); if (resourceList != null) { generateCheckedExceptionJumps(resourceList); resourceList.accept(this); } PsiCodeBlock tryBlock = statement.getTryBlock(); if (tryBlock != null) { // javac works as if all checked exceptions can occur at the top of the block generateCheckedExceptionJumps(tryBlock); tryBlock.accept(this); } //noinspection StatementWithEmptyBody while (myUnhandledExceptionCatchBlocks.pop() != null) ; myCurrentFlow.addInstruction(new GoToInstruction(finallyBlock == null ? 0 : -6)); if (finallyBlock == null) { addElementOffsetLater(statement, false); } else { addElementOffsetLater(finallyBlock, true); } for (int i = 0; i < catchNum; i++) { myCatchParameters.pop(); myCatchBlocks.pop(); } for (int i = catchNum - 1; i >= 0; i--) { ProgressManager.checkCanceled(); if (myPolicy.isParameterAccepted(catchBlockParameters[i])) { generateWriteInstruction(catchBlockParameters[i]); } PsiCodeBlock catchBlock = catchBlocks[i]; if (catchBlock != null) { catchBlock.accept(this); } else { LOG.error("Catch body is null (" + i + ") " + statement.getText()); } myCurrentFlow.addInstruction(new GoToInstruction(finallyBlock == null ? 0 : -6)); if (finallyBlock == null) { addElementOffsetLater(statement, false); } else { addElementOffsetLater(finallyBlock, true); } } if (finallyBlock != null) { myFinallyBlocks.pop(); } if (finallyBlock != null) { // normal completion, call finally block and proceed CallInstruction normalCompletion = new CallInstruction(0, 0, myStack); finallyBlockSubroutine.addCall(normalCompletion); myCurrentFlow.addInstruction(normalCompletion); addElementOffsetLater(finallyBlock, true); myCurrentFlow.addInstruction(new GoToInstruction(0)); addElementOffsetLater(statement, false); // return completion, call finally block and return CallInstruction returnCompletion = new CallInstruction(0, 0, myStack); finallyBlockSubroutine.addCall(returnCompletion); myCurrentFlow.addInstruction(returnCompletion); addElementOffsetLater(finallyBlock, true); addReturnInstruction(statement); // throw exception completion, call finally block and rethrow CallInstruction throwExceptionCompletion = new CallInstruction(0, 0, myStack); finallyBlockSubroutine.addCall(throwExceptionCompletion); myCurrentFlow.addInstruction(throwExceptionCompletion); addElementOffsetLater(finallyBlock, true); final GoToInstruction gotoUncheckedRethrow = new GoToInstruction(0); myCurrentFlow.addInstruction(gotoUncheckedRethrow); addElementOffsetLater(finallyBlock, false); finallyBlock.accept(this); final int procStart = myCurrentFlow.getStartOffset(finallyBlock); final int procEnd = myCurrentFlow.getEndOffset(finallyBlock); for (CallInstruction callInstruction : finallyBlockSubroutine.getCalls()) { callInstruction.procBegin = procStart; callInstruction.procEnd = procEnd; } // generate return instructions // first three return instructions are for normal completion, return statement call completion and unchecked exception throwing completion resp. // normal completion myCurrentFlow.addInstruction(new ReturnInstruction(0, myStack, normalCompletion)); // return statement call completion myCurrentFlow.addInstruction(new ReturnInstruction(procStart - 3, myStack, returnCompletion)); // unchecked exception throwing completion myCurrentFlow.addInstruction(new ReturnInstruction(procStart - 1, myStack, throwExceptionCompletion)); // checked exception throwing completion. need to dispatch to the correct catch clause final List<PsiElement> unhandledExceptionCatchBlocks = finallyBlockToUnhandledExceptions.remove(finallyBlock); for (int i = 0; unhandledExceptionCatchBlocks != null && i < unhandledExceptionCatchBlocks.size(); i++) { ProgressManager.checkCanceled(); PsiElement catchBlock = unhandledExceptionCatchBlocks.get(i); final ReturnInstruction returnInstruction = new ReturnInstruction(0, myStack, throwExceptionCompletion); returnInstruction.setRethrowFromFinally(); myCurrentFlow.addInstruction(returnInstruction); if (catchBlock == null) { // dispatch to rethrowing exception code returnInstruction.offset = procStart - 1; } else { // dispatch to catch clause returnInstruction.offset--; // -1 for catch block init parameter instruction addElementOffsetLater(catchBlock, true); } } // here generated rethrowing code for unchecked exceptions gotoUncheckedRethrow.offset = myCurrentFlow.getSize(); generateUncheckedExceptionJumps(statement, false); // just in case myCurrentFlow.addInstruction(new ThrowToInstruction(0)); addElementOffsetLater(myCodeFragment, false); } finishElement(statement); } @Override public void visitResourceList(final PsiResourceList resourceList) { startElement(resourceList); for (PsiResourceListElement resource : resourceList) { ProgressManager.checkCanceled(); if (resource instanceof PsiResourceVariable) { processVariable((PsiVariable)resource); } else if (resource instanceof PsiResourceExpression) { ((PsiResourceExpression)resource).getExpression().accept(this); } } finishElement(resourceList); } @Override public void visitWhileStatement(PsiWhileStatement statement) { startElement(statement); PsiStatement body = statement.getBody(); if (body == null) { myStartStatementStack.pushStatement(statement, false); } else { myStartStatementStack.pushStatement(body, true); } myEndStatementStack.pushStatement(statement, false); PsiExpression condition = statement.getCondition(); if (condition != null) { condition.accept(this); } Object loopCondition = myConstantEvaluationHelper.computeConstantExpression(statement.getCondition()); if (loopCondition instanceof Boolean) { boolean value = ((Boolean)loopCondition).booleanValue(); if (value) { emitEmptyInstruction(); } else { myCurrentFlow.addInstruction(new GoToInstruction(0)); addElementOffsetLater(statement, false); } } else { Instruction instruction = new ConditionalGoToInstruction(0, statement.getCondition()); myCurrentFlow.addInstruction(instruction); addElementOffsetLater(statement, false); } if (body != null) { body.accept(this); } int offset = myCurrentFlow.getStartOffset(statement); Instruction instruction = new GoToInstruction(offset); myCurrentFlow.addInstruction(instruction); myStartStatementStack.popStatement(); myEndStatementStack.popStatement(); finishElement(statement); } @Override public void visitExpressionList(PsiExpressionList list) { PsiExpression[] expressions = list.getExpressions(); for (final PsiExpression expression : expressions) { ProgressManager.checkCanceled(); myStartStatementStack.pushStatement(expression, false); myEndStatementStack.pushStatement(expression, false); expression.accept(this); myStartStatementStack.popStatement(); myEndStatementStack.popStatement(); } } @Override public void visitArrayAccessExpression(PsiArrayAccessExpression expression) { startElement(expression); expression.getArrayExpression().accept(this); final PsiExpression indexExpression = expression.getIndexExpression(); if (indexExpression != null) { indexExpression.accept(this); } finishElement(expression); } @Override public void visitArrayInitializerExpression(PsiArrayInitializerExpression expression) { startElement(expression); PsiExpression[] initializers = expression.getInitializers(); for (PsiExpression initializer : initializers) { ProgressManager.checkCanceled(); initializer.accept(this); } finishElement(expression); } @Override public void visitAssignmentExpression(PsiAssignmentExpression expression) { startElement(expression); PsiExpression rExpr = expression.getRExpression(); myStartStatementStack.pushStatement(rExpr == null ? expression : rExpr, false); myEndStatementStack.pushStatement(rExpr == null ? expression : rExpr, false); PsiExpression lExpr = PsiUtil.skipParenthesizedExprDown(expression.getLExpression()); if (lExpr instanceof PsiReferenceExpression) { PsiVariable variable = getUsedVariable((PsiReferenceExpression)lExpr); if (variable != null) { if (myAssignmentTargetsAreElements) { startElement(lExpr); } PsiExpression qualifier = ((PsiReferenceExpression)lExpr).getQualifierExpression(); if (qualifier != null) { qualifier.accept(this); } if (expression.getOperationTokenType() != JavaTokenType.EQ) { generateReadInstruction(variable); } if (rExpr != null) { rExpr.accept(this); } generateWriteInstruction(variable); if (myAssignmentTargetsAreElements) finishElement(lExpr); } else { if (rExpr != null) { rExpr.accept(this); } lExpr.accept(this); //? } } else if (lExpr instanceof PsiArrayAccessExpression && ((PsiArrayAccessExpression)lExpr).getArrayExpression() instanceof PsiReferenceExpression){ PsiVariable variable = getUsedVariable((PsiReferenceExpression)((PsiArrayAccessExpression)lExpr).getArrayExpression()); if (variable != null) { generateReadInstruction(variable); final PsiExpression indexExpression = ((PsiArrayAccessExpression)lExpr).getIndexExpression(); if (indexExpression != null) { indexExpression.accept(this); } } else { lExpr.accept(this); } if (rExpr != null) { rExpr.accept(this); } } else if (lExpr != null) { lExpr.accept(this); if (rExpr != null) { rExpr.accept(this); } } myStartStatementStack.popStatement(); myEndStatementStack.popStatement(); finishElement(expression); } private enum Shortcut { NO_SHORTCUT, // a || b SKIP_CURRENT_OPERAND, // false || a STOP_EXPRESSION // true || a } @Override public void visitPolyadicExpression(PsiPolyadicExpression expression) { startElement(expression); IElementType signTokenType = expression.getOperationTokenType(); boolean isAndAnd = signTokenType == JavaTokenType.ANDAND; boolean isOrOr = signTokenType == JavaTokenType.OROR; PsiExpression[] operands = expression.getOperands(); Boolean lValue = isAndAnd; PsiExpression lOperand = null; Boolean rValue = null; for (int i = 0; i < operands.length; i++) { PsiExpression rOperand = operands[i]; if ((isAndAnd || isOrOr) && myEnabledShortCircuit) { Object exprValue = myConstantEvaluationHelper.computeConstantExpression(rOperand); if (exprValue instanceof Boolean) { myCurrentFlow.setConstantConditionOccurred(true); rValue = shouldCalculateConstantExpression(expression) ? (Boolean)exprValue : null; } BranchingInstruction.Role role = isAndAnd ? myEndJumpRoles.peek() : myStartJumpRoles.peek(); PsiElement gotoElement = isAndAnd ? myEndStatementStack.peekElement() : myStartStatementStack.peekElement(); boolean gotoIsAtStart = isAndAnd ? myEndStatementStack.peekAtStart() : myStartStatementStack.peekAtStart(); Shortcut shortcut; if (lValue != null) { shortcut = lValue.booleanValue() == isOrOr ? Shortcut.STOP_EXPRESSION : Shortcut.SKIP_CURRENT_OPERAND; } else if (rValue != null && rValue.booleanValue() == isOrOr) { shortcut = Shortcut.STOP_EXPRESSION; } else { shortcut = Shortcut.NO_SHORTCUT; } switch (shortcut) { case NO_SHORTCUT: assert lOperand != null; myCurrentFlow.addInstruction(new ConditionalGoToInstruction(0, role, lOperand)); addElementOffsetLater(gotoElement, gotoIsAtStart); break; case STOP_EXPRESSION: if (lOperand != null) { myCurrentFlow.addInstruction(new GoToInstruction(0, role)); addElementOffsetLater(gotoElement, gotoIsAtStart); } break; case SKIP_CURRENT_OPERAND: break; } if (shortcut == Shortcut.STOP_EXPRESSION) break; } generateLOperand(rOperand, i == operands.length - 1 ? null : operands[i + 1], signTokenType); lOperand = rOperand; lValue = rValue; } finishElement(expression); } private void generateLOperand(@NotNull PsiExpression lOperand, @Nullable PsiExpression rOperand, @NotNull IElementType signTokenType) { if (rOperand != null) { myStartJumpRoles.push(BranchingInstruction.Role.END); myEndJumpRoles.push(BranchingInstruction.Role.END); PsiElement then = signTokenType == JavaTokenType.OROR ? myStartStatementStack.peekElement() : rOperand; boolean thenAtStart = signTokenType != JavaTokenType.OROR || myStartStatementStack.peekAtStart(); myStartStatementStack.pushStatement(then, thenAtStart); PsiElement elseS = signTokenType == JavaTokenType.ANDAND ? myEndStatementStack.peekElement() : rOperand; boolean elseAtStart = signTokenType != JavaTokenType.ANDAND || myEndStatementStack.peekAtStart(); myEndStatementStack.pushStatement(elseS, elseAtStart); } lOperand.accept(this); if (rOperand != null) { myStartStatementStack.popStatement(); myEndStatementStack.popStatement(); myStartJumpRoles.pop(); myEndJumpRoles.pop(); } } private static boolean isInsideIfCondition(@NotNull PsiExpression expression) { PsiElement element = expression; while (element instanceof PsiExpression) { final PsiElement parent = element.getParent(); if (parent instanceof PsiIfStatement && element == ((PsiIfStatement)parent).getCondition()) return true; element = parent; } return false; } private boolean shouldCalculateConstantExpression(@NotNull PsiExpression expression) { return myEvaluateConstantIfCondition || !isInsideIfCondition(expression); } @Override public void visitClassObjectAccessExpression(PsiClassObjectAccessExpression expression) { visitChildren(expression); } private void visitChildren(@NotNull PsiElement element) { startElement(element); PsiElement[] children = element.getChildren(); for (PsiElement child : children) { ProgressManager.checkCanceled(); child.accept(this); } finishElement(element); } @Override public void visitConditionalExpression(PsiConditionalExpression expression) { startElement(expression); final PsiExpression condition = expression.getCondition(); final PsiExpression thenExpression = expression.getThenExpression(); final PsiExpression elseExpression = expression.getElseExpression(); generateConditionalStatementInstructions(expression, condition, thenExpression, elseExpression); finishElement(expression); } @Override public void visitInstanceOfExpression(PsiInstanceOfExpression expression) { startElement(expression); final PsiExpression operand = expression.getOperand(); operand.accept(this); finishElement(expression); } @Override public void visitLiteralExpression(PsiLiteralExpression expression) { startElement(expression); finishElement(expression); } @Override public void visitLambdaExpression(PsiLambdaExpression expression) { startElement(expression); final PsiElement body = expression.getBody(); if (body != null) { List<PsiVariable> array = new ArrayList<>(); addUsedVariables(array, body); for (PsiVariable var : array) { ProgressManager.checkCanceled(); generateReadInstruction(var); } } finishElement(expression); } @Override public void visitMethodCallExpression(PsiMethodCallExpression expression) { startElement(expression); final PsiReferenceExpression methodExpression = expression.getMethodExpression(); methodExpression.accept(this); final PsiExpressionList argumentList = expression.getArgumentList(); argumentList.accept(this); // just to increase counter - there is some executable code here emitEmptyInstruction(); generateCheckedExceptionJumps(expression); finishElement(expression); } @Override public void visitNewExpression(PsiNewExpression expression) { startElement(expression); int pc = myCurrentFlow.getSize(); PsiElement[] children = expression.getChildren(); for (PsiElement child : children) { ProgressManager.checkCanceled(); child.accept(this); } generateCheckedExceptionJumps(expression); if (pc == myCurrentFlow.getSize()) { // generate at least one instruction for constructor call emitEmptyInstruction(); } finishElement(expression); } @Override public void visitParenthesizedExpression(PsiParenthesizedExpression expression) { visitChildren(expression); } @Override public void visitPostfixExpression(PsiPostfixExpression expression) { startElement(expression); IElementType op = expression.getOperationTokenType(); PsiExpression operand = PsiUtil.skipParenthesizedExprDown(expression.getOperand()); if (operand != null) { operand.accept(this); if (op == JavaTokenType.PLUSPLUS || op == JavaTokenType.MINUSMINUS) { if (operand instanceof PsiReferenceExpression) { PsiVariable variable = getUsedVariable((PsiReferenceExpression)operand); if (variable != null) { generateWriteInstruction(variable); } } } } finishElement(expression); } @Override public void visitPrefixExpression(PsiPrefixExpression expression) { startElement(expression); PsiExpression operand = PsiUtil.skipParenthesizedExprDown(expression.getOperand()); if (operand != null) { IElementType operationSign = expression.getOperationTokenType(); if (operationSign == JavaTokenType.EXCL) { // negation inverts jump targets PsiElement topStartStatement = myStartStatementStack.peekElement(); boolean topAtStart = myStartStatementStack.peekAtStart(); myStartStatementStack.pushStatement(myEndStatementStack.peekElement(), myEndStatementStack.peekAtStart()); myEndStatementStack.pushStatement(topStartStatement, topAtStart); } operand.accept(this); if (operationSign == JavaTokenType.EXCL) { // negation inverts jump targets myStartStatementStack.popStatement(); myEndStatementStack.popStatement(); } if (operand instanceof PsiReferenceExpression && (operationSign == JavaTokenType.PLUSPLUS || operationSign == JavaTokenType.MINUSMINUS)) { PsiVariable variable = getUsedVariable((PsiReferenceExpression)operand); if (variable != null) { generateWriteInstruction(variable); } } } finishElement(expression); } @Override public void visitReferenceExpression(PsiReferenceExpression expression) { startElement(expression); PsiExpression qualifier = expression.getQualifierExpression(); if (qualifier != null) { qualifier.accept(this); } PsiVariable variable = getUsedVariable(expression); if (variable != null) { generateReadInstruction(variable); } finishElement(expression); } @Override public void visitSuperExpression(PsiSuperExpression expression) { startElement(expression); finishElement(expression); } @Override public void visitThisExpression(PsiThisExpression expression) { startElement(expression); finishElement(expression); } @Override public void visitTypeCastExpression(PsiTypeCastExpression expression) { startElement(expression); PsiExpression operand = expression.getOperand(); if (operand != null) { operand.accept(this); } finishElement(expression); } @Override public void visitClass(PsiClass aClass) { startElement(aClass); // anonymous or local class if (aClass instanceof PsiAnonymousClass) { final PsiElement arguments = PsiTreeUtil.getChildOfType(aClass, PsiExpressionList.class); if (arguments != null) arguments.accept(this); } List<PsiVariable> array = new ArrayList<>(); addUsedVariables(array, aClass); for (PsiVariable var : array) { ProgressManager.checkCanceled(); generateReadInstruction(var); } finishElement(aClass); } private void addUsedVariables(@NotNull List<PsiVariable> array, @NotNull PsiElement scope) { if (scope instanceof PsiReferenceExpression) { PsiVariable variable = getUsedVariable((PsiReferenceExpression)scope); if (variable != null) { if (!array.contains(variable)) { array.add(variable); } } } PsiElement[] children = scope.getChildren(); for (PsiElement child : children) { ProgressManager.checkCanceled(); addUsedVariables(array, child); } } private void generateReadInstruction(@NotNull PsiVariable variable) { Instruction instruction = new ReadVariableInstruction(variable); myCurrentFlow.addInstruction(instruction); } private void generateWriteInstruction(@NotNull PsiVariable variable) { Instruction instruction = new WriteVariableInstruction(variable); myCurrentFlow.addInstruction(instruction); } @Nullable private PsiVariable getUsedVariable(@NotNull PsiReferenceExpression refExpr) { if (refExpr.getParent() instanceof PsiMethodCallExpression) return null; return myPolicy.getUsedVariable(refExpr); } private static class FinallyBlockSubroutine { private final PsiElement myElement; private final List<CallInstruction> myCalls; public FinallyBlockSubroutine(@NotNull PsiElement element) { myElement = element; myCalls = new ArrayList<>(); } @NotNull public PsiElement getElement() { return myElement; } @NotNull public List<CallInstruction> getCalls() { return myCalls; } private void addCall(@NotNull CallInstruction callInstruction) { myCalls.add(callInstruction); } } }
apache-2.0
jexp/idea2
java/idea-ui/src/com/intellij/openapi/roots/ui/configuration/ModulesAlphaComparator.java
1065
/* * Copyright 2000-2009 JetBrains s.r.o. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.intellij.openapi.roots.ui.configuration; import com.intellij.openapi.module.Module; import java.util.Comparator; /** * @author Eugene Zhuravlev * Date: Dec 1 * @author 2003 */ public class ModulesAlphaComparator implements Comparator<Module>{ public int compare(Module module1, Module module2) { final String name1 = module1.getName(); final String name2 = module2.getName(); return name1.compareToIgnoreCase(name2); } }
apache-2.0
robsoncardosoti/flowable-engine
modules/flowable-idm-engine/src/main/java/org/flowable/idm/engine/impl/cmd/ExecuteCustomSqlCmd.java
911
package org.flowable.idm.engine.impl.cmd; import org.flowable.engine.common.impl.cmd.CustomSqlExecution; import org.flowable.idm.engine.impl.interceptor.Command; import org.flowable.idm.engine.impl.interceptor.CommandContext; /** * @author jbarrez */ public class ExecuteCustomSqlCmd<Mapper, ResultType> implements Command<ResultType> { protected Class<Mapper> mapperClass; protected CustomSqlExecution<Mapper, ResultType> customSqlExecution; public ExecuteCustomSqlCmd(Class<Mapper> mapperClass, CustomSqlExecution<Mapper, ResultType> customSqlExecution) { this.mapperClass = mapperClass; this.customSqlExecution = customSqlExecution; } @Override public ResultType execute(CommandContext commandContext) { Mapper mapper = commandContext.getDbSqlSession().getSqlSession().getMapper(mapperClass); return customSqlExecution.execute(mapper); } }
apache-2.0
kdvolder/spring-boot
spring-boot-project/spring-boot-actuator-autoconfigure/src/main/java/org/springframework/boot/actuate/autoconfigure/mongo/MongoReactiveHealthIndicatorAutoConfiguration.java
2799
/* * Copyright 2012-2019 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 * * https://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.boot.actuate.autoconfigure.mongo; import java.util.Map; import reactor.core.publisher.Flux; import org.springframework.boot.actuate.autoconfigure.health.CompositeReactiveHealthIndicatorConfiguration; import org.springframework.boot.actuate.autoconfigure.health.ConditionalOnEnabledHealthIndicator; import org.springframework.boot.actuate.autoconfigure.health.HealthIndicatorAutoConfiguration; import org.springframework.boot.actuate.health.ReactiveHealthIndicator; import org.springframework.boot.actuate.mongo.MongoReactiveHealthIndicator; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.AutoConfigureBefore; import org.springframework.boot.autoconfigure.EnableAutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnClass; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.data.mongo.MongoReactiveDataAutoConfiguration; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.data.mongodb.core.ReactiveMongoTemplate; /** * {@link EnableAutoConfiguration Auto-configuration} for * {@link MongoReactiveHealthIndicator}. * * @author Stephane Nicoll * @since 2.1.0 */ @Configuration(proxyBeanMethods = false) @ConditionalOnClass({ ReactiveMongoTemplate.class, Flux.class }) @ConditionalOnBean(ReactiveMongoTemplate.class) @ConditionalOnEnabledHealthIndicator("mongo") @AutoConfigureBefore(HealthIndicatorAutoConfiguration.class) @AutoConfigureAfter(MongoReactiveDataAutoConfiguration.class) public class MongoReactiveHealthIndicatorAutoConfiguration extends CompositeReactiveHealthIndicatorConfiguration<MongoReactiveHealthIndicator, ReactiveMongoTemplate> { @Bean @ConditionalOnMissingBean(name = "mongoHealthIndicator") public ReactiveHealthIndicator mongoHealthIndicator( Map<String, ReactiveMongoTemplate> reactiveMongoTemplates) { return createHealthIndicator(reactiveMongoTemplates); } }
apache-2.0
GoogleCloudPlatform/appengine-tck
tests/appengine-tck-capability/src/test/java/com/google/appengine/tck/capability/CapabilityTest.java
3341
/* * Copyright 2013 Google Inc. All Rights Reserved. * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.appengine.tck.capability; import com.google.appengine.api.capabilities.CapabilitiesService; import com.google.appengine.api.capabilities.CapabilitiesServiceFactory; import com.google.appengine.api.capabilities.Capability; import com.google.appengine.api.capabilities.CapabilityState; import com.google.appengine.api.capabilities.CapabilityStatus; import com.google.appengine.api.utils.SystemProperty; import com.google.appengine.tck.base.TestBase; import org.jboss.arquillian.container.test.api.Deployment; import org.jboss.arquillian.junit.Arquillian; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import static org.junit.Assert.assertEquals; /** * Tests for capability service. * * @author hchen@google.com (Hannah Chen) */ @RunWith(Arquillian.class) public class CapabilityTest extends TestBase { private CapabilitiesService capabilitiesService; private String[] TEST_DATA = {"blobstore", "datastore_v3", "datastore_v3,write", "images", "mail", "memcache", "taskqueue", "urlfetch", "xmpp"}; @Before public void setUp() { capabilitiesService = CapabilitiesServiceFactory.getCapabilitiesService(); } @Deployment public static WebArchive getDeployment() { WebArchive war = getTckDeployment(); war.addAsWebInfResource(new StringAsset("capability"), "dummy.txt"); return war; } @Test public void testGetStatus() { Capability capability; for (String p : TEST_DATA) { if (p.indexOf(',') > 0) { String in[] = p.split(","); capability = new Capability(in[0], in[1]); p = in[0]; } else { capability = new Capability(p); } CapabilityState cState = capabilitiesService.getStatus(capability); assertEquals(p, cState.getCapability().getPackageName()); assertEquals(CapabilityStatus.ENABLED, cState.getStatus()); } } /** * check unknown service. */ @Test public void testDummyService() { // only check this in appserver since everything in dev_appserver has ENABLED status. if (SystemProperty.environment.value() == SystemProperty.Environment.Value.Production) { String pName = "dummy"; Capability capability = new Capability(pName); CapabilityState cState = capabilitiesService.getStatus(capability); assertEquals(pName, cState.getCapability().getPackageName()); assertEquals(CapabilityStatus.UNKNOWN, cState.getStatus()); } } }
apache-2.0
gocd/gocd
api/api-plugin-infos-v7/src/test/groovy/com/thoughtworks/go/apiv7/plugininfos/representers/MetadataRepresenterResolverTest.java
1891
/* * Copyright 2022 ThoughtWorks, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.thoughtworks.go.apiv7.plugininfos.representers; import com.thoughtworks.go.apiv7.plugininfos.representers.metadata.MetadataRepresenter; import com.thoughtworks.go.apiv7.plugininfos.representers.metadata.MetadataWithPartOfIdentityRepresenter; import com.thoughtworks.go.apiv7.plugininfos.representers.metadata.PackageMaterialMetadataRepresenter; import com.thoughtworks.go.plugin.domain.common.MetadataWithPartOfIdentity; import com.thoughtworks.go.plugin.domain.common.PackageMaterialMetadata; import org.junit.jupiter.api.Test; import static org.assertj.core.api.Assertions.assertThat; class MetadataRepresenterResolverTest { @Test void shouldResolveMetadataRepresenterForPackageMaterialMetadata() { MetadataRepresenter representer = MetadataRepresenterResolver.resolve(new PackageMaterialMetadata(false, true, false, "foo", 1)); assertThat(representer).isOfAnyClassIn(PackageMaterialMetadataRepresenter.class); } @Test void shouldResolveMetadataRepresenterForMetadataWithPartOfIdentityRepresenter() { MetadataRepresenter representer = MetadataRepresenterResolver.resolve(new MetadataWithPartOfIdentity(false, false, false)); assertThat(representer).isOfAnyClassIn(MetadataWithPartOfIdentityRepresenter.class); } }
apache-2.0
punkhorn/camel-upstream
core/camel-core/src/main/java/org/apache/camel/processor/aggregate/ClosedCorrelationKeyException.java
1748
/** * 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.camel.processor.aggregate; import org.apache.camel.CamelExchangeException; import org.apache.camel.Exchange; /** * The correlation key has been closed and the Exchange cannot be aggregated. */ public class ClosedCorrelationKeyException extends CamelExchangeException { private static final long serialVersionUID = 1L; private final String correlationKey; public ClosedCorrelationKeyException(String correlationKey, Exchange exchange) { super("The correlation key [" + correlationKey + "] has been closed", exchange); this.correlationKey = correlationKey; } public ClosedCorrelationKeyException(String correlationKey, Exchange exchange, Throwable cause) { super("The correlation key [" + correlationKey + "] has been closed", exchange, cause); this.correlationKey = correlationKey; } public String getCorrelationKey() { return correlationKey; } }
apache-2.0
spring-cloud/spring-cloud-task
spring-cloud-starter-single-step-batch-job/src/main/java/org/springframework/cloud/task/batch/autoconfigure/flatfile/FlatFileItemReaderAutoConfiguration.java
5133
/* * Copyright 2019-2021 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 * * https://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.cloud.task.batch.autoconfigure.flatfile; import java.util.HashMap; import java.util.Map; import org.springframework.batch.item.file.FlatFileItemReader; import org.springframework.batch.item.file.LineCallbackHandler; import org.springframework.batch.item.file.LineMapper; import org.springframework.batch.item.file.builder.FlatFileItemReaderBuilder; import org.springframework.batch.item.file.mapping.FieldSetMapper; import org.springframework.batch.item.file.separator.RecordSeparatorPolicy; import org.springframework.batch.item.file.transform.FieldSet; import org.springframework.batch.item.file.transform.LineTokenizer; import org.springframework.batch.item.file.transform.Range; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.AutoConfigureAfter; import org.springframework.boot.autoconfigure.batch.BatchAutoConfiguration; import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean; import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty; import org.springframework.boot.context.properties.EnableConfigurationProperties; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; /** * Autconfiguration for a {@code FlatFileItemReader}. * * @author Michael Minella * @author Glenn Renfro * @since 2.3 */ @Configuration(proxyBeanMethods = false) @EnableConfigurationProperties(FlatFileItemReaderProperties.class) @AutoConfigureAfter(BatchAutoConfiguration.class) public class FlatFileItemReaderAutoConfiguration { private final FlatFileItemReaderProperties properties; public FlatFileItemReaderAutoConfiguration(FlatFileItemReaderProperties properties) { this.properties = properties; } @Bean @ConditionalOnMissingBean @ConditionalOnProperty(prefix = "spring.batch.job.flatfileitemreader", name = "name") public FlatFileItemReader<Map<String, Object>> itemReader( @Autowired(required = false) LineTokenizer lineTokenizer, @Autowired(required = false) FieldSetMapper<Map<String, Object>> fieldSetMapper, @Autowired(required = false) LineMapper<Map<String, Object>> lineMapper, @Autowired(required = false) LineCallbackHandler skippedLinesCallback, @Autowired(required = false) RecordSeparatorPolicy recordSeparatorPolicy) { FlatFileItemReaderBuilder<Map<String, Object>> mapFlatFileItemReaderBuilder = new FlatFileItemReaderBuilder<Map<String, Object>>() .name(this.properties.getName()).resource(this.properties.getResource()) .saveState(this.properties.isSaveState()) .maxItemCount(this.properties.getMaxItemCount()) .currentItemCount(this.properties.getCurrentItemCount()) .strict(this.properties.isStrict()) .encoding(this.properties.getEncoding()) .linesToSkip(this.properties.getLinesToSkip()) .comments(this.properties.getComments() .toArray(new String[this.properties.getComments().size()])); mapFlatFileItemReaderBuilder.lineTokenizer(lineTokenizer); if (recordSeparatorPolicy != null) { mapFlatFileItemReaderBuilder .recordSeparatorPolicy(recordSeparatorPolicy); } mapFlatFileItemReaderBuilder.fieldSetMapper(fieldSetMapper); mapFlatFileItemReaderBuilder.lineMapper(lineMapper); mapFlatFileItemReaderBuilder.skippedLinesCallback(skippedLinesCallback); if (this.properties.isDelimited()) { mapFlatFileItemReaderBuilder.delimited() .quoteCharacter(this.properties.getQuoteCharacter()) .delimiter(this.properties.getDelimiter()) .includedFields( this.properties.getIncludedFields().toArray(new Integer[0])) .names(this.properties.getNames()) .beanMapperStrict(this.properties.isParsingStrict()) .fieldSetMapper(new MapFieldSetMapper()); } else if (this.properties.isFixedLength()) { mapFlatFileItemReaderBuilder.fixedLength() .columns(this.properties.getRanges().toArray(new Range[0])) .names(this.properties.getNames()) .fieldSetMapper(new MapFieldSetMapper()) .beanMapperStrict(this.properties.isParsingStrict()); } return mapFlatFileItemReaderBuilder.build(); } /** * A {@link FieldSetMapper} that takes a {@code FieldSet} and returns the * {@code Map<String, Object>} of its contents. */ public static class MapFieldSetMapper implements FieldSetMapper<Map<String, Object>> { @Override public Map<String, Object> mapFieldSet(FieldSet fieldSet) { return new HashMap<String, Object>((Map) fieldSet.getProperties()); } } }
apache-2.0
google/volley
core/src/main/java/com/android/volley/toolbox/HttpStack.java
1736
/* * Copyright (C) 2011 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.volley.toolbox; import com.android.volley.AuthFailureError; import com.android.volley.Request; import java.io.IOException; import java.util.Map; import org.apache.http.HttpResponse; /** * An HTTP stack abstraction. * * @deprecated This interface should be avoided as it depends on the deprecated Apache HTTP library. * Use {@link BaseHttpStack} to avoid this dependency. This class may be removed in a future * release of Volley. */ @Deprecated public interface HttpStack { /** * Performs an HTTP request with the given parameters. * * <p>A GET request is sent if request.getPostBody() == null. A POST request is sent otherwise, * and the Content-Type header is set to request.getPostBodyContentType(). * * @param request the request to perform * @param additionalHeaders additional headers to be sent together with {@link * Request#getHeaders()} * @return the HTTP response */ HttpResponse performRequest(Request<?> request, Map<String, String> additionalHeaders) throws IOException, AuthFailureError; }
apache-2.0
rLadia/AttacknidPatch
Attacknids/src/org/anddev/andengine/opengl/texture/region/buffer/BaseTextureRegionBuffer.java
4226
package org.anddev.andengine.opengl.texture.region.buffer; import static org.anddev.andengine.opengl.vertex.RectangleVertexBuffer.VERTICES_PER_RECTANGLE; import org.anddev.andengine.opengl.buffer.BufferObject; import org.anddev.andengine.opengl.texture.Texture; import org.anddev.andengine.opengl.texture.region.BaseTextureRegion; import org.anddev.andengine.opengl.util.FastFloatBuffer; /** * @author Nicolas Gramlich * @since 19:05:50 - 09.03.2010 */ public abstract class BaseTextureRegionBuffer extends BufferObject { // =========================================================== // Constants // =========================================================== // =========================================================== // Fields // =========================================================== protected final BaseTextureRegion mTextureRegion; private boolean mFlippedVertical; private boolean mFlippedHorizontal; // =========================================================== // Constructors // =========================================================== public BaseTextureRegionBuffer(final BaseTextureRegion pBaseTextureRegion, final int pDrawType) { super(2 * VERTICES_PER_RECTANGLE, pDrawType); this.mTextureRegion = pBaseTextureRegion; } // =========================================================== // Getter & Setter // =========================================================== public BaseTextureRegion getTextureRegion() { return this.mTextureRegion; } public boolean isFlippedHorizontal() { return this.mFlippedHorizontal; } public void setFlippedHorizontal(final boolean pFlippedHorizontal) { if(this.mFlippedHorizontal != pFlippedHorizontal) { this.mFlippedHorizontal = pFlippedHorizontal; this.update(); } } public boolean isFlippedVertical() { return this.mFlippedVertical; } public void setFlippedVertical(final boolean pFlippedVertical) { if(this.mFlippedVertical != pFlippedVertical) { this.mFlippedVertical = pFlippedVertical; this.update(); } } // =========================================================== // Methods for/from SuperClass/Interfaces // =========================================================== protected abstract float getX1(); protected abstract float getY1(); protected abstract float getX2(); protected abstract float getY2(); // =========================================================== // Methods // =========================================================== public synchronized void update() { final BaseTextureRegion textureRegion = this.mTextureRegion; final Texture texture = textureRegion.getTexture(); if(texture == null) { return; } final int x1 = Float.floatToRawIntBits(this.getX1()); final int y1 = Float.floatToRawIntBits(this.getY1()); final int x2 = Float.floatToRawIntBits(this.getX2()); final int y2 = Float.floatToRawIntBits(this.getY2()); final int[] bufferData = this.mBufferData; if(this.mFlippedVertical) { if(this.mFlippedHorizontal) { bufferData[0] = x2; bufferData[1] = y2; bufferData[2] = x2; bufferData[3] = y1; bufferData[4] = x1; bufferData[5] = y2; bufferData[6] = x1; bufferData[7] = y1; } else { bufferData[0] = x1; bufferData[1] = y2; bufferData[2] = x1; bufferData[3] = y1; bufferData[4] = x2; bufferData[5] = y2; bufferData[6] = x2; bufferData[7] = y1; } } else { if(this.mFlippedHorizontal) { bufferData[0] = x2; bufferData[1] = y1; bufferData[2] = x2; bufferData[3] = y2; bufferData[4] = x1; bufferData[5] = y1; bufferData[6] = x1; bufferData[7] = y2; } else { bufferData[0] = x1; bufferData[1] = y1; bufferData[2] = x1; bufferData[3] = y2; bufferData[4] = x2; bufferData[5] = y1; bufferData[6] = x2; bufferData[7] = y2; } } final FastFloatBuffer buffer = this.getFloatBuffer(); buffer.position(0); buffer.put(bufferData); buffer.position(0); super.setHardwareBufferNeedsUpdate(); } // =========================================================== // Inner and Anonymous Classes // =========================================================== }
apache-2.0
srijeyanthan/hops
hadoop-hdfs-project/hadoop-hdfs/src/test/java/org/apache/hadoop/hdfs/TestModTime.java
8117
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hdfs; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.fs.CommonConfigurationKeys; import org.apache.hadoop.fs.FSDataOutputStream; import org.apache.hadoop.fs.FileStatus; import org.apache.hadoop.fs.FileSystem; import org.apache.hadoop.fs.Path; import org.apache.hadoop.hdfs.protocol.DatanodeInfo; import org.apache.hadoop.hdfs.protocol.HdfsConstants.DatanodeReportType; import org.apache.hadoop.util.ThreadUtil; import org.junit.Test; import java.io.IOException; import java.io.OutputStream; import java.net.InetSocketAddress; import java.util.Random; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; /** * This class tests the decommissioning of nodes. */ public class TestModTime { static final long seed = 0xDEADBEEFL; static final int blockSize = 8192; static final int fileSize = 16384; static final int numDatanodes = 6; Random myrand = new Random(); Path hostsFile; Path excludeFile; private void writeFile(FileSystem fileSys, Path name, int repl) throws IOException { // create and write a file that contains three blocks of data FSDataOutputStream stm = fileSys.create(name, true, fileSys.getConf() .getInt(CommonConfigurationKeys.IO_FILE_BUFFER_SIZE_KEY, 4096), (short) repl, blockSize); byte[] buffer = new byte[fileSize]; Random rand = new Random(seed); rand.nextBytes(buffer); stm.write(buffer); stm.close(); } private void cleanupFile(FileSystem fileSys, Path name) throws IOException { assertTrue(fileSys.exists(name)); fileSys.delete(name, true); assertTrue(!fileSys.exists(name)); } private void printDatanodeReport(DatanodeInfo[] info) { System.out.println("-------------------------------------------------"); for (int i = 0; i < info.length; i++) { System.out.println(info[i].getDatanodeReport()); System.out.println(); } } /** * Tests modification time in DFS. */ @Test public void testModTime() throws IOException { Configuration conf = new HdfsConfiguration(); MiniDFSCluster cluster = new MiniDFSCluster.Builder(conf).numDataNodes(numDatanodes).build(); cluster.waitActive(); InetSocketAddress addr = new InetSocketAddress("localhost", cluster.getNameNodePort()); DFSClient client = new DFSClient(addr, conf); DatanodeInfo[] info = client.datanodeReport(DatanodeReportType.LIVE); assertEquals("Number of Datanodes ", numDatanodes, info.length); FileSystem fileSys = cluster.getFileSystem(); int replicas = numDatanodes - 1; assertTrue(fileSys instanceof DistributedFileSystem); try { // // create file and record ctime and mtime of test file // System.out.println("Creating testdir1 and testdir1/test1.dat."); Path dir1 = new Path("testdir1"); Path file1 = new Path(dir1, "test1.dat"); writeFile(fileSys, file1, replicas); FileStatus stat = fileSys.getFileStatus(file1); long mtime1 = stat.getModificationTime(); assertTrue(mtime1 != 0); // // record dir times // stat = fileSys.getFileStatus(dir1); long mdir1 = stat.getModificationTime(); // // create second test file // System.out.println("Creating testdir1/test2.dat."); Path file2 = new Path(dir1, "test2.dat"); writeFile(fileSys, file2, replicas); stat = fileSys.getFileStatus(file2); // // verify that mod time of dir remains the same // as before. modification time of directory has increased. // stat = fileSys.getFileStatus(dir1); assertTrue(stat.getModificationTime() >= mdir1); mdir1 = stat.getModificationTime(); // // create another directory // Path dir2 = fileSys.makeQualified(new Path("testdir2/")); System.out.println("Creating testdir2 " + dir2); assertTrue(fileSys.mkdirs(dir2)); stat = fileSys.getFileStatus(dir2); long mdir2 = stat.getModificationTime(); // // rename file1 from testdir into testdir2 // Path newfile = new Path(dir2, "testnew.dat"); System.out.println("Moving " + file1 + " to " + newfile); fileSys.rename(file1, newfile); // // verify that modification time of file1 did not change. // stat = fileSys.getFileStatus(newfile); assertTrue(stat.getModificationTime() == mtime1); // // verify that modification time of testdir1 and testdir2 // were changed. // stat = fileSys.getFileStatus(dir1); assertTrue(stat.getModificationTime() != mdir1); mdir1 = stat.getModificationTime(); stat = fileSys.getFileStatus(dir2); assertTrue(stat.getModificationTime() != mdir2); mdir2 = stat.getModificationTime(); // // delete newfile // System.out.println("Deleting testdir2/testnew.dat."); assertTrue(fileSys.delete(newfile, true)); // // verify that modification time of testdir1 has not changed. // stat = fileSys.getFileStatus(dir1); assertTrue(stat.getModificationTime() == mdir1); // // verify that modification time of testdir2 has changed. // stat = fileSys.getFileStatus(dir2); assertTrue(stat.getModificationTime() != mdir2); mdir2 = stat.getModificationTime(); cleanupFile(fileSys, file2); cleanupFile(fileSys, dir1); cleanupFile(fileSys, dir2); } catch (IOException e) { info = client.datanodeReport(DatanodeReportType.ALL); printDatanodeReport(info); throw e; } finally { fileSys.close(); cluster.shutdown(); } } /** * Regression test for HDFS-3864 - NN does not update internal file mtime for * OP_CLOSE when reading from the edit log. */ @Test public void testModTimePersistsAfterRestart() throws IOException { final long sleepTime = 10; // 10 milliseconds MiniDFSCluster cluster = null; FileSystem fs = null; Configuration conf = new HdfsConfiguration(); try { cluster = new MiniDFSCluster.Builder(conf).build(); fs = cluster.getFileSystem(); Path testPath = new Path("/test"); // Open a file, and get its initial modification time. OutputStream out = fs.create(testPath); long initialModTime = fs.getFileStatus(testPath).getModificationTime(); assertTrue(initialModTime > 0); // Wait and then close the file. Ensure that the mod time goes up. ThreadUtil.sleepAtLeastIgnoreInterrupts(sleepTime); out.close(); long modTimeAfterClose = fs.getFileStatus(testPath).getModificationTime(); assertTrue(modTimeAfterClose >= initialModTime + sleepTime); // Restart the NN, and make sure that the later mod time is still used. cluster.restartNameNode(); long modTimeAfterRestart = fs.getFileStatus(testPath).getModificationTime(); assertEquals(modTimeAfterClose, modTimeAfterRestart); } finally { if (fs != null) { fs.close(); } if (cluster != null) { cluster.shutdown(); } } } public static void main(String[] args) throws Exception { new TestModTime().testModTime(); } }
apache-2.0
kzganesan/libgdx
extensions/gdx-setup/src/com/badlogic/gdx/setup/ProjectFile.java
1892
/******************************************************************************* * Copyright 2011 See AUTHORS file. * * 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.badlogic.gdx.setup; /** * A file in a {@link Project}, the resourceName specifies the location * of the template file, the outputName specifies the final name of the * file relative to its project, the isTemplate field specifies if * values need to be replaced in this file or not. * @author badlogic * */ public class ProjectFile { /** the name of the template resource, relative to com.badlogic.gdx.setup.resources **/ public String resourceName; /** the name of the output file, including directories, relative to the project dir **/ public String outputName; /** whehter to replace values in this file **/ public boolean isTemplate; public ProjectFile(String name) { this.resourceName = name; this.outputName = name; this.isTemplate = true; } public ProjectFile(String name, boolean isTemplate) { this.resourceName = name; this.outputName = name; this.isTemplate = isTemplate; } public ProjectFile(String resourceName, String outputName, boolean isTemplate) { this.resourceName = resourceName; this.outputName = outputName; this.isTemplate = isTemplate; } }
apache-2.0
apache/uima-uimaj
uimaj-core/src/main/java/org/apache/uima/cas/FeatureStructure.java
12287
/* * 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.uima.cas; import org.apache.uima.jcas.JCas; // @formatter:off /** * Interface for feature structures. * * This interface includes indirect getters and setters that use Feature object instances to specify * the feature. There are multiple versions of these, corresponding to the consolidated types of the * feature range. * * Here are the types: * FeatureStructure - reference to another Feature structure * String * float * int * byte * boolean * short * long * double */ //@formatter:on public interface FeatureStructure extends Cloneable { /** * Get the type of this FS. * * @return The type. */ Type getType(); /** * Set a feature value to another FS. * * @param feat * The feature whose value should be set. * @param fs * The value FS. * @exception CASRuntimeException * If there is a typing violation, i.e., if <code>feat</code> is not defined for the * type of this FS, or the range type of <code>feat</code> is not a supertype of * <code>fs.getType()</code>. */ void setFeatureValue(Feature feat, FeatureStructure fs) throws CASRuntimeException; /** * Get a feature value. * * @param feat * The feature whose value we want to get. * @return The value; may be <code>null</code> if the value has not been set. * @exception CASRuntimeException * If there is a typing violation, i.e., if <code>feat</code> is not defined for the * type of this FS, or the range type of <code>feat</code> is Float, Integer or * String. */ FeatureStructure getFeatureValue(Feature feat) throws CASRuntimeException; /** * Set the string value of a feature. * * @param feat * The feature whose value we want to set. * @param s * The string we're setting the feature to. * @exception CASRuntimeException * If there is a typing violation, i.e., if <code>feat</code> is not defined for * <code>this.getType()</code> or <code>feat.getRange()</code> is not * <code>CAS.STRING_TYPE</code>. */ void setStringValue(Feature feat, String s) throws CASRuntimeException; /** * Get the string value under a feature. * * @param f * The feature for which we want the value. * @return The value of this feature; may be <code>null</code> if the value has not been set. * @exception CASRuntimeException * If there is a typing violation, i.e., if <code>f</code> is not defined for the * type of this feature structure, or if the range type of <code>f</code> is not * String. */ String getStringValue(Feature f) throws CASRuntimeException; /** * Get the float value of a feature. This method will throw an exception if the feature is not * float valued. * * @param feat * The feature whose value we want to get. * @return The value float; <code>0.0</code> if the value has not been set. * @exception CASRuntimeException * If <code>feat</code> is not defined for the type of this FS, or if it is not float * valued. */ float getFloatValue(Feature feat) throws CASRuntimeException; /** * Set the float value of a feature. * * @param feat * The feature whose value we want to set. * @param f * The float we're setting the feature to. * @exception CASRuntimeException * If <code>feat</code> is not defined for the type of this FS, or if it is not float * valued. */ void setFloatValue(Feature feat, float f) throws CASRuntimeException; /** * Get the int value of a feature. This method will throw an exception if the feature is not int * valued. * * @param feat * The feature whose value we want to get. * @return The value int; <code>0</code> if the value has not been set. * @exception CASRuntimeException * If <code>feat</code> is not defined for the type of this FS, or if it is not int * valued. */ int getIntValue(Feature feat) throws CASRuntimeException; /** * Set the int value of a feature. * * @param feat * The feature whose value we want to set. * @param i * The int we're setting the feature to. */ void setIntValue(Feature feat, int i) throws CASRuntimeException; /** * * Get the byte value of a feature. This method will throw an exception if the feature is not byte * valued. * * @param feat * The feature whose value we want to set. * @return The value byte; <code>0</code> if the value has not been set. * @throws CASRuntimeException * tbd */ byte getByteValue(Feature feat) throws CASRuntimeException; /** * Set the byte (8 bit) value of a feature. * * @param feat * The feature whose value we want to set. * @param i * The 8bit value we're setting the feature to. * @throws CASRuntimeException * tbd */ void setByteValue(Feature feat, byte i) throws CASRuntimeException; /** * Get the boolean value of a feature. This method will throw an exception if the feature is not * boolean valued. * * @param feat * The feature whose value we want to get. * @return The value int; <code>0</code> if the value has not been set. * @exception CASRuntimeException * If <code>feat</code> is not defined for the type of this FS, or if it is not * boolean valued. */ boolean getBooleanValue(Feature feat) throws CASRuntimeException; /** * Set the boolean value of a feature. * * @param feat * The feature whose value we want to set. * @param i * The boolean value we're setting the feature to. */ void setBooleanValue(Feature feat, boolean i) throws CASRuntimeException; /** * Get the short value of a feature. This method will throw an exception if the feature is not * short valued. * * @param feat * The feature whose value we want to get. * @return The value int; <code>0</code> if the value has not been set. * @exception CASRuntimeException * If <code>feat</code> is not defined for the type of this FS, or if it is not short * valued. */ short getShortValue(Feature feat) throws CASRuntimeException; /** * Set the short (16 bit) value of a feature. * * @param feat * The feature whose value we want to set. * @param i * The short (16bit) value we're setting the feature to. */ void setShortValue(Feature feat, short i) throws CASRuntimeException; /** * Get the long value of a feature. This method will throw an exception if the feature is not long * valued. * * @param feat * The feature whose value we want to get. * @return The value int; <code>0</code> if the value has not been set. * @exception CASRuntimeException * If <code>feat</code> is not defined for the type of this FS, or if it is not long * valued. */ long getLongValue(Feature feat) throws CASRuntimeException; /** * Set the long (64 bit) value of a feature. * * @param feat * The feature whose value we want to set. * @param i * The long (64bit) value we're setting the feature to. */ void setLongValue(Feature feat, long i) throws CASRuntimeException; /** * Get the double value of a feature. This method will throw an exception if the feature is not * double valued. * * @param feat * The feature whose value we want to get. * @return The value int; <code>0</code> if the value has not been set. * @exception CASRuntimeException * If <code>feat</code> is not defined for the type of this FS, or if it is not * double valued. */ double getDoubleValue(Feature feat) throws CASRuntimeException; /** * Set the double value of a feature. * * @param feat * The feature whose value we want to set. * @param i * The double value we're setting the feature to. * @exception CASRuntimeException * If <code>feat</code> is not defined for the type of this FS */ void setDoubleValue(Feature feat, double i) throws CASRuntimeException; /** * Get the value of the feature as a string if the type of the feature is one of the primitive * type. * * @param feat * The feature whose value we want to get and whose type is one of the primitive types. * @return A string representation of the feature value. * @throws CASRuntimeException * If <code>feat</code> is not defined for the type of this FS, or if the type is not a * primitive type. */ String getFeatureValueAsString(Feature feat) throws CASRuntimeException; /** * Sets the value of a feature from a string input if the feature type is one of the primitive * types. * * @param feat * The feature whose value we want to set. * @param s * The string value that the feature will be set to. * @throws CASRuntimeException * If <code>feat</code> is not a primitive type or the value cannot be converted to this * type. */ void setFeatureValueFromString(Feature feat, String s) throws CASRuntimeException; /** * @return The CAS view where this Feature Structure was created */ CAS getCAS(); /** * @return the JCas view where this Feature Structure was created */ default JCas getJCas() { return getCAS().getJCasImpl(); // getJCas defined (from v2) to throw exception, this one doesn't }; /** * return the unique (to this CAS) id of this feature structure * * @return the id */ int _id(); /** * Internal use * * @return the type code of this feature structure */ int _getTypeCode(); /** * Creates a copy of this feature structure. The returned feature structure is a new and separate * object but all features of the feature structure which are not of builtin types (integer, * float, string) will be shared between the clone and it's source FS. * * @return a FeatureStructure that is the cloned copy of this FeatureStructure. * @throws CASRuntimeException * passthru */ Object clone() throws CASRuntimeException; /** * Compatibility for v2 code. As a side effect, this will enter this Feature Structure into the * int-to-FS table so the low level API call ll_getFSForRef(int) works. This has the effect of * disabling garbage collection for this Feature Structure. * * @return the equivalent of the v2 address */ int getAddress(); /** * A feature structure is equal to another feature structure iff it is identical in the underlying * representation. * * @exception ClassCastException * If <code>o</code> is not a FS. */ @Override boolean equals(Object o) throws ClassCastException; /** * Will return a hash code that's consistent with equality, i.e., if two FSs are equal, they will * also return the same hash code. * * @return The hash code. */ @Override int hashCode(); }
apache-2.0
lz84/bachelor-all
bachelor-up/bachelor-up-common/src/main/java/cn/org/bachelor/up/oauth2/common/exception/OAuthSystemException.java
457
package cn.org.bachelor.up.oauth2.common.exception; /** * Created by team bachelor on 15/5/20. */ public class OAuthSystemException extends Exception { public OAuthSystemException() { } public OAuthSystemException(String s) { super(s); } public OAuthSystemException(Throwable throwable) { super(throwable); } public OAuthSystemException(String s, Throwable throwable) { super(s, throwable); } }
apache-2.0
wouterv/orientdb
core/src/main/java/com/orientechnologies/orient/core/index/OIndexException.java
1276
/* * * * Copyright 2014 Orient Technologies LTD (info(at)orientechnologies.com) * * * * Licensed under the Apache License, Version 2.0 (the "License"); * * you may not use this file except in compliance with the License. * * You may obtain a copy of the License at * * * * http://www.apache.org/licenses/LICENSE-2.0 * * * * Unless required by applicable law or agreed to in writing, software * * distributed under the License is distributed on an "AS IS" BASIS, * * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * * See the License for the specific language governing permissions and * * limitations under the License. * * * * For more information: http://www.orientechnologies.com * */ package com.orientechnologies.orient.core.index; import com.orientechnologies.common.exception.OHighLevelException; import com.orientechnologies.orient.core.exception.OCoreException; public class OIndexException extends OCoreException { private static final long serialVersionUID = -2655748565531836968L; public OIndexException(OIndexException exception) { super(exception); } public OIndexException(final String string) { super(string); } }
apache-2.0
nmcl/scratch
graalvm/transactions/fork/narayana/txbridge/src/test/java/org/jboss/jbossts/txbridge/tests/common/AbstractBasicTests.java
5433
/* * JBoss, Home of Professional Open Source * Copyright 2010, Red Hat, Inc. and/or its affiliates, * and individual contributors as indicated by the @author tags. * See the copyright.txt in the distribution for a * full listing of individual contributors. * This copyrighted material is made available to anyone wishing to use, * modify, copy, or redistribute it subject to the terms and conditions * of the GNU Lesser General Public License, v. 2.1. * This program is distributed in the hope that it will be useful, but WITHOUT A * WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * You should have received a copy of the GNU Lesser General Public License, * v.2.1 along with this distribution; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, * MA 02110-1301, USA. * * (C) 2010, * @author JBoss, by Red Hat. */ package org.jboss.jbossts.txbridge.tests.common; import java.io.IOException; import org.apache.http.client.ResponseHandler; import org.apache.http.client.methods.HttpGet; import org.apache.http.impl.client.BasicResponseHandler; import org.apache.http.impl.client.DefaultHttpClient; import org.jboss.byteman.agent.submit.Submit; import org.jboss.byteman.contrib.dtest.Instrumentor; import org.jboss.shrinkwrap.api.Archive; import org.jboss.shrinkwrap.api.ShrinkWrap; import org.jboss.shrinkwrap.api.asset.StringAsset; import org.jboss.shrinkwrap.api.spec.WebArchive; import org.junit.Assert; import org.junit.BeforeClass; /** * Common methods for tx bridge test cases. * * @author Ivo Studensky (istudens@redhat.com) */ public abstract class AbstractBasicTests { protected static Instrumentor instrumentor = null; public static final String INBOUND_SERVICE_DEPLOYMENT_NAME = "txbridge-inbound-tests-service"; public static final String INBOUND_CLIENT_DEPLOYMENT_NAME = "txbridge-inbound-tests-client"; public static final String OUTBOUND_SERVICE_DEPLOYMENT_NAME = "txbridge-outbound-tests-service"; public static final String OUTBOUND_CLIENT_DEPLOYMENT_NAME = "txbridge-outbound-tests-client"; protected static final String CONTAINER = "jboss"; protected static Archive<?> getInboundServiceArchive() { Archive<?> archive = ShrinkWrap.create(WebArchive.class, INBOUND_SERVICE_DEPLOYMENT_NAME + ".war") .addPackage("org.jboss.jbossts.txbridge.tests.inbound.service") .addPackage("org.jboss.jbossts.txbridge.tests.inbound.utility") // .addAsManifestResource("inbound/jboss-beans.xml", "jboss-beans.xml") .addAsManifestResource(new StringAsset("Dependencies: org.jboss.xts,org.jboss.jts\n"), "MANIFEST.MF"); // archive.as(ZipExporter.class).exportTo(new File("/tmp/deployment.zip"), true); return archive; } protected static Archive<?> getInboundClientArchive() { Archive<?> archive = ShrinkWrap.create(WebArchive.class, INBOUND_CLIENT_DEPLOYMENT_NAME + ".war") .addPackage("org.jboss.jbossts.txbridge.tests.inbound.client") .addAsManifestResource(new StringAsset("Dependencies: org.jboss.xts,org.jboss.jts\n"), "MANIFEST.MF"); return archive; } protected static Archive<?> getOutboundServiceArchive() { Archive<?> archive = ShrinkWrap.create(WebArchive.class, OUTBOUND_SERVICE_DEPLOYMENT_NAME + ".war") .addClass(org.jboss.jbossts.txbridge.tests.outbound.service.TestServiceImpl.class) .addPackage("org.jboss.jbossts.txbridge.tests.outbound.utility") .addAsResource("outbound/jaxws-handlers-server.xml", "jaxws-handlers-server.xml") // .addAsManifestResource("outbound/jboss-beans.xml", "jboss-beans.xml") .addAsManifestResource(new StringAsset("Dependencies: org.jboss.xts,org.jboss.jts\n"), "MANIFEST.MF"); return archive; } protected static Archive<?> getOutboundClientArchive() { Archive<?> archive = ShrinkWrap.create(WebArchive.class, OUTBOUND_CLIENT_DEPLOYMENT_NAME + ".war") .addClass(org.jboss.jbossts.txbridge.tests.outbound.client.TestClient.class) .addClass(org.jboss.jbossts.txbridge.tests.outbound.client.TestService.class) .addAsManifestResource(new StringAsset("Dependencies: org.jboss.xts,org.jboss.jts\n"), "MANIFEST.MF"); return archive; } @BeforeClass public static void beforeClass() throws Exception { if (instrumentor == null) { instrumentor = new Instrumentor(new Submit(), 1199); } } protected void execute(String url) throws Exception { execute(url, true); } protected void execute(String url, boolean expectResponse) throws Exception { try { DefaultHttpClient httpclient = new DefaultHttpClient(); HttpGet httpget = new HttpGet(url); ResponseHandler<String> responseHandler = new BasicResponseHandler(); String response = httpclient.execute(httpget, responseHandler); if (expectResponse) { Assert.assertEquals("Invalid response!", "finished", response.trim()); } } catch (IOException e) { if (expectResponse) { throw e; } } } }
apache-2.0
webmetrics/browsermob-proxy
src/main/java/org/browsermob/proxy/guice/ConfigModule.java
1975
package org.browsermob.proxy.guice; import com.google.inject.Binder; import com.google.inject.Key; import com.google.inject.Module; import cz.mallat.uasparser.OnlineUpdateUASparser; import joptsimple.ArgumentAcceptingOptionSpec; import joptsimple.OptionParser; import joptsimple.OptionSet; import org.browsermob.proxy.http.BrowserMobHttpClient; import java.io.IOException; import static java.util.Arrays.asList; public class ConfigModule implements Module { private String[] args; public ConfigModule(String[] args) { this.args = args; } @Override public void configure(Binder binder) { OptionParser parser = new OptionParser(); ArgumentAcceptingOptionSpec<Integer> portSpec = parser.accepts("port", "The port to listen on") .withOptionalArg().ofType(Integer.class).defaultsTo(8080); ArgumentAcceptingOptionSpec<Integer> userAgentCacheSpec = parser.accepts("uaCache", "The number of days to cache a database of User-Agent records from http://user-agent-string.info") .withOptionalArg().ofType(Integer.class).defaultsTo(1); parser.acceptsAll(asList("help", "?"), "This help text"); OptionSet options = parser.parse(args); if (options.has("?")) { try { parser.printHelpOn(System.out); System.exit(0); } catch (IOException e) { // should never happen, but... e.printStackTrace(); } return; } binder.bind(Key.get(Integer.class, new NamedImpl("port"))).toInstance(portSpec.value(options)); Integer userAgentCacheDays = userAgentCacheSpec.value(options); if (BrowserMobHttpClient.PARSER instanceof OnlineUpdateUASparser) { ((OnlineUpdateUASparser) BrowserMobHttpClient.PARSER).setUpdateInterval(1000 * 60 * 60 * 24 * userAgentCacheDays); } } }
apache-2.0
grgrzybek/karaf
web/src/main/java/org/apache/karaf/web/commands/List.java
2795
/* * 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.karaf.web.commands; import org.apache.karaf.shell.api.action.Action; import org.apache.karaf.shell.api.action.Command; import org.apache.karaf.shell.api.action.Option; import org.apache.karaf.shell.api.action.lifecycle.Reference; import org.apache.karaf.shell.api.action.lifecycle.Service; import org.apache.karaf.shell.support.table.Col; import org.apache.karaf.shell.support.table.ShellTable; import org.apache.karaf.web.WebBundle; import org.apache.karaf.web.WebContainerService; @Command(scope = "web", name = "list", description = "Lists details for war bundles.") @Service public class List implements Action { @Option(name = "--no-format", description = "Disable table rendered output", required = false, multiValued = false) boolean noFormat; @Reference private WebContainerService webContainerService; public void setWebContainerService(WebContainerService webContainerService) { this.webContainerService = webContainerService; } @Override public Object execute() throws Exception { ShellTable table = new ShellTable(); table.column(new Col("ID")); table.column(new Col("State")); table.column(new Col("Web-State")); table.column(new Col("Level")); table.column(new Col("Web-ContextPath")); table.column(new Col("Name")); java.util.List<WebBundle> webBundles = webContainerService.list(); if (webBundles != null && !webBundles.isEmpty()) { for (WebBundle webBundle : webBundles) { table.addRow().addContent( webBundle.getBundleId(), webBundle.getState(), webBundle.getWebState(), webBundle.getLevel(), webBundle.getContextPath(), webBundle.getName()); } } table.print(System.out, !noFormat); return null; } }
apache-2.0
pumpadump/sweble-wikitext
swc-engine/src/main/java/org/sweble/wikitext/engine/config/WikiConfigImpl.java
26039
/** * Copyright 2011 The Open Source Research Group, * University of Erlangen-Nürnberg * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.sweble.wikitext.engine.config; import java.io.File; import java.io.InputStream; import java.io.OutputStream; import java.io.Reader; import java.io.Writer; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.Map; import java.util.TimeZone; import javax.xml.bind.JAXBContext; import javax.xml.bind.JAXBException; import javax.xml.bind.Marshaller; import javax.xml.bind.PropertyException; import javax.xml.bind.Unmarshaller; import javax.xml.bind.ValidationEvent; import javax.xml.bind.ValidationEventHandler; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementWrapper; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.util.JAXBSource; import javax.xml.transform.Source; import org.sweble.wikitext.engine.ParserFunctionBase; import org.sweble.wikitext.engine.TagExtensionBase; import org.sweble.wikitext.engine.nodes.EngineNodeFactoryImpl; import org.sweble.wikitext.engine.utils.EngineAstTextUtils; import org.sweble.wikitext.engine.utils.EngineAstTextUtilsImpl; import com.sun.xml.bind.marshaller.NamespacePrefixMapper; @XmlRootElement( name = "WikiConfig", namespace = "org.sweble.wikitext.engine") @XmlType(propOrder = { "siteName", "wikiUrl", "contentLang", "iwPrefix", "jaxbNamespaces", "jaxbInterwikis", "jaxbAliases", "jaxbPfnGroups", "jaxbTagExtGroups", "parserConfig", "engineConfig" }) @XmlAccessorType(XmlAccessType.NONE) public class WikiConfigImpl implements WikiConfig { @XmlElement() private final ParserConfigImpl parserConfig; @XmlElement() private final EngineConfigImpl engineConfig; // -- AST generation/processing -- private EngineNodeFactoryImpl nodeFactory; private EngineAstTextUtilsImpl textUtils; // -- General Information -- @XmlElement() private String siteName; @XmlElement() private String wikiUrl; @XmlElement() private String contentLang; @XmlElement() private String iwPrefix; // -- Aliases -- private final Map<String, I18nAliasImpl> aliases = new HashMap<String, I18nAliasImpl>(); private transient final Map<String, I18nAliasImpl> nameToAliasMap = new HashMap<String, I18nAliasImpl>(); // -- Parser Functions -- private final Map<String, ParserFunctionGroup> pfnGroups = new HashMap<String, ParserFunctionGroup>(); private transient final Map<String, ParserFunctionBase> parserFunctions = new HashMap<String, ParserFunctionBase>(); private transient final Map<I18nAliasImpl, ParserFunctionBase> aliasToPfnMap = new HashMap<I18nAliasImpl, ParserFunctionBase>(); // -- Tag Extensions -- private final Map<String, TagExtensionGroup> tagExtGroups = new HashMap<String, TagExtensionGroup>(); private transient final Map<String, TagExtensionBase> tagExtensions = new HashMap<String, TagExtensionBase>(); // -- Interwikis -- private final Map<String, InterwikiImpl> prefixToInterwikiMap = new HashMap<String, InterwikiImpl>(); // -- Namespaces -- private final Map<Integer, NamespaceImpl> namespaceById = new HashMap<Integer, NamespaceImpl>(); private transient final Map<String, NamespaceImpl> namespaceByName = new HashMap<String, NamespaceImpl>(); private NamespaceImpl templateNamespace; private NamespaceImpl defaultNamespace; // -- Runtime information -- private WikiRuntimeInfo runtimeInfo; // ========================================================================= public WikiConfigImpl() { this.parserConfig = new ParserConfigImpl(this); this.nodeFactory = new EngineNodeFactoryImpl(this.parserConfig); this.textUtils = new EngineAstTextUtilsImpl(this.parserConfig); this.runtimeInfo = new WikiRuntimeInfoImpl(this); this.engineConfig = new EngineConfigImpl(); } // ==[ Parser Configuration ]=============================================== @Override public ParserConfigImpl getParserConfig() { return parserConfig; } // ==[ Engine Configuration ]=============================================== public EngineConfigImpl getEngineConfig() { return engineConfig; } // ==[ AST creation/processing ]============================================ public EngineNodeFactoryImpl getNodeFactory() { return nodeFactory; } @Override public EngineAstTextUtils getAstTextUtils() { return textUtils; } // ==[ Namespaces ]========================================================= public void addNamespace(NamespaceImpl ns) { NamespaceImpl old = namespaceById.get(ns.getId()); if (old == ns) throw new IllegalArgumentException("The namespace with id `" + ns.getId() + "' is already registered."); if (old != null) throw new IllegalArgumentException("A namespace with the same id `" + ns.getId() + "' is already registered."); ArrayList<String> names = new ArrayList<String>(ns.getAliases().size() + 2); for (String name : ns.getAliases()) names.add(name.toLowerCase()); names.add(ns.getName().toLowerCase()); names.add(ns.getCanonical().toLowerCase()); for (String name : names) { old = namespaceByName.get(name); // old == ns would have been caught by the id search above if (old != null) throw new IllegalArgumentException("Another namespace already registered the name `" + name + "'."); } namespaceById.put(ns.getId(), ns); for (String name : names) namespaceByName.put(name, ns); } public void setDefaultNamespace(NamespaceImpl defaultNamespace) { if (this.namespaceById.get(defaultNamespace.getId()) != defaultNamespace) throw new IllegalArgumentException("Given namespace unknown in this configuration"); this.defaultNamespace = defaultNamespace; } public void setTemplateNamespace(NamespaceImpl templateNamespace) { if (this.namespaceById.get(templateNamespace.getId()) != templateNamespace) throw new IllegalArgumentException("Given namespace unknown in this configuration"); this.templateNamespace = templateNamespace; } @Override public NamespaceImpl getNamespace(String name) { return namespaceByName.get(name.toLowerCase()); } @SuppressWarnings({ "unchecked", "rawtypes" }) @Override public Collection<Namespace> getNamespaces() { return (Collection) Collections.unmodifiableCollection(namespaceById.values()); } @Override public NamespaceImpl getNamespace(int id) { return namespaceById.get(id); } @Override public NamespaceImpl getDefaultNamespace() { return defaultNamespace; } @Override public NamespaceImpl getTemplateNamespace() { return templateNamespace; } @Override public Namespace getFileNamespace() { return getNamespace("File"); } @Override public Namespace getSubjectNamespaceFor(Namespace namespace) { if (namespace.isSubjectNamespace()) return namespace; return getNamespace(namespace.getSubjectspaceId()); } @Override public Namespace getTalkNamespaceFor(Namespace namespace) { if (namespace.isTalkNamespace()) return namespace; return getNamespace(namespace.getTalkspaceId()); } // ==[ Known Wikis ]======================================================== public void addInterwiki(InterwikiImpl iw) { InterwikiImpl old = prefixToInterwikiMap.get(iw.getPrefix()); if (old == iw) throw new IllegalArgumentException("The wiki with interwiki prefix `" + iw.getPrefix() + "' is already registered."); if (old != null) throw new IllegalArgumentException("A wiki with the same interwiki prefix `" + iw.getPrefix() + "' is already registered."); prefixToInterwikiMap.put(iw.getPrefix(), iw); } @Override public InterwikiImpl getInterwiki(String prefix) { return prefixToInterwikiMap.get(prefix); } @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public Collection<Interwiki> getInterwikis() { return (Collection) Collections.unmodifiableCollection(prefixToInterwikiMap.values()); } // ==[ Internationalization ]=============================================== /** * Aliases apply to the following things: * <ul> * <li>Page switches, e.g. {@code __NOTOC__}. They can be queried using * getPageSwitch(). The full name (e.g. " {@code __NOTOC__}") has to be * specified as alias when specifying an alias as well as when querying the * page switch in the expansion process.</li> * <li>Parser functions, e.g. {@code lc:}. They can be queried using * getParserFunction(). The full name plus the colon (e.g. " {@code lc:}") * has to be specified as alias when specifying an alias as well as when * querying the parser function in the expansion process. A parser function * that can also be called without arguments is treated as magic word * instead (e.g. {@code NAMESPACE} instead of {@code NAMESPACE:})!</li> * <li>Magic words, e.g. {@code CURRENTDAY}. They can be queried using * getParserFunction(). The full name (e.g. " {@code CURRENTDAY}") has to be * specified as alias when specifying an alias as well as when querying the * magic word in the expansion process.</li> * <li>Redirect keyword</li> * </ul> */ public void addI18nAlias(I18nAliasImpl alias) { I18nAliasImpl old = aliases.get(alias.getId()); if (old == alias || (old != null && old.equals(alias))) throw new IllegalArgumentException("This alias is already registered: " + alias.getId()); if (old != null) throw new IllegalArgumentException("An alias with the same id `" + alias.getId() + "' is already registered."); for (String a : alias.getAliases()) { String lcAlias = a.toLowerCase(); I18nAliasImpl old2 = nameToAliasMap.get(lcAlias); if (old2 == alias) throw new IllegalArgumentException("This alias (`" + alias.getId() + "') registeres the name `" + a + "' twice."); if (old2 != null) throw new IllegalArgumentException("The name `" + a + "' was already registered by the alias `" + old2.getId() + "' when trying to register it for alias `" + alias.getId() + "'."); nameToAliasMap.put(lcAlias, alias); } aliases.put(alias.getId(), alias); } @Override public I18nAliasImpl getI18nAlias(String name) { if (name == null) throw new NullPointerException(); I18nAliasImpl alias = nameToAliasMap.get(name.toLowerCase()); if (alias != null && alias.isCaseSensitive() && !alias.getAliases().contains(name)) alias = null; return alias; } public I18nAliasImpl getI18nAliasById(String id) { return aliases.get(id); } @Override @SuppressWarnings({ "unchecked", "rawtypes" }) public Collection<I18nAlias> getI18nAliases() { return (Collection) Collections.unmodifiableCollection(aliases.values()); } // ==[ Tag extensions, parser functions and page switches ]================= public void addParserFunctionGroup(ParserFunctionGroup pfnGroup) { ParserFunctionGroup old = pfnGroups.get(pfnGroup.getName()); if (old == pfnGroup) throw new IllegalArgumentException("The parser function group `" + pfnGroup.getName() + "' is already registered."); if (old != null) throw new IllegalArgumentException("A parser function group with the same name `" + pfnGroup.getName() + "' is already registered."); for (ParserFunctionBase pfn : pfnGroup.getParserFunctions()) addParserFunction(pfn); this.pfnGroups.put(pfnGroup.getName(), pfnGroup); } protected void addParserFunction(ParserFunctionBase pfn) { ParserFunctionBase old = parserFunctions.get(pfn.getId()); if (old == pfn) throw new IllegalArgumentException("The parser function `" + pfn.getId() + "' is already registered."); if (old != null) throw new IllegalArgumentException("A parser function with the same id `" + pfn.getId() + "' is already registered."); parserFunctions.put(pfn.getId(), pfn); I18nAliasImpl alias = aliases.get(pfn.getId()); if (alias == null) throw new IllegalArgumentException("No alias registered for parser function `" + pfn.getId() + "'."); if (aliasToPfnMap.put(alias, pfn) != null) throw new InternalError("Alias collision should not be possible..."); } @Override public Collection<ParserFunctionBase> getParserFunctions() { return Collections.unmodifiableCollection(parserFunctions.values()); } @Override public ParserFunctionBase getParserFunction(String name) { I18nAliasImpl alias = getI18nAlias(name); if (alias == null) return null; ParserFunctionBase pfn = aliasToPfnMap.get(alias); if (pfn != null && pfn.isPageSwitch()) return null; return pfn; } @Override public ParserFunctionBase getPageSwitch(String name) { I18nAliasImpl alias = getI18nAlias(name); if (alias == null) return null; ParserFunctionBase pfn = aliasToPfnMap.get(alias); if (pfn != null && !pfn.isPageSwitch()) return null; return pfn; } // -------- public void addTagExtensionGroup(TagExtensionGroup tagExtGroup) { TagExtensionGroup old = tagExtGroups.get(tagExtGroup.getName()); if (old == tagExtGroup) throw new IllegalArgumentException("The tag extension group `" + tagExtGroup.getName() + "' is already registered."); if (old != null) throw new IllegalArgumentException("A tag extension group with the same name `" + tagExtGroup.getName() + "' is already registered."); for (TagExtensionBase tagExt : tagExtGroup.getTagExtensions()) addTagExtension(tagExt); this.tagExtGroups.put(tagExtGroup.getName(), tagExtGroup); } protected void addTagExtension(TagExtensionBase tagExt) { TagExtensionBase old = tagExtensions.get(tagExt.getId()); if (old == tagExt) throw new IllegalArgumentException("The tag extension `" + tagExt.getId() + "' is already registered."); if (old != null) throw new IllegalArgumentException("A tag extension with the same id `" + tagExt.getId() + "' is already registered."); tagExtensions.put(tagExt.getId(), tagExt); } @Override public Collection<TagExtensionBase> getTagExtensions() { return Collections.unmodifiableCollection(tagExtensions.values()); } @Override public TagExtensionBase getTagExtension(String name) { return tagExtensions.get(name); } // ==[ Properties of the wiki instance ]==================================== public void setSiteName(String siteName) { this.siteName = siteName; } @Override public String getSiteName() { return this.siteName; } public void setWikiUrl(String wikiUrl) { this.wikiUrl = wikiUrl; } @Override public String getWikiUrl() { return this.wikiUrl; } @Override public String getArticlePath() { return getWikiUrl() + "?title=$1"; } public void setContentLang(String contentLang) { this.contentLang = contentLang; } @Override public String getContentLanguage() { return contentLang; } public void setIwPrefix(String iwPrefix) { this.iwPrefix = iwPrefix; } @Override public String getInterwikiPrefix() { return iwPrefix; } @Override public TimeZone getTimezone() { // TODO: Make variable and save to / read from XML return TimeZone.getDefault(); } // ==[ Runtime information ]================================================ @Override public WikiRuntimeInfo getRuntimeInfo() { return runtimeInfo; } public void setRuntimeInfo(WikiRuntimeInfo runtimeInfo) { this.runtimeInfo = runtimeInfo; } // ========================================================================= @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((aliases == null) ? 0 : aliases.hashCode()); result = prime * result + ((engineConfig == null) ? 0 : engineConfig.hashCode()); result = prime * result + ((contentLang == null) ? 0 : contentLang.hashCode()); result = prime * result + ((defaultNamespace == null) ? 0 : defaultNamespace.hashCode()); result = prime * result + ((iwPrefix == null) ? 0 : iwPrefix.hashCode()); result = prime * result + ((namespaceById == null) ? 0 : namespaceById.hashCode()); result = prime * result + ((parserConfig == null) ? 0 : parserConfig.hashCode()); result = prime * result + ((pfnGroups == null) ? 0 : pfnGroups.hashCode()); result = prime * result + ((prefixToInterwikiMap == null) ? 0 : prefixToInterwikiMap.hashCode()); result = prime * result + ((tagExtGroups == null) ? 0 : tagExtGroups.hashCode()); result = prime * result + ((templateNamespace == null) ? 0 : templateNamespace.hashCode()); result = prime * result + ((wikiUrl == null) ? 0 : wikiUrl.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; WikiConfigImpl other = (WikiConfigImpl) obj; if (aliases == null) { if (other.aliases != null) return false; } else if (!aliases.equals(other.aliases)) return false; if (engineConfig == null) { if (other.engineConfig != null) return false; } else if (!engineConfig.equals(other.engineConfig)) return false; if (contentLang == null) { if (other.contentLang != null) return false; } else if (!contentLang.equals(other.contentLang)) return false; if (defaultNamespace == null) { if (other.defaultNamespace != null) return false; } else if (!defaultNamespace.equals(other.defaultNamespace)) return false; if (iwPrefix == null) { if (other.iwPrefix != null) return false; } else if (!iwPrefix.equals(other.iwPrefix)) return false; if (namespaceById == null) { if (other.namespaceById != null) return false; } else if (!namespaceById.equals(other.namespaceById)) return false; if (parserConfig == null) { if (other.parserConfig != null) return false; } else if (!parserConfig.equals(other.parserConfig)) return false; if (pfnGroups == null) { if (other.pfnGroups != null) return false; } else if (!pfnGroups.equals(other.pfnGroups)) return false; if (prefixToInterwikiMap == null) { if (other.prefixToInterwikiMap != null) return false; } else if (!prefixToInterwikiMap.equals(other.prefixToInterwikiMap)) return false; if (tagExtGroups == null) { if (other.tagExtGroups != null) return false; } else if (!tagExtGroups.equals(other.tagExtGroups)) return false; if (templateNamespace == null) { if (other.templateNamespace != null) return false; } else if (!templateNamespace.equals(other.templateNamespace)) return false; if (wikiUrl == null) { if (other.wikiUrl != null) return false; } else if (!wikiUrl.equals(other.wikiUrl)) return false; return true; } // ========================================================================= public void save(File file) throws JAXBException { createMarshaller().marshal(this, file); } public void save(Writer writer) throws JAXBException { createMarshaller().marshal(this, writer); } public void save(OutputStream out) throws JAXBException { createMarshaller().marshal(this, out); } public JAXBSource getAsJAXBSource() throws JAXBException { return new JAXBSource(createMarshaller(), this); } private Marshaller createMarshaller() throws JAXBException { JAXBContext context = JAXBContext.newInstance(WikiConfigImpl.class); Marshaller m = context.createMarshaller(); m.setEventHandler(new ValidationEventHandler() { @Override public boolean handleEvent(ValidationEvent event) { System.err.println(event); return true; } }); try { m.setProperty( "com.sun.xml.bind.namespacePrefixMapper", new NamespaceMapper()); m.setProperty( Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE); } catch (PropertyException e) { } return m; } public static WikiConfigImpl load(File file) throws JAXBException { return finishImport((WikiConfigImpl) createUnmarshaller().unmarshal(file)); } public static WikiConfigImpl load(Reader reader) throws JAXBException { return finishImport((WikiConfigImpl) createUnmarshaller().unmarshal(reader)); } public static WikiConfigImpl load(InputStream in) throws JAXBException { return finishImport((WikiConfigImpl) createUnmarshaller().unmarshal(in)); } public static WikiConfigImpl load(Source in) throws JAXBException { return finishImport((WikiConfigImpl) createUnmarshaller().unmarshal(in)); } private static WikiConfigImpl finishImport(WikiConfigImpl config) { for (ParserFunctionBase pf : config.getParserFunctions()) pf.setWikiConfig(config); for (TagExtensionBase te : config.getTagExtensions()) te.setWikiConfig(config); config.parserConfig.setWikiConfig(config); config.nodeFactory = new EngineNodeFactoryImpl(config.parserConfig); return config; } private static Unmarshaller createUnmarshaller() throws JAXBException { JAXBContext context = JAXBContext.newInstance(WikiConfigImpl.class); Unmarshaller m = context.createUnmarshaller(); m.setEventHandler(new ValidationEventHandler() { @Override public boolean handleEvent(ValidationEvent event) { // We don't want to recover! return false; } }); return m; } // ========================================================================= private static final class NamespaceMapper extends NamespacePrefixMapper { private static final String SWC_ENGINE_PREFIX = "swc-engine"; private static final String SWC_ENGINE_URI = "org.sweble.wikitext.engine"; @Override public String getPreferredPrefix( String namespaceUri, String suggestion, boolean requirePrefix) { if (SWC_ENGINE_URI.equals(namespaceUri)) return SWC_ENGINE_PREFIX; else return suggestion; } @Override public String[] getPreDeclaredNamespaceUris() { return new String[] { SWC_ENGINE_URI, }; } } // ========================================================================= @XmlElement(name = "i18nAlias") @XmlElementWrapper(name = "i18nAliases") private I18nAliasImpl[] getJaxbAliases() { I18nAliasImpl[] jaxbAliases = this.aliases.values().toArray( new I18nAliasImpl[this.aliases.size()]); Arrays.sort(jaxbAliases); return jaxbAliases; } @SuppressWarnings("unused") private void setJaxbAliases(I18nAliasImpl[] aliases) { for (I18nAliasImpl alias : aliases) addI18nAlias(alias); } // ========================================================================= @XmlElement(name = "pfnGroup") @XmlElementWrapper(name = "pfnGroups") private ParserFunctionGroup[] getJaxbPfnGroups() { ParserFunctionGroup[] jaxbPfnGroups = this.pfnGroups.values().toArray( new ParserFunctionGroup[this.pfnGroups.size()]); Arrays.sort(jaxbPfnGroups); return jaxbPfnGroups; } @SuppressWarnings("unused") private void setJaxbPfnGroups(ParserFunctionGroup[] pfnGroups) { for (ParserFunctionGroup pfnGroup : pfnGroups) addParserFunctionGroup(pfnGroup); } // ========================================================================= @XmlElement(name = "tagExtGroup") @XmlElementWrapper(name = "tagExtGroups") private TagExtensionGroup[] getJaxbTagExtGroups() { TagExtensionGroup[] jaxbTagExtGroups = this.tagExtGroups.values().toArray( new TagExtensionGroup[this.tagExtGroups.size()]); Arrays.sort(jaxbTagExtGroups); return jaxbTagExtGroups; } @SuppressWarnings("unused") private void setJaxbTagExtGroups(TagExtensionGroup[] tagExtGroups) { for (TagExtensionGroup tagExtGroup : tagExtGroups) addTagExtensionGroup(tagExtGroup); } // ========================================================================= @XmlElement(name = "interwiki") @XmlElementWrapper(name = "interwikis") private InterwikiImpl[] getJaxbInterwikis() { InterwikiImpl[] jaxbInterwikis = this.prefixToInterwikiMap.values().toArray( new InterwikiImpl[this.prefixToInterwikiMap.size()]); Arrays.sort(jaxbInterwikis); return jaxbInterwikis; } @SuppressWarnings("unused") private void setJaxbInterwikis(InterwikiImpl[] interwikis) { for (InterwikiImpl iw : interwikis) addInterwiki(iw); } // ========================================================================= private static final class Namespaces { @XmlElement(name = "namespace") private NamespaceImpl[] namespaces; @XmlAttribute private int defaultNsId; @XmlAttribute private int templateNsId; @SuppressWarnings("unused") public Namespaces() { } public Namespaces(NamespaceImpl[] namespaces, int defId, int tmplId) { Arrays.sort(namespaces); this.namespaces = namespaces; this.defaultNsId = defId; this.templateNsId = tmplId; } } @XmlElement(name = "namespaces") private Namespaces getJaxbNamespaces() { return new Namespaces( this.namespaceById.values().toArray( new NamespaceImpl[this.namespaceById.size()]), defaultNamespace.getId(), templateNamespace.getId()); } @SuppressWarnings("unused") private void setJaxbNamespaces(Namespaces namespaces) { for (NamespaceImpl ns : namespaces.namespaces) addNamespace(ns); setDefaultNamespace(getNamespace(namespaces.defaultNsId)); setTemplateNamespace(getNamespace(namespaces.templateNsId)); } }
apache-2.0
Bernardo-MG/pendragon-model-api
src/main/java/com/wandrell/tabletop/pendragon/model/character/background/BackgroundInfo.java
719
package com.wandrell.tabletop.pendragon.model.character.background; public interface BackgroundInfo { public String getCulture(); public String getFatherClass(); public String getHomeland(); public String getLiegeLord(); public Religion getReligion(); public Integer getSonNumber(); public Boolean isKnight(); public void setCulture(final String culture); public void setFatherClass(final String fatherClass); public void setHomeland(final String homeland); public void setKnight(final Boolean knight); public void setLiegeLord(final String liege); public void setReligion(final Religion religion); public void setSonNumber(final Integer son); }
apache-2.0
liveontologies/proof-utils
src/main/java/org/liveontologies/puli/pinpointing/PriorityComparator.java
1242
/*- * #%L * Proof Utility Library * $Id:$ * $HeadURL:$ * %% * Copyright (C) 2014 - 2017 Live Ontologies 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. * #L% */ package org.liveontologies.puli.pinpointing; import java.util.Comparator; /** * Instead of comparing objects directly, compares their priorities provided by * {@link #getPriority(Object)}. * * @author Peter Skocovsky * * @param <T> * The type of the compared objects. * @param <P> * The type of their priorities. */ public interface PriorityComparator<T, P> extends Comparator<P> { /** * @param object * @return The priority, based on which the provided object is compared. */ P getPriority(T object); }
apache-2.0
jphp-compiler/jphp
jphp-core/src/org/develnext/jphp/core/tokenizer/token/stmt/AndStmtToken.java
230
package org.develnext.jphp.core.tokenizer.token.stmt; import org.develnext.jphp.core.tokenizer.TokenMeta; public class AndStmtToken extends LogicStmtToken { public AndStmtToken(TokenMeta meta) { super(meta); } }
apache-2.0
bazelbuild/intellij
base/src/com/google/idea/blaze/base/projectview/section/Section.java
1617
/* * Copyright 2016 The Bazel Authors. All rights reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google.idea.blaze.base.projectview.section; import com.google.common.base.Objects; import java.io.Serializable; /** * A section is a part of an project view file. For instance: * * <p>directories java/com/a java/com/b * * <p>Is a directory section with two items. */ public abstract class Section<T> implements Serializable { private static final long serialVersionUID = 2L; private final String sectionName; protected Section(SectionKey<T, ?> key) { this.sectionName = key.getName(); } public boolean isSectionType(SectionKey<?, ?> key) { return this.sectionName.equals(key.getName()); } @Override public boolean equals(Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Section<?> section = (Section<?>) o; return Objects.equal(sectionName, section.sectionName); } @Override public int hashCode() { return Objects.hashCode(sectionName); } }
apache-2.0
apetro/uPortal
uportal-war/src/main/java/org/apereo/portal/utils/cache/CacheHealthReporterService.java
4610
/** * Licensed to Apereo under one or more contributor license * agreements. See the NOTICE file distributed with this work * for additional information regarding copyright ownership. * Apereo 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 the following location: * * 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.apereo.portal.utils.cache; import java.util.ArrayList; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import net.sf.ehcache.Ehcache; import net.sf.ehcache.Element; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.scheduling.annotation.Async; import org.springframework.stereotype.Service; /** * This service supports custom {@link net.sf.ehcache.event.CacheEventListener} * objects that recognize when "something bad" is happening with a uPortal * cache. Those listeners quickly contact this service with the details. * Periodically this service produces a report on bad things that are occurring, * if any, and writes it to the log. * * @author drewwills */ @Service("cacheHealthReporterService") public class CacheHealthReporterService { protected final Logger logger = LoggerFactory.getLogger(getClass()); private enum Reports { CACHE_SIZE_NOT_LARGE_ENOUGH { @Override protected void doReportInternal(Logger logger, List<ReportTuple> list) { if (list.size() != 0) { final StringBuilder report = new StringBuilder(); final Map<String,Integer> counts = new HashMap<>(); for (ReportTuple tuple : list) { final String cacheName = tuple.getCache().getName(); Integer newCount = 1; // default Integer oldCount = counts.get(cacheName); if (oldCount != null) { newCount = ++oldCount; } counts.put(cacheName, newCount); } report.append("The following cache(s) have insufficient maxElementsInMemory; " + "there must be room in the cache to hold every object of " + "the corresponding type in the portal:"); for (Map.Entry<String,Integer> y : counts.entrySet()) { report.append("\n\t- ").append(y.getKey()).append(" (") .append(y.getValue()) .append(" elements evicted due to insufficient size since last report)"); } logger.warn(report.toString()); } } }; private final List<ReportTuple> entries = Collections.synchronizedList(new ArrayList<ReportTuple>()); public final void add(ReportTuple tuple) { entries.add(tuple); } public final void writeReport(Logger logger) { // Copy & Reset the entries list final List<ReportTuple> list = new ArrayList<>(entries); entries.clear(); doReportInternal(logger, list); } protected abstract void doReportInternal(Logger logger, List<ReportTuple> list); } public void generateReports() { for (Reports report : Reports.values()) { report.writeReport(logger); } } @Async public void reportCacheSizeNotLargeEnough(Ehcache cache, Element element) { final ReportTuple tuple = new ReportTuple(cache, element); Reports.CACHE_SIZE_NOT_LARGE_ENOUGH.add(tuple); } /* * Nested Types */ private static final class ReportTuple { private final Ehcache cache; private final Element element; public ReportTuple(Ehcache cache, Element element) { this.cache = cache; this.element = element; } public Ehcache getCache() { return cache; } public Element getElement() { return element; } } }
apache-2.0
Squeegee/batik
sources/org/apache/batik/transcoder/image/resources/Messages.java
2305
/* 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.batik.transcoder.image.resources; import java.util.Locale; import java.util.MissingResourceException; import org.apache.batik.i18n.LocalizableSupport; /** * This class manages the message for the image transcoder module. * * @author <a href="mailto:tkormann@apache.org">Thierry Kormann</a> * @version $Id$ */ public class Messages { /** * This class does not need to be instantiated. */ protected Messages() { } /** * The error messages bundle class name. */ protected static final String RESOURCES = "org.apache.batik.transcoder.image.resources.Messages"; /** * The localizable support for the error messages. */ protected static LocalizableSupport localizableSupport = new LocalizableSupport(RESOURCES, Messages.class.getClassLoader()); /** * Implements {@link org.apache.batik.i18n.Localizable#setLocale(Locale)}. */ public static void setLocale(Locale l) { localizableSupport.setLocale(l); } /** * Implements {@link org.apache.batik.i18n.Localizable#getLocale()}. */ public static Locale getLocale() { return localizableSupport.getLocale(); } /** * Implements {@link * org.apache.batik.i18n.Localizable#formatMessage(String,Object[])}. */ public static String formatMessage(String key, Object[] args) throws MissingResourceException { return localizableSupport.formatMessage(key, args); } }
apache-2.0
seata/seata
saga/seata-saga-processctrl/src/main/java/io/seata/saga/proctrl/HierarchicalProcessContext.java
1847
/* * Copyright 1999-2019 Seata.io Group. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.seata.saga.proctrl; import java.util.Map; /** * Hierarchical process context * * @author lorne.cl */ public interface HierarchicalProcessContext extends ProcessContext { /** * Gets get variable locally. * * @param name the name * @return the get variable locally */ Object getVariableLocally(String name); /** * Sets set variable locally. * * @param name the name * @param value the value */ void setVariableLocally(String name, Object value); /** * Gets get variables locally. * * @return the get variables locally */ Map<String, Object> getVariablesLocally(); /** * Sets set variables locally. * * @param variables the variables */ void setVariablesLocally(Map<String, Object> variables); /** * Has variable local boolean. * * @param name the name * @return the boolean */ boolean hasVariableLocal(String name); /** * Remove variable locally. * * @param name the name * @return the removed variable or null */ Object removeVariableLocally(String name); /** * Clear locally. */ void clearLocally(); }
apache-2.0
GoogleCloudPlatform/appengine-maven-archetypes-java
hello-endpoints-archetype/src/main/resources/archetype-resources/src/main/java/Constants.java
590
#set( $symbol_pound = '#' ) #set( $symbol_dollar = '$' ) #set( $symbol_escape = '\' ) package ${package}; /** * Contains the client IDs and scopes for allowed clients consuming the helloworld API. */ public class Constants { public static final String WEB_CLIENT_ID = "${web-client-id}"; public static final String ANDROID_CLIENT_ID = "${android-client-id}"; public static final String IOS_CLIENT_ID = "${ios-client-id}"; public static final String ANDROID_AUDIENCE = WEB_CLIENT_ID; public static final String EMAIL_SCOPE = "https://www.googleapis.com/auth/userinfo.email"; }
apache-2.0
gaowangyizu/myHeritrix
myHeritrix/src/org/archive/util/BloomFilter32bp2.java
9014
/* BloomFilter * * $Id: BloomFilter32bp2.java 4644 2006-09-20 22:40:21Z paul_jack $ * * Created on Jun 21, 2005 * * Copyright (C) 2005 Internet Archive; a slight adaptation of * LGPL work (C) Sebastiano Vigna * * This file is part of the Heritrix web crawler (crawler.archive.org). * * Heritrix is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * any later version. * * Heritrix is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser Public License for more details. * * You should have received a copy of the GNU Lesser Public License * along with Heritrix; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.archive.util; import java.io.Serializable; import java.security.SecureRandom; /** A Bloom filter. * * SLIGHTLY ADAPTED VERSION OF MG4J it.unimi.dsi.mg4j.util.BloomFilter * * <p>KEY CHANGES: * * <ul> * <li>Adapted to use 32bit ops as much as possible... may be slightly * faster on 32bit hardware/OS</li> * <li>Changed to use bitfield that is a power-of-two in size, allowing * hash() to use bitshifting rather than modulus... may be slightly * faster</li> * <li>NUMBER_OF_WEIGHTS is 2083, to better avoid collisions between * similar strings</li> * <li>Removed dependence on cern.colt MersenneTwister (replaced with * SecureRandom) and QuickBitVector (replaced with local methods).</li> * </ul> * * <hr> * * <P>Instances of this class represent a set of character sequences (with false positives) * using a Bloom filter. Because of the way Bloom filters work, * you cannot remove elements. * * <P>Bloom filters have an expected error rate, depending on the number * of hash functions used, on the filter size and on the number of elements in the filter. This implementation * uses a variable optimal number of hash functions, depending on the expected * number of elements. More precisely, a Bloom * filter for <var>n</var> character sequences with <var>d</var> hash functions will use * ln 2 <var>d</var><var>n</var> &#8776; 1.44 <var>d</var><var>n</var> bits; * false positives will happen with probability 2<sup>-<var>d</var></sup>. * * <P>Hash functions are generated at creation time using universal hashing. Each hash function * uses {@link #NUMBER_OF_WEIGHTS} random integers, which are cyclically multiplied by * the character codes in a character sequence. The resulting integers are XOR-ed together. * * <P>This class exports access methods that are very similar to those of {@link java.util.Set}, * but it does not implement that interface, as too many non-optional methods * would be unimplementable (e.g., iterators). * * @author Sebastiano Vigna */ public class BloomFilter32bp2 implements Serializable, BloomFilter { private static final long serialVersionUID = -2292902803681146635L; /** The number of weights used to create hash functions. */ final public static int NUMBER_OF_WEIGHTS = 2083; // CHANGED FROM 16 /** The number of bits in this filter. */ final public long m; /** the power-of-two that m is */ final public long power; // 1<<power == m /** The number of hash functions used by this filter. */ final public int d; /** The underlying bit vectorS. */ final private int[] bits; /** The random integers used to generate the hash functions. */ final private int[][] weight; /** The number of elements currently in the filter. It may be * smaller than the actual number of additions of distinct character * sequences because of false positives. */ private int size; /** The natural logarithm of 2, used in the computation of the number of bits. */ private final static double NATURAL_LOG_OF_2 = Math.log( 2 ); private final static boolean DEBUG = false; /** Creates a new Bloom filter with given number of hash functions and expected number of elements. * * @param n the expected number of elements. * @param d the number of hash functions; if the filter add not more than <code>n</code> elements, * false positives will happen with probability 2<sup>-<var>d</var></sup>. */ public BloomFilter32bp2( final int n, final int d ) { this.d = d; long minBits = (long) ((long)n * (long)d / NATURAL_LOG_OF_2); long pow = 0; while((1L<<pow) < minBits) { pow++; } this.power = pow; this.m = 1L<<pow; int len = (int) (m / 32); if ( m > 1L<<32 ) { throw new IllegalArgumentException( "This filter would require " + m + " bits" ); } System.out.println("power "+power+" bits "+m+" len "+len); bits = new int[ len ]; if ( DEBUG ) System.err.println( "Number of bits: " + m ); // seeded for reproduceable behavior in repeated runs; BUT: // SecureRandom's default implementation (as of 1.5) // seems to mix in its own seeding. final SecureRandom random = new SecureRandom(new byte[] {19,96}); weight = new int[ d ][]; for( int i = 0; i < d; i++ ) { weight[ i ] = new int[ NUMBER_OF_WEIGHTS ]; for( int j = 0; j < NUMBER_OF_WEIGHTS; j++ ) weight[ i ][ j ] = random.nextInt(); } } /** The number of character sequences in the filter. * * @return the number of character sequences in the filter (but see {@link #contains(CharSequence)}). */ public int size() { return size; } /** Hashes the given sequence with the given hash function. * * @param s a character sequence. * @param l the length of <code>s</code>. * @param k a hash function index (smaller than {@link #d}). * @return the position in the filter corresponding to <code>s</code> for the hash function <code>k</code>. */ private int hash( final CharSequence s, final int l, final int k ) { final int[] w = weight[ k ]; int h = 0, i = l; while( i-- != 0 ) h ^= s.charAt( i ) * w[ i % NUMBER_OF_WEIGHTS ]; return h >>> (32-power); } /** Checks whether the given character sequence is in this filter. * * <P>Note that this method may return true on a character sequence that is has * not been added to the filter. This will happen with probability 2<sub>-<var>d</var></sub>, * where <var>d</var> is the number of hash functions specified at creation time, if * the number of the elements in the filter is less than <var>n</var>, the number * of expected elements specified at creation time. * * @param s a character sequence. * @return true if the sequence is in the filter (or if a sequence with the * same hash sequence is in the filter). */ public boolean contains( final CharSequence s ) { int i = d, l = s.length(); while( i-- != 0 ) if ( ! getBit( hash( s, l, i ) ) ) return false; return true; } /** Adds a character sequence to the filter. * * @param s a character sequence. * @return true if the character sequence was not in the filter (but see {@link #contains(CharSequence)}). */ public boolean add( final CharSequence s ) { boolean result = false; int i = d, l = s.length(); int h; while( i-- != 0 ) { h = hash( s, l, i ); if ( ! getBit( h ) ) result = true; setBit( h ); } if ( result ) size++; return result; } protected final static int ADDRESS_BITS_PER_UNIT = 5; // 32=2^5 protected final static int BIT_INDEX_MASK = 31; // = BITS_PER_UNIT - 1; /** * Returns from the local bitvector the value of the bit with * the specified index. The value is <tt>true</tt> if the bit * with the index <tt>bitIndex</tt> is currently set; otherwise, * returns <tt>false</tt>. * * (adapted from cern.colt.bitvector.QuickBitVector) * * @param bitIndex the bit index. * @return the value of the bit with the specified index. */ protected boolean getBit(int bitIndex) { return ((bits[(int)(bitIndex >>> ADDRESS_BITS_PER_UNIT)] & (1 << (bitIndex & BIT_INDEX_MASK))) != 0); } /** * Changes the bit with index <tt>bitIndex</tt> in local bitvector. * * (adapted from cern.colt.bitvector.QuickBitVector) * * @param bitIndex the index of the bit to be set. */ protected void setBit(int bitIndex) { bits[(int)(bitIndex >>> ADDRESS_BITS_PER_UNIT)] |= 1 << (bitIndex & BIT_INDEX_MASK); } /* (non-Javadoc) * @see org.archive.util.BloomFilter#getSizeBytes() */ public long getSizeBytes() { return bits.length*4; } }
apache-2.0
BigAppOS/BigApp_Discuz_Android
libs/ZUtilsExtWidget/src/com/kit/widget/dialog/DefaultDialog.java
1720
package com.kit.widget.dialog; import java.util.ArrayList; import org.json.JSONException; import org.json.JSONObject; import android.app.Activity; import android.app.ProgressDialog; import android.content.Context; import android.content.DialogInterface; import android.content.Intent; import android.os.AsyncTask; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; public class DefaultDialog extends AbstractDialog { private ProgressDialog pd; private Context context; private boolean isAbleGotoNext; private String content; private int layoutId; private boolean haveCancel; public DefaultDialog(Context context, String content, int layoutId, boolean haveCancel) { super(context, content, layoutId); this.context = context; this.content = content; this.layoutId = layoutId; this.haveCancel = haveCancel; } @Override public void setContent(String content) { // TODO Auto-generated method stub mTVContent.setText(content); } @Override protected void onButtonOK() { // TODO Auto-generated method stub super.onButtonOK(); } /** * @return the isAbleGotoNext */ public boolean isAbleGotoNext() { return isAbleGotoNext; } /** * @param isAbleGotoNext * the isAbleGotoNext to set */ public void setAbleGotoNext(boolean isAbleGotoNext) { this.isAbleGotoNext = isAbleGotoNext; } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (haveCancel) { this.mButtonCancel.setVisibility(View.VISIBLE); } else { this.mButtonCancel.setVisibility(View.GONE); } } }
apache-2.0
galpha/gradoop
gradoop-flink/src/main/java/org/gradoop/flink/algorithms/fsm/transactional/tle/functions/CCSWrapInSubgraphEmbeddings.java
1868
/* * Copyright © 2014 - 2021 Leipzig University (Database Research Group) * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.gradoop.flink.algorithms.fsm.transactional.tle.functions; import com.google.common.collect.Lists; import org.apache.flink.api.common.functions.MapFunction; import org.gradoop.common.model.impl.id.GradoopId; import org.gradoop.flink.algorithms.fsm.transactional.tle.tuples.CCSSubgraph; import org.gradoop.flink.algorithms.fsm.transactional.tle.tuples.CCSSubgraphEmbeddings; /** * {@code subgraphWithSampleEmbedding => subgraphWithEmbeddings} */ public class CCSWrapInSubgraphEmbeddings implements MapFunction<CCSSubgraph, CCSSubgraphEmbeddings> { /** * Reuse tuple to avoid instantiations. */ private final CCSSubgraphEmbeddings reuseTuple; /** * Constructor. */ public CCSWrapInSubgraphEmbeddings() { this.reuseTuple = new CCSSubgraphEmbeddings(); this.reuseTuple.setGraphId(GradoopId.NULL_VALUE); } @Override public CCSSubgraphEmbeddings map(CCSSubgraph subgraph) throws Exception { reuseTuple.setCanonicalLabel(subgraph.getCanonicalLabel()); reuseTuple.setCategory(subgraph.getCategory()); reuseTuple.setSize(subgraph.getEmbedding().getEdges().size()); reuseTuple.setEmbeddings(Lists.newArrayList(subgraph.getEmbedding())); return reuseTuple; } }
apache-2.0
fschopp/cloudkeeper
cloudkeeper-maven/cloudkeeper-maven-bundles/src/test/java/xyz/cloudkeeper/maven/BundlesTest.java
1350
package xyz.cloudkeeper.maven; import org.eclipse.aether.artifact.Artifact; import org.testng.Assert; import org.testng.annotations.Test; import xyz.cloudkeeper.model.immutable.element.Version; import java.net.URI; public class BundlesTest { @Test public void testBundleIdentifierFromMaven() { URI uri = Bundles.bundleIdentifierFromMaven("foo", "bar", Version.valueOf("1.0")); Assert.assertEquals(uri.getScheme(), Bundles.URI_SCHEME); Assert.assertEquals(uri.getSchemeSpecificPart(), "foo:bar:ckbundle:1.0"); } @Test public void testUnresolvedArtifactFromURI() { URI uri = Bundles.bundleIdentifierFromMaven("foo", "bar", Version.valueOf("1.0")); Artifact artifact = Bundles.unresolvedArtifactFromURI(uri); Assert.assertEquals(artifact.getGroupId(), "foo"); Assert.assertEquals(artifact.getArtifactId(), "bar"); Assert.assertEquals(artifact.getVersion(), "1.0"); Assert.assertNull(artifact.getFile()); try { Bundles.unresolvedArtifactFromURI(URI.create("http://127.0.0.1/")); Assert.fail(); } catch (IllegalArgumentException exception) { Assert.assertTrue(exception.getMessage().contains(Bundles.URI_SCHEME) && exception.getMessage().contains(Bundles.ARTIFACT_TYPE)); } } }
apache-2.0
ErikKringen/kafka
streams/src/main/java/org/apache/kafka/streams/processor/internals/CompositeRestoreListener.java
4699
/* * 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.kafka.streams.processor.internals; import org.apache.kafka.common.TopicPartition; import org.apache.kafka.streams.KeyValue; import org.apache.kafka.streams.processor.AbstractNotifyingBatchingRestoreCallback; import org.apache.kafka.streams.processor.BatchingStateRestoreCallback; import org.apache.kafka.streams.processor.StateRestoreCallback; import org.apache.kafka.streams.processor.StateRestoreListener; import java.util.Collection; public class CompositeRestoreListener implements BatchingStateRestoreCallback, StateRestoreListener { public static final NoOpStateRestoreListener NO_OP_STATE_RESTORE_LISTENER = new NoOpStateRestoreListener(); private final BatchingStateRestoreCallback internalBatchingRestoreCallback; private final StateRestoreListener storeRestoreListener; private StateRestoreListener globalRestoreListener = NO_OP_STATE_RESTORE_LISTENER; CompositeRestoreListener(final StateRestoreCallback stateRestoreCallback) { if (stateRestoreCallback instanceof StateRestoreListener) { storeRestoreListener = (StateRestoreListener) stateRestoreCallback; } else { storeRestoreListener = NO_OP_STATE_RESTORE_LISTENER; } internalBatchingRestoreCallback = getBatchingRestoreCallback(stateRestoreCallback); } @Override public void onRestoreStart(final TopicPartition topicPartition, final String storeName, final long startingOffset, final long endingOffset) { globalRestoreListener.onRestoreStart(topicPartition, storeName, startingOffset, endingOffset); storeRestoreListener.onRestoreStart(topicPartition, storeName, startingOffset, endingOffset); } @Override public void onBatchRestored(final TopicPartition topicPartition, final String storeName, final long batchEndOffset, final long numRestored) { globalRestoreListener.onBatchRestored(topicPartition, storeName, batchEndOffset, numRestored); storeRestoreListener.onBatchRestored(topicPartition, storeName, batchEndOffset, numRestored); } @Override public void onRestoreEnd(final TopicPartition topicPartition, final String storeName, final long totalRestored) { globalRestoreListener.onRestoreEnd(topicPartition, storeName, totalRestored); storeRestoreListener.onRestoreEnd(topicPartition, storeName, totalRestored); } @Override public void restoreAll(final Collection<KeyValue<byte[], byte[]>> records) { internalBatchingRestoreCallback.restoreAll(records); } void setGlobalRestoreListener(final StateRestoreListener globalRestoreListener) { if (globalRestoreListener != null) { this.globalRestoreListener = globalRestoreListener; } } @Override public void restore(final byte[] key, final byte[] value) { throw new UnsupportedOperationException("Single restore functionality shouldn't be called directly but " + "through the delegated StateRestoreCallback instance"); } private BatchingStateRestoreCallback getBatchingRestoreCallback(StateRestoreCallback restoreCallback) { if (restoreCallback instanceof BatchingStateRestoreCallback) { return (BatchingStateRestoreCallback) restoreCallback; } return new WrappedBatchingStateRestoreCallback(restoreCallback); } private static final class NoOpStateRestoreListener extends AbstractNotifyingBatchingRestoreCallback { @Override public void restoreAll(final Collection<KeyValue<byte[], byte[]>> records) { } } }
apache-2.0
apache/derby
java/org.apache.derby.engine/org/apache/derby/impl/sql/execute/UniqueIndexSortObserver.java
3367
/* Derby - Class org.apache.derby.impl.sql.execute.UniqueIndexSortObserver 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.derby.impl.sql.execute; import org.apache.derby.catalog.UUID; import org.apache.derby.shared.common.error.StandardException; import org.apache.derby.shared.common.reference.SQLState; import org.apache.derby.iapi.sql.conn.LanguageConnectionContext; import org.apache.derby.iapi.sql.execute.ExecRow; import org.apache.derby.iapi.store.access.BackingStoreHashtable; import org.apache.derby.iapi.store.access.TransactionController; import org.apache.derby.iapi.types.DataValueDescriptor; /** * Unique index aggregator. Enforces uniqueness when * creating a unique index or constraint. * */ class UniqueIndexSortObserver extends BasicSortObserver { private final boolean deferrable; private final boolean deferred; private final String indexOrConstraintName; private final String tableName; private final LanguageConnectionContext lcc; private final UUID constraintId; private BackingStoreHashtable deferredDuplicates; public UniqueIndexSortObserver( LanguageConnectionContext lcc, UUID constraintId, boolean doClone, boolean deferrable, boolean deferred, String indexOrConstraintName, ExecRow execRow, boolean reuseWrappers, String tableName) { super(doClone, !deferred, execRow, reuseWrappers); this.lcc = lcc; this.constraintId = constraintId; this.deferrable = deferrable; this.deferred = deferred; this.indexOrConstraintName = indexOrConstraintName; this.tableName = tableName; } @Override public DataValueDescriptor[] insertDuplicateKey( DataValueDescriptor[] in, DataValueDescriptor[] dup) throws StandardException { StandardException se = null; se = StandardException.newException( SQLState.LANG_DUPLICATE_KEY_CONSTRAINT, indexOrConstraintName, tableName); throw se; } @Override public boolean deferred() { return deferred; } @Override public boolean deferrable() { return deferrable; } @Override public void rememberDuplicate(DataValueDescriptor[] row) throws StandardException { deferredDuplicates = DeferredConstraintsMemory.rememberDuplicate( lcc, deferredDuplicates, constraintId, row); } }
apache-2.0
bitgilde/HyperImage3
hi3-editor/src/org/hyperimage/client/ws/AuthenticatePR.java
3263
package org.hyperimage.client.ws; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlType; /** * <p>Java-Klasse für authenticatePR complex type. * * <p>Das folgende Schemafragment gibt den erwarteten Content an, der in dieser Klasse enthalten ist. * * <pre> * &lt;complexType name="authenticatePR"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="token" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="tokenSecret" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="tokenVerifier" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;element name="userID" type="{http://www.w3.org/2001/XMLSchema}string" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "authenticatePR", propOrder = { "token", "tokenSecret", "tokenVerifier", "userID" }) public class AuthenticatePR { protected String token; protected String tokenSecret; protected String tokenVerifier; protected String userID; /** * Ruft den Wert der token-Eigenschaft ab. * * @return * possible object is * {@link String } * */ public String getToken() { return token; } /** * Legt den Wert der token-Eigenschaft fest. * * @param value * allowed object is * {@link String } * */ public void setToken(String value) { this.token = value; } /** * Ruft den Wert der tokenSecret-Eigenschaft ab. * * @return * possible object is * {@link String } * */ public String getTokenSecret() { return tokenSecret; } /** * Legt den Wert der tokenSecret-Eigenschaft fest. * * @param value * allowed object is * {@link String } * */ public void setTokenSecret(String value) { this.tokenSecret = value; } /** * Ruft den Wert der tokenVerifier-Eigenschaft ab. * * @return * possible object is * {@link String } * */ public String getTokenVerifier() { return tokenVerifier; } /** * Legt den Wert der tokenVerifier-Eigenschaft fest. * * @param value * allowed object is * {@link String } * */ public void setTokenVerifier(String value) { this.tokenVerifier = value; } /** * Ruft den Wert der userID-Eigenschaft ab. * * @return * possible object is * {@link String } * */ public String getUserID() { return userID; } /** * Legt den Wert der userID-Eigenschaft fest. * * @param value * allowed object is * {@link String } * */ public void setUserID(String value) { this.userID = value; } }
apache-2.0
bodar/totallylazy
src/com/googlecode/totallylazy/iterators/InitIterator.java
629
package com.googlecode.totallylazy.iterators; import java.util.Iterator; import java.util.NoSuchElementException; public class InitIterator<T> extends StatefulIterator<T> { private final PeekingIterator<T> peekingIterator; public InitIterator(Iterator<? extends T> iterator) { this.peekingIterator = new PeekingIterator<T>(iterator); } @Override protected T getNext() throws Exception { T next = peekingIterator.next(); try { peekingIterator.peek(); return next; } catch (NoSuchElementException ex){ return finished(); } } }
apache-2.0
kuujo/copycat
primitive/src/main/java/io/atomix/primitive/PrimitiveCache.java
1159
/* * Copyright 2018-present Open Networking 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 io.atomix.primitive; import java.util.concurrent.CompletableFuture; import java.util.function.Supplier; /** * Atomix primitive cache. */ public interface PrimitiveCache { /** * Gets or creates a locally cached multiton primitive instance. * * @param name the primitive name * @param supplier the primitive factory * @param <P> the primitive type * @return the primitive instance */ <P extends DistributedPrimitive> CompletableFuture<P> getPrimitive(String name, Supplier<CompletableFuture<P>> supplier); }
apache-2.0
Wechat-Group/WxJava
weixin-java-mp/src/main/java/me/chanjar/weixin/mp/bean/device/WxDeviceMsg.java
720
package me.chanjar.weixin.mp.bean.device; import com.google.gson.annotations.SerializedName; import lombok.Data; import lombok.EqualsAndHashCode; import me.chanjar.weixin.mp.util.json.WxMpGsonBuilder; /** * @author keungtung. * @date 10/12/2016 */ @Data @EqualsAndHashCode(callSuper = false) public class WxDeviceMsg extends AbstractDeviceBean { private static final long serialVersionUID = -5567110858455277963L; @SerializedName("device_type") private String deviceType; @SerializedName("device_id") private String deviceId; @SerializedName("open_id") private String openId; private String content; @Override public String toString() { return WxMpGsonBuilder.create().toJson(this); } }
apache-2.0
yuzhongyousida/struts-2.3.1.2
src/apps/showcase/target/classes/org/apache/struts2/showcase/validation/SubmitApplication.java
1873
/* * $Id: SubmitApplication.java 471756 2006-11-06 15:01:43Z husted $ * * 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.struts2.showcase.validation; import com.opensymphony.xwork2.ActionSupport; /** * * @version $Date: 2006-11-06 16:01:43 +0100 (Mon, 06 Nov 2006) $ $Id: SubmitApplication.java 471756 2006-11-06 15:01:43Z husted $ */ public class SubmitApplication extends ActionSupport { private String name; private Integer age; public void setName(String name) { this.name = name; } public String getName() { return this.name; } public void setAge(Integer age) { this.age = age; } public Integer getAge() { return age; } public String submitApplication() throws Exception { return SUCCESS; } public String applicationOk() throws Exception { addActionMessage("Your application looks ok."); return SUCCESS; } public String cancelApplication() throws Exception { addActionMessage("So you have decided to cancel the application"); return SUCCESS; } }
apache-2.0
intrigus/jtransc
jtransc-asm/src/com/jtransc/org/objectweb/asm/tree/AnnotationNode.java
8295
/*** * ASM: a very small and fast Java bytecode manipulation framework * Copyright (c) 2000-2011 INRIA, France Telecom * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the copyright holders nor the names of its * contributors may be used to endorse or promote products derived from * this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF * THE POSSIBILITY OF SUCH DAMAGE. */ package com.jtransc.org.objectweb.asm.tree; import java.util.ArrayList; import java.util.List; import com.jtransc.org.objectweb.asm.AnnotationVisitor; import com.jtransc.org.objectweb.asm.Type; import com.jtransc.org.objectweb.asm.Opcodes; /** * A node that represents an annotationn. * * @author Eric Bruneton */ public class AnnotationNode extends AnnotationVisitor { /** * The class descriptor of the annotation class. */ public String desc; /** * The name value pairs of this annotation. Each name value pair is stored * as two consecutive elements in the list. The name is a {@link String}, * and the value may be a {@link Byte}, {@link Boolean}, {@link Character}, * {@link Short}, {@link Integer}, {@link Long}, {@link Float}, * {@link Double}, {@link String} or {@link Type}, or an * two elements String array (for enumeration values), a * {@link AnnotationNode}, or a {@link List} of values of one of the * preceding types. The list may be <tt>null</tt> if there is no name value * pair. */ public List<Object> values; /** * Constructs a new {@link AnnotationNode}. <i>Subclasses must not use this * constructor</i>. Instead, they must use the * {@link #AnnotationNode(int, String)} version. * * @param desc * the class descriptor of the annotation class. * @throws IllegalStateException * If a subclass calls this constructor. */ public AnnotationNode(final String desc) { this(Opcodes.ASM5, desc); if (getClass() != AnnotationNode.class) { throw new IllegalStateException(); } } /** * Constructs a new {@link AnnotationNode}. * * @param api * the ASM API version implemented by this visitor. Must be one * of {@link Opcodes#ASM4} or {@link Opcodes#ASM5}. * @param desc * the class descriptor of the annotation class. */ public AnnotationNode(final int api, final String desc) { super(api); this.desc = desc; } /** * Constructs a new {@link AnnotationNode} to visit an array value. * * @param values * where the visited values must be stored. */ AnnotationNode(final List<Object> values) { super(Opcodes.ASM5); this.values = values; } // ------------------------------------------------------------------------ // Implementation of the AnnotationVisitor abstract class // ------------------------------------------------------------------------ @Override public void visit(final String name, final Object value) { if (values == null) { values = new ArrayList<Object>(this.desc != null ? 2 : 1); } if (this.desc != null) { values.add(name); } values.add(value); } @Override public void visitEnum(final String name, final String desc, final String value) { if (values == null) { values = new ArrayList<Object>(this.desc != null ? 2 : 1); } if (this.desc != null) { values.add(name); } values.add(new String[] { desc, value }); } @Override public AnnotationVisitor visitAnnotation(final String name, final String desc) { if (values == null) { values = new ArrayList<Object>(this.desc != null ? 2 : 1); } if (this.desc != null) { values.add(name); } AnnotationNode annotation = new AnnotationNode(desc); values.add(annotation); return annotation; } @Override public AnnotationVisitor visitArray(final String name) { if (values == null) { values = new ArrayList<Object>(this.desc != null ? 2 : 1); } if (this.desc != null) { values.add(name); } List<Object> array = new ArrayList<Object>(); values.add(array); return new AnnotationNode(array); } @Override public void visitEnd() { } // ------------------------------------------------------------------------ // Accept methods // ------------------------------------------------------------------------ /** * Checks that this annotation node is compatible with the given ASM API * version. This methods checks that this node, and all its nodes * recursively, do not contain elements that were introduced in more recent * versions of the ASM API than the given version. * * @param api * an ASM API version. Must be one of {@link Opcodes#ASM4} or * {@link Opcodes#ASM5}. */ public void check(final int api) { // nothing to do } /** * Makes the given visitor visit this annotation. * * @param av * an annotation visitor. Maybe <tt>null</tt>. */ public void accept(final AnnotationVisitor av) { if (av != null) { if (values != null) { for (int i = 0; i < values.size(); i += 2) { String name = (String) values.get(i); Object value = values.get(i + 1); accept(av, name, value); } } av.visitEnd(); } } /** * Makes the given visitor visit a given annotation value. * * @param av * an annotation visitor. Maybe <tt>null</tt>. * @param name * the value name. * @param value * the actual value. */ static void accept(final AnnotationVisitor av, final String name, final Object value) { if (av != null) { if (value instanceof String[]) { String[] typeconst = (String[]) value; av.visitEnum(name, typeconst[0], typeconst[1]); } else if (value instanceof AnnotationNode) { AnnotationNode an = (AnnotationNode) value; an.accept(av.visitAnnotation(name, an.desc)); } else if (value instanceof List) { AnnotationVisitor v = av.visitArray(name); if (v != null) { List<?> array = (List<?>) value; for (int j = 0; j < array.size(); ++j) { accept(v, null, array.get(j)); } v.visitEnd(); } } else { av.visit(name, value); } } } }
apache-2.0
ggeorg/chillverse
simple-http/src/test/java/org/simpleframework/http/CookieTest.java
2093
package org.simpleframework.http; import junit.framework.TestCase; public class CookieTest extends TestCase { public void testCookies() throws Exception { Cookie cookie = new Cookie("JSESSIONID", "XXX"); cookie.setExpiry(10); cookie.setPath("/path"); System.err.println(cookie); assertTrue(cookie.toString().contains("max-age=10")); assertTrue(cookie.toString().matches(".*expires=\\w\\w\\w, \\d\\d-\\w\\w\\w-\\d\\d\\d\\d \\d\\d:\\d\\d:\\d\\d GMT;.*")); } public void testCookieWithoutExpiry() throws Exception { Cookie cookie = new Cookie("JSESSIONID", "XXX"); cookie.setPath("/path"); System.err.println(cookie); assertFalse(cookie.toString().contains("max-age=10")); assertFalse(cookie.toString().matches(".*expires=\\w\\w\\w, \\d\\d \\w\\w\\w \\d\\d\\d\\d \\d\\d:\\d\\d:\\d\\d GMT;.*")); } public void testSecureCookies() throws Exception { Cookie cookie = new Cookie("JSESSIONID", "XXX"); cookie.setExpiry(10); cookie.setPath("/path"); cookie.setSecure(true); System.err.println(cookie); assertTrue(cookie.toString().contains("max-age=10")); assertTrue(cookie.toString().matches(".*expires=\\w\\w\\w, \\d\\d-\\w\\w\\w-\\d\\d\\d\\d \\d\\d:\\d\\d:\\d\\d GMT;.*")); cookie.setExpiry(10); cookie.setPath("/path"); cookie.setSecure(false); cookie.setProtected(true); System.err.println(cookie); assertTrue(cookie.toString().contains("max-age=10")); assertTrue(cookie.toString().matches(".*expires=\\w\\w\\w, \\d\\d-\\w\\w\\w-\\d\\d\\d\\d \\d\\d:\\d\\d:\\d\\d GMT;.*")); cookie.setExpiry(10); cookie.setPath("/path"); cookie.setSecure(true); cookie.setProtected(true); System.err.println(cookie); assertTrue(cookie.toString().contains("max-age=10")); assertTrue(cookie.toString().matches(".*expires=\\w\\w\\w, \\d\\d-\\w\\w\\w-\\d\\d\\d\\d \\d\\d:\\d\\d:\\d\\d GMT;.*")); } }
apache-2.0
visouza/solr-5.0.0
solr/solrj/src/java/org/apache/solr/client/solrj/SolrQuery.java
30920
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.solr.client.solrj; import org.apache.solr.common.params.CommonParams; import org.apache.solr.common.params.FacetParams; import org.apache.solr.common.params.HighlightParams; import org.apache.solr.common.params.ModifiableSolrParams; import org.apache.solr.common.params.StatsParams; import org.apache.solr.common.params.TermsParams; import org.apache.solr.common.util.DateUtil; import java.util.ArrayList; import java.util.Collections; import java.util.Date; import java.util.List; import java.util.Locale; import java.util.regex.Pattern; /** * This is an augmented SolrParams with get/set/add fields for common fields used * in the Standard and Dismax request handlers * * * @since solr 1.3 */ public class SolrQuery extends ModifiableSolrParams { public static final String DOCID = "_docid_"; // duplicate of org.apache.solr.search.QueryParsing.DOCID which is not accessible from here public enum ORDER { desc, asc; public ORDER reverse() { return (this == asc) ? desc : asc; } } /** Maintains a map of current sorts */ private List<SortClause> sortClauses; public SolrQuery() { super(); } /** Create a new SolrQuery * * @param q query string */ public SolrQuery(String q) { this(); this.set(CommonParams.Q, q); } /** enable/disable terms. * * @param b flag to indicate terms should be enabled. <br /> if b==false, removes all other terms parameters * @return Current reference (<i>this</i>) */ public SolrQuery setTerms(boolean b) { if (b) { this.set(TermsParams.TERMS, true); } else { this.remove(TermsParams.TERMS); this.remove(TermsParams.TERMS_FIELD); this.remove(TermsParams.TERMS_LOWER); this.remove(TermsParams.TERMS_UPPER); this.remove(TermsParams.TERMS_UPPER_INCLUSIVE); this.remove(TermsParams.TERMS_LOWER_INCLUSIVE); this.remove(TermsParams.TERMS_LIMIT); this.remove(TermsParams.TERMS_PREFIX_STR); this.remove(TermsParams.TERMS_MINCOUNT); this.remove(TermsParams.TERMS_MAXCOUNT); this.remove(TermsParams.TERMS_RAW); this.remove(TermsParams.TERMS_SORT); this.remove(TermsParams.TERMS_REGEXP_STR); this.remove(TermsParams.TERMS_REGEXP_FLAG); } return this; } public boolean getTerms() { return this.getBool(TermsParams.TERMS, false); } public SolrQuery addTermsField(String field) { this.add(TermsParams.TERMS_FIELD, field); return this; } public String[] getTermsFields() { return this.getParams(TermsParams.TERMS_FIELD); } public SolrQuery setTermsLower(String lower) { this.set(TermsParams.TERMS_LOWER, lower); return this; } public String getTermsLower() { return this.get(TermsParams.TERMS_LOWER, ""); } public SolrQuery setTermsUpper(String upper) { this.set(TermsParams.TERMS_UPPER, upper); return this; } public String getTermsUpper() { return this.get(TermsParams.TERMS_UPPER, ""); } public SolrQuery setTermsUpperInclusive(boolean b) { this.set(TermsParams.TERMS_UPPER_INCLUSIVE, b); return this; } public boolean getTermsUpperInclusive() { return this.getBool(TermsParams.TERMS_UPPER_INCLUSIVE, false); } public SolrQuery setTermsLowerInclusive(boolean b) { this.set(TermsParams.TERMS_LOWER_INCLUSIVE, b); return this; } public boolean getTermsLowerInclusive() { return this.getBool(TermsParams.TERMS_LOWER_INCLUSIVE, true); } public SolrQuery setTermsLimit(int limit) { this.set(TermsParams.TERMS_LIMIT, limit); return this; } public int getTermsLimit() { return this.getInt(TermsParams.TERMS_LIMIT, 10); } public SolrQuery setTermsMinCount(int cnt) { this.set(TermsParams.TERMS_MINCOUNT, cnt); return this; } public int getTermsMinCount() { return this.getInt(TermsParams.TERMS_MINCOUNT, 1); } public SolrQuery setTermsMaxCount(int cnt) { this.set(TermsParams.TERMS_MAXCOUNT, cnt); return this; } public int getTermsMaxCount() { return this.getInt(TermsParams.TERMS_MAXCOUNT, -1); } public SolrQuery setTermsPrefix(String prefix) { this.set(TermsParams.TERMS_PREFIX_STR, prefix); return this; } public String getTermsPrefix() { return this.get(TermsParams.TERMS_PREFIX_STR, ""); } public SolrQuery setTermsRaw(boolean b) { this.set(TermsParams.TERMS_RAW, b); return this; } public boolean getTermsRaw() { return this.getBool(TermsParams.TERMS_RAW, false); } public SolrQuery setTermsSortString(String type) { this.set(TermsParams.TERMS_SORT, type); return this; } public String getTermsSortString() { return this.get(TermsParams.TERMS_SORT, TermsParams.TERMS_SORT_COUNT); } public SolrQuery setTermsRegex(String regex) { this.set(TermsParams.TERMS_REGEXP_STR, regex); return this; } public String getTermsRegex() { return this.get(TermsParams.TERMS_REGEXP_STR); } public SolrQuery setTermsRegexFlag(String flag) { this.add(TermsParams.TERMS_REGEXP_FLAG, flag); return this; } public String[] getTermsRegexFlags() { return this.getParams(TermsParams.TERMS_REGEXP_FLAG); } /** Add field(s) for facet computation. * * @param fields Array of field names from the IndexSchema * @return this */ public SolrQuery addFacetField(String ... fields) { add(FacetParams.FACET_FIELD, fields); this.set(FacetParams.FACET, true); return this; } /** Add field(s) for pivot computation. * * pivot fields are comma separated * * @param fields Array of field names from the IndexSchema * @return this */ public SolrQuery addFacetPivotField(String ... fields) { add(FacetParams.FACET_PIVOT, fields); this.set(FacetParams.FACET, true); return this; } /** * Add a numeric range facet. * * @param field The field * @param start The start of range * @param end The end of the range * @param gap The gap between each count * @return this */ public SolrQuery addNumericRangeFacet(String field, Number start, Number end, Number gap) { add(FacetParams.FACET_RANGE, field); add(String.format(Locale.ROOT, "f.%s.%s", field, FacetParams.FACET_RANGE_START), start.toString()); add(String.format(Locale.ROOT, "f.%s.%s", field, FacetParams.FACET_RANGE_END), end.toString()); add(String.format(Locale.ROOT, "f.%s.%s", field, FacetParams.FACET_RANGE_GAP), gap.toString()); this.set(FacetParams.FACET, true); return this; } /** * Add a numeric range facet. * * @param field The field * @param start The start of range * @param end The end of the range * @param gap The gap between each count * @return this */ public SolrQuery addDateRangeFacet(String field, Date start, Date end, String gap) { add(FacetParams.FACET_RANGE, field); add(String.format(Locale.ROOT, "f.%s.%s", field, FacetParams.FACET_RANGE_START), DateUtil.getThreadLocalDateFormat().format(start)); add(String.format(Locale.ROOT, "f.%s.%s", field, FacetParams.FACET_RANGE_END), DateUtil.getThreadLocalDateFormat().format(end)); add(String.format(Locale.ROOT, "f.%s.%s", field, FacetParams.FACET_RANGE_GAP), gap); this.set(FacetParams.FACET, true); return this; } /** * Add Interval Faceting on a field. All intervals for the same field should be included * in the same call to this method. * For syntax documentation see <a href="https://wiki.apache.org/solr/SimpleFacetParameters#Interval_Faceting">Solr wiki</a> * * @param field the field to add facet intervals * @param intervals Intervals to be used for faceting. It can be an empty array, but it can't * be <code>null</code> * @return this */ public SolrQuery addIntervalFacets(String field, String[] intervals) { if (intervals == null) { throw new IllegalArgumentException("Can't add null intervals"); } set(FacetParams.FACET, true); add(FacetParams.FACET_INTERVAL, field); for (String interval:intervals) { add(String.format(Locale.ROOT, "f.%s.facet.interval.set", field), interval); } return this; } /** * Remove all Interval Facets on a field * * @param field the field to remove from facet intervals * @return Array of current intervals for <code>field</code> */ public String[] removeIntervalFacets(String field) { while(remove(FacetParams.FACET_INTERVAL, field)){}; return remove(String.format(Locale.ROOT, "f.%s.facet.interval.set", field)); } /** get the facet fields * * @return string array of facet fields or null if not set/empty */ public String[] getFacetFields() { return this.getParams(FacetParams.FACET_FIELD); } /** remove a facet field * * @param name Name of the facet field to be removed. * * @return true, if the item was removed. <br /> * false, if the facet field was null or did not exist. */ public boolean removeFacetField(String name) { boolean b = this.remove(FacetParams.FACET_FIELD, name); if (this.get(FacetParams.FACET_FIELD) == null && this.get(FacetParams.FACET_QUERY) == null) { this.setFacet(false); } return b; } /** enable/disable faceting. * * @param b flag to indicate faceting should be enabled. <br /> if b==false, removes all other faceting parameters * @return Current reference (<i>this</i>) */ public SolrQuery setFacet(boolean b) { if (b) { this.set(FacetParams.FACET, true); } else { this.remove(FacetParams.FACET); this.remove(FacetParams.FACET_MINCOUNT); this.remove(FacetParams.FACET_FIELD); this.remove(FacetParams.FACET_LIMIT); this.remove(FacetParams.FACET_MISSING); this.remove(FacetParams.FACET_OFFSET); this.remove(FacetParams.FACET_PREFIX); this.remove(FacetParams.FACET_QUERY); this.remove(FacetParams.FACET_SORT); this.remove(FacetParams.FACET_ZEROS); this.remove(FacetParams.FACET_PREFIX); // does not include the individual fields... this.remove(FacetParams.FACET_INTERVAL); // does not remove interval parameters } return this; } public SolrQuery setFacetPrefix( String prefix ) { this.set( FacetParams.FACET_PREFIX, prefix ); return this; } public SolrQuery setFacetPrefix( String field, String prefix ) { this.set( "f."+field+"."+FacetParams.FACET_PREFIX, prefix ); return this; } /** add a faceting query * * @param f facet query */ public SolrQuery addFacetQuery(String f) { this.add(FacetParams.FACET_QUERY, f); this.set(FacetParams.FACET, true); return this; } /** get facet queries * * @return all facet queries or null if not set/empty */ public String[] getFacetQuery() { return this.getParams(FacetParams.FACET_QUERY); } /** remove a facet query * * @param q the facet query to remove * @return true if the facet query was removed false otherwise */ public boolean removeFacetQuery(String q) { boolean b = this.remove(FacetParams.FACET_QUERY, q); if (this.get(FacetParams.FACET_FIELD) == null && this.get(FacetParams.FACET_QUERY) == null) { this.setFacet(false); } return b; } /** set the facet limit * * @param lim number facet items to return */ public SolrQuery setFacetLimit(int lim) { this.set(FacetParams.FACET_LIMIT, lim); return this; } /** get current facet limit * * @return facet limit or default of 25 */ public int getFacetLimit() { return this.getInt(FacetParams.FACET_LIMIT, 25); } /** set facet minimum count * * @param cnt facets having less that cnt hits will be excluded from teh facet list */ public SolrQuery setFacetMinCount(int cnt) { this.set(FacetParams.FACET_MINCOUNT, cnt); return this; } /** get facet minimum count * * @return facet minimum count or default of 1 */ public int getFacetMinCount() { return this.getInt(FacetParams.FACET_MINCOUNT, 1); } /** * Sets facet missing boolean flag * * @param v flag to indicate the field of {@link FacetParams#FACET_MISSING} . * @return this */ public SolrQuery setFacetMissing(Boolean v) { this.set(FacetParams.FACET_MISSING, v); return this; } /** get facet sort * * @return facet sort or default of {@link FacetParams#FACET_SORT_COUNT} */ public String getFacetSortString() { return this.get(FacetParams.FACET_SORT, FacetParams.FACET_SORT_COUNT); } /** set facet sort * * @param sort sort facets * @return this */ public SolrQuery setFacetSort(String sort) { this.set(FacetParams.FACET_SORT, sort); return this; } /** add highlight field * * @param f field to enable for highlighting */ public SolrQuery addHighlightField(String f) { this.add(HighlightParams.FIELDS, f); this.set(HighlightParams.HIGHLIGHT, true); return this; } /** remove a field for highlighting * * @param f field name to not highlight * @return <i>true</i>, if removed, <br /> <i>false</i>, otherwise */ public boolean removeHighlightField(String f) { boolean b = this.remove(HighlightParams.FIELDS, f); if (this.get(HighlightParams.FIELDS) == null) { this.setHighlight(false); } return b; } /** get list of highlighted fields * * @return Array of highlight fields or null if not set/empty */ public String[] getHighlightFields() { return this.getParams(HighlightParams.FIELDS); } public SolrQuery setHighlightSnippets(int num) { this.set(HighlightParams.SNIPPETS, num); return this; } public int getHighlightSnippets() { return this.getInt(HighlightParams.SNIPPETS, 1); } public SolrQuery setHighlightFragsize(int num) { this.set(HighlightParams.FRAGSIZE, num); return this; } public int getHighlightFragsize() { return this.getInt(HighlightParams.FRAGSIZE, 100); } public SolrQuery setHighlightRequireFieldMatch(boolean flag) { this.set(HighlightParams.FIELD_MATCH, flag); return this; } public boolean getHighlightRequireFieldMatch() { return this.getBool(HighlightParams.FIELD_MATCH, false); } public SolrQuery setHighlightSimplePre(String f) { this.set(HighlightParams.SIMPLE_PRE, f); return this; } public String getHighlightSimplePre() { return this.get(HighlightParams.SIMPLE_PRE, ""); } public SolrQuery setHighlightSimplePost(String f) { this.set(HighlightParams.SIMPLE_POST, f); return this; } public String getHighlightSimplePost() { return this.get(HighlightParams.SIMPLE_POST, ""); } /** * Gets the raw sort field, as it will be sent to Solr. * <p> * The returned sort field will always contain a serialized version * of the sort string built using {@link #setSort(SortClause)}, * {@link #addSort(SortClause)}, {@link #addOrUpdateSort(SortClause)}, * {@link #removeSort(SortClause)}, {@link #clearSorts()} and * {@link #setSorts(List)}. */ public String getSortField() { return this.get(CommonParams.SORT); } /** * Clears current sort information. * * @return the modified SolrQuery object, for easy chaining * @since 4.2 */ public SolrQuery clearSorts() { sortClauses = null; serializeSorts(); return this; } /** * Replaces the current sort information. * * @return the modified SolrQuery object, for easy chaining * @since 4.2 */ public SolrQuery setSorts(List<SortClause> value) { sortClauses = new ArrayList<>(value); serializeSorts(); return this; } /** * Gets an a list of current sort clauses. * * @return an immutable list of current sort clauses * @since 4.2 */ public List<SortClause> getSorts() { if (sortClauses == null) return Collections.emptyList(); else return Collections.unmodifiableList(sortClauses); } /** * Replaces the current sort information with a single sort clause * * @return the modified SolrQuery object, for easy chaining * @since 4.2 */ public SolrQuery setSort(String field, ORDER order) { return setSort(new SortClause(field, order)); } /** * Replaces the current sort information with a single sort clause * * @return the modified SolrQuery object, for easy chaining * @since 4.2 */ public SolrQuery setSort(SortClause sortClause) { clearSorts(); return addSort(sortClause); } /** * Adds a single sort clause to the end of the current sort information. * * @return the modified SolrQuery object, for easy chaining * @since 4.2 */ public SolrQuery addSort(String field, ORDER order) { return addSort(new SortClause(field, order)); } /** * Adds a single sort clause to the end of the query. * * @return the modified SolrQuery object, for easy chaining * @since 4.2 */ public SolrQuery addSort(SortClause sortClause) { if (sortClauses == null) sortClauses = new ArrayList<>(); sortClauses.add(sortClause); serializeSorts(); return this; } /** * Updates or adds a single sort clause to the query. * If the field is already used for sorting, the order * of the existing field is modified; otherwise, it is * added to the end. * <p> * @return the modified SolrQuery object, for easy chaining * @since 4.2 */ public SolrQuery addOrUpdateSort(String field, ORDER order) { return addOrUpdateSort(new SortClause(field, order)); } /** * Updates or adds a single sort field specification to the current sort * information. If the sort field already exist in the sort information map, * its position is unchanged and the sort order is set; if it does not exist, * it is appended at the end with the specified order.. * * @return the modified SolrQuery object, for easy chaining * @since 4.2 */ public SolrQuery addOrUpdateSort(SortClause sortClause) { if (sortClauses != null) { for (int index=0 ; index<sortClauses.size() ; index++) { SortClause existing = sortClauses.get(index); if (existing.getItem().equals(sortClause.getItem())) { sortClauses.set(index, sortClause); serializeSorts(); return this; } } } return addSort(sortClause); } /** * Removes a single sort field from the current sort information. * * @return the modified SolrQuery object, for easy chaining * @since 4.2 */ public SolrQuery removeSort(SortClause sortClause) { return removeSort(sortClause.getItem()); } /** * Removes a single sort field from the current sort information. * * @return the modified SolrQuery object, for easy chaining * @since 4.2 */ public SolrQuery removeSort(String itemName) { if (sortClauses != null) { for (SortClause existing : sortClauses) { if (existing.getItem().equals(itemName)) { sortClauses.remove(existing); if (sortClauses.isEmpty()) sortClauses = null; serializeSorts(); break; } } } return this; } private void serializeSorts() { if (sortClauses == null || sortClauses.isEmpty()) { remove(CommonParams.SORT); } else { StringBuilder sb = new StringBuilder(); for (SortClause sortClause : sortClauses) { if (sb.length() > 0) sb.append(","); sb.append(sortClause.getItem()); sb.append(" "); sb.append(sortClause.getOrder()); } set(CommonParams.SORT, sb.toString()); } } public void setGetFieldStatistics( boolean v ) { this.set( StatsParams.STATS, v ); } public void setGetFieldStatistics( String field ) { this.set( StatsParams.STATS, true ); this.add( StatsParams.STATS_FIELD, field ); } public void addGetFieldStatistics( String ... field ) { this.set( StatsParams.STATS, true ); this.add( StatsParams.STATS_FIELD, field ); } public void addStatsFieldFacets( String field, String ... facets ) { if( field == null ) { this.add( StatsParams.STATS_FACET, facets ); } else { for( String f : facets ) { this.add( "f."+field+"."+StatsParams.STATS_FACET, f ); } } } public void addStatsFieldCalcDistinct(String field, boolean calcDistinct) { if (field == null) { this.add(StatsParams.STATS_CALC_DISTINCT, Boolean.toString(calcDistinct)); } else { this.add("f." + field + "." + StatsParams.STATS_CALC_DISTINCT, Boolean.toString(calcDistinct)); } } public SolrQuery setFilterQueries(String ... fq) { this.set(CommonParams.FQ, fq); return this; } public SolrQuery addFilterQuery(String ... fq) { this.add(CommonParams.FQ, fq); return this; } public boolean removeFilterQuery(String fq) { return this.remove(CommonParams.FQ, fq); } public String[] getFilterQueries() { return this.getParams(CommonParams.FQ); } public boolean getHighlight() { return this.getBool(HighlightParams.HIGHLIGHT, false); } public SolrQuery setHighlight(boolean b) { if (b) { this.set(HighlightParams.HIGHLIGHT, true); } else { this.remove(HighlightParams.HIGHLIGHT); this.remove(HighlightParams.FIELD_MATCH); this.remove(HighlightParams.FIELDS); this.remove(HighlightParams.FORMATTER); this.remove(HighlightParams.FRAGSIZE); this.remove(HighlightParams.SIMPLE_POST); this.remove(HighlightParams.SIMPLE_PRE); this.remove(HighlightParams.SNIPPETS); } return this; } public SolrQuery setFields(String ... fields) { if( fields == null || fields.length == 0 ) { this.remove( CommonParams.FL ); return this; } StringBuilder sb = new StringBuilder(); sb.append( fields[0] ); for( int i=1; i<fields.length; i++ ) { sb.append( ',' ); sb.append( fields[i] ); } this.set(CommonParams.FL, sb.toString() ); return this; } public SolrQuery addField(String field) { return addValueToParam(CommonParams.FL, field); } public String getFields() { String fields = this.get(CommonParams.FL); if (fields!=null && fields.equals("score")) { fields = "*, score"; } return fields; } private static Pattern scorePattern = Pattern.compile("(^|[, ])score"); public SolrQuery setIncludeScore(boolean includeScore) { String fields = get(CommonParams.FL,"*"); if (includeScore) { if (!scorePattern.matcher(fields).find()) { this.set(CommonParams.FL, fields+",score"); } } else { this.set(CommonParams.FL, scorePattern.matcher(fields).replaceAll("")); } return this; } public SolrQuery setQuery(String query) { this.set(CommonParams.Q, query); return this; } public String getQuery() { return this.get(CommonParams.Q); } public SolrQuery setRows(Integer rows) { if( rows == null ) { this.remove( CommonParams.ROWS ); } else { this.set(CommonParams.ROWS, rows); } return this; } public Integer getRows() { return this.getInt(CommonParams.ROWS); } public void setShowDebugInfo(boolean showDebugInfo) { this.set(CommonParams.DEBUG_QUERY, String.valueOf(showDebugInfo)); } public void setDistrib(boolean val) { this.set(CommonParams.DISTRIB, String.valueOf(val)); } public SolrQuery setStart(Integer start) { if( start == null ) { this.remove( CommonParams.START ); } else { this.set(CommonParams.START, start); } return this; } public Integer getStart() { return this.getInt(CommonParams.START); } /** * The Request Handler to use (see the solrconfig.xml), which is stored in the "qt" parameter. * Normally it starts with a '/' and if so it will be used by * {@link org.apache.solr.client.solrj.request.QueryRequest#getPath()} in the URL instead of the "qt" parameter. * If this is left blank, then the default of "/select" is assumed. * * @param qt The Request Handler name corresponding to one in solrconfig.xml on the server. * @return this */ public SolrQuery setRequestHandler(String qt) { this.set(CommonParams.QT, qt); return this; } public String getRequestHandler() { return this.get(CommonParams.QT); } /** * @return this * @see ModifiableSolrParams#set(String,String[]) */ public SolrQuery setParam(String name, String ... values) { this.set(name, values); return this; } /** * @return this * @see org.apache.solr.common.params.ModifiableSolrParams#set(String, boolean) */ public SolrQuery setParam(String name, boolean value) { this.set(name, value); return this; } /** get a deep copy of this object **/ public SolrQuery getCopy() { SolrQuery q = new SolrQuery(); for (String name : this.getParameterNames()) { q.setParam(name, this.getParams(name)); } return q; } /** * Set the maximum time allowed for this query. If the query takes more time * than the specified milliseconds, a timeout occurs and partial (or no) * results may be returned. * * If given Integer is null, then this parameter is removed from the request * *@param milliseconds the time in milliseconds allowed for this query */ public SolrQuery setTimeAllowed(Integer milliseconds) { if (milliseconds == null) { this.remove(CommonParams.TIME_ALLOWED); } else { this.set(CommonParams.TIME_ALLOWED, milliseconds); } return this; } /** * Get the maximum time allowed for this query. */ public Integer getTimeAllowed() { return this.getInt(CommonParams.TIME_ALLOWED); } /////////////////////// // Utility functions /////////////////////// private String toSortString(String field, ORDER order) { return field.trim() + ' ' + String.valueOf(order).trim(); } private String join(String a, String b, String sep) { StringBuilder sb = new StringBuilder(); if (a!=null && a.length()>0) { sb.append(a); sb.append(sep); } if (b!=null && b.length()>0) { sb.append(b); } return sb.toString().trim(); } private SolrQuery addValueToParam(String name, String value) { String tmp = this.get(name); tmp = join(tmp, value, ","); this.set(name, tmp); return this; } private String join(String[] vals, String sep, String removeVal) { StringBuilder sb = new StringBuilder(); for (int i=0; i<vals.length; i++) { if (!vals[i].equals(removeVal)) { if (sb.length() > 0) { sb.append(sep); } sb.append(vals[i]); } } return sb.toString().trim(); } /** * A single sort clause, encapsulating what to sort and the sort order. * <p> * The item specified can be "anything sortable" by solr; some examples * include a simple field name, the constant string {@code score}, and functions * such as {@code sum(x_f, y_f)}. * <p> * A SortClause can be created through different mechanisms: * <PRE><code> * new SortClause("product", SolrQuery.ORDER.asc); * new SortClause("product", "asc"); * SortClause.asc("product"); * SortClause.desc("product"); * </code></PRE> */ public static class SortClause implements java.io.Serializable { private static final long serialVersionUID = 1L; private final String item; private final ORDER order; /** * Creates a SortClause based on item and order * @param item item to sort on * @param order direction to sort */ public SortClause(String item, ORDER order) { this.item = item; this.order = order; } /** * Creates a SortClause based on item and order * @param item item to sort on * @param order string value for direction to sort */ public SortClause(String item, String order) { this(item, ORDER.valueOf(order)); } /** * Creates an ascending SortClause for an item * @param item item to sort on */ public static SortClause create (String item, ORDER order) { return new SortClause(item, order); } /** * Creates a SortClause based on item and order * @param item item to sort on * @param order string value for direction to sort */ public static SortClause create(String item, String order) { return new SortClause(item, ORDER.valueOf(order)); } /** * Creates an ascending SortClause for an item * @param item item to sort on */ public static SortClause asc (String item) { return new SortClause(item, ORDER.asc); } /** * Creates a decending SortClause for an item * @param item item to sort on */ public static SortClause desc (String item) { return new SortClause(item, ORDER.desc); } /** * Gets the item to sort, typically a function or a fieldname * @return item to sort */ public String getItem() { return item; } /** * Gets the order to sort * @return order to sort */ public ORDER getOrder() { return order; } public boolean equals(Object other){ if (this == other) return true; if (!(other instanceof SortClause)) return false; final SortClause that = (SortClause) other; return this.getItem().equals(that.getItem()) && this.getOrder().equals(that.getOrder()); } public int hashCode(){ return this.getItem().hashCode(); } /** * Gets a human readable description of the sort clause. * <p> * The returned string is not suitable for passing to Solr, * but may be useful in debug output and the like. * @return a description of the current sort clause */ public String toString() { return "[" + getClass().getSimpleName() + ": item=" + getItem() + "; order=" + getOrder() + "]"; } } }
apache-2.0
3-Round-Stones/callimachus
src/org/callimachusproject/xproc/SerializeJsonStep.java
4199
/* * Copyright (c) 2013 3 Round Stones Inc., Some Rights Reserved * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.callimachusproject.xproc; import java.io.PrintWriter; import java.io.StringWriter; import net.sf.saxon.s9api.Axis; import net.sf.saxon.s9api.QName; import net.sf.saxon.s9api.SaxonApiException; import net.sf.saxon.s9api.XdmItem; import net.sf.saxon.s9api.XdmNode; import net.sf.saxon.s9api.XdmNodeKind; import net.sf.saxon.s9api.XdmSequenceIterator; import com.xmlcalabash.core.XProcConstants; import com.xmlcalabash.core.XProcException; import com.xmlcalabash.core.XProcRuntime; import com.xmlcalabash.core.XProcStep; import com.xmlcalabash.io.ReadablePipe; import com.xmlcalabash.io.WritablePipe; import com.xmlcalabash.model.RuntimeValue; import com.xmlcalabash.runtime.XAtomicStep; import com.xmlcalabash.util.S9apiUtils; import com.xmlcalabash.util.TreeWriter; import com.xmlcalabash.util.XMLtoJSON; public class SerializeJsonStep implements XProcStep { private static final QName _content_type = new QName("content-type"); private final XProcRuntime runtime; private final XAtomicStep step; private String contentType = "application/json"; private ReadablePipe source; private WritablePipe result; public SerializeJsonStep(XProcRuntime runtime, XAtomicStep step) { this.runtime = runtime; this.step = step; } @Override public void setParameter(QName name, RuntimeValue value) { throw new XProcException("No parameters allowed."); } @Override public void setParameter(String port, QName name, RuntimeValue value) { setParameter(name, value); } @Override public void setOption(QName name, RuntimeValue value) { if ("content-type".equals(name.getLocalName())) { contentType = value.getString(); } } public void setInput(String port, ReadablePipe pipe) { source = pipe; } public void setOutput(String port, WritablePipe pipe) { result = pipe; } public void reset() { source.resetReader(); result.resetWriter(); } @Override public void run() throws SaxonApiException { while (source.moreDocuments()) { XdmNode doc = source.read(); XdmNode root = S9apiUtils.getDocumentElement(doc); String contentType = getContentType(root); XdmNode json = getJsonNode(root); StringWriter out = new StringWriter(); if (json != null) { PrintWriter writer = new PrintWriter(out); writer.print(XMLtoJSON.convert(json)); writer.close(); } TreeWriter tree = new TreeWriter(runtime); tree.startDocument(step.getNode().getBaseURI()); tree.addStartElement(XProcConstants.c_data); tree.addAttribute(_content_type, contentType); tree.startContent(); tree.addText(out.toString()); tree.addEndElement(); tree.endDocument(); result.write(tree.getResult()); } } private String getContentType(XdmNode root) { if (this.contentType == null && root != null) { return root.getAttributeValue(_content_type); } else { return this.contentType; } } private XdmNode getJsonNode(XdmNode root) { if (root == null) return root; QName name = root.getNodeName(); if (XProcConstants.c_data.equals(name) || XProcConstants.c_body.equals(name)) { XdmNode jchild = null; XdmSequenceIterator iter = root.axisIterator(Axis.CHILD); while (iter.hasNext()) { XdmItem item = iter.next(); if (item instanceof XdmNode) { XdmNode child = (XdmNode) item; if (child.getNodeKind() == XdmNodeKind.ELEMENT) { if (jchild != null) { throw new XProcException( "Found more than one JSON element?"); } else { jchild = child; } } } } return jchild; } else { return root; } } }
apache-2.0
B2M-Software/project-drahtlos-smg20
remoteframework.lib/src/main/java/org/fortiss/smg/remoteframework/lib/DefaultProxy.java
622
package org.fortiss.smg.remoteframework.lib; import java.io.IOException; import java.util.concurrent.TimeoutException; public class DefaultProxy<T> extends GenericProxy { private RabbitRPCProxy<T> proxy; public DefaultProxy(Class klass, String queue, int timeout) { super(klass, queue, timeout); proxy = new RabbitRPCProxy<T>(klass, queue, timeout); } @Override public T init() throws IOException, TimeoutException { return proxy.init(); } @Override public void destroy() throws IOException { proxy.destroy(); } @Override public T initLoop() throws IOException { return proxy.initLoop(); } }
apache-2.0