repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
GreenDelta/olca-updates
src/main/java/org/openlca/updates/VersionState.java
1048
package org.openlca.updates; import org.openlca.core.database.IDatabase; import org.openlca.updates.legacy.Upgrades; /** * The result of a version check of a database. */ public enum VersionState { /** * The database is up to date. */ UP_TO_DATE, /** * The database requires updates (provided by new update concept). */ NEEDS_UPDATE, /** * The database requires updates (provided by legacy upgrade concept). */ NEEDS_UPGRADE, /** * The database is newer than the version of openLCA. */ HIGHER_VERSION, /** * Could not get the version because of an error. */ ERROR; public static VersionState checkVersion(IDatabase database) { int version = database.getVersion(); if (version < 1) return VersionState.ERROR; if (version == IDatabase.CURRENT_VERSION) return VersionState.UP_TO_DATE; if (version < IDatabase.CURRENT_VERSION) if (version < Upgrades.FINAL_UPGRADE) return VersionState.NEEDS_UPGRADE; else return VersionState.NEEDS_UPDATE; return VersionState.HIGHER_VERSION; } }
mpl-2.0
tbouvet/seed
rest/specs/src/main/java/org/seedstack/seed/rest/api/hal/Link.java
3707
/** * Copyright (c) 2013-2015, The SeedStack authors <http://seedstack.org> * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.seedstack.seed.rest.api.hal; import com.damnhandy.uri.template.UriTemplate; import com.fasterxml.jackson.annotation.JsonInclude; import java.net.URI; import java.util.HashMap; import java.util.Map; /** * Defines a Link representation as described by the * <a href=https://tools.ietf.org/html/draft-kelly-json-hal-06#section-5>HAL specification</a>. * * @author pierre.thirouin@ext.mpsa.com (Pierre Thirouin) */ @JsonInclude(JsonInclude.Include.NON_DEFAULT) public class Link { private String href; private boolean templated = false; private String type; private String deprecation; private String name; private URI profile; private String title; private String hrefLang; private Map<String, Object> hrefVars = new HashMap<String, Object>(); /** * Default constructor required by Jackson. */ Link() { } /** * Constructor. * * @param href the href */ public Link(String href) { this.href = href; } /** * Copy constructor. * * @param link link to copy */ public Link(Link link) { this.href = link.href; this.templated = link.templated; this.type = link.type; this.deprecation = link.deprecation; this.name = link.name; this.profile = link.profile; this.title = link.title; this.hrefLang = link.hrefLang; this.hrefVars = link.hrefVars; } /** * Indicates that the href is templated. * * @return itself */ public Link templated() { this.templated = true; return this; } /** * Indicates that the resource is deprecated and * specify the URI for deprecation information. * * @param deprecation the deprecation URI * @return itself */ public Link deprecate(String deprecation) { this.deprecation = deprecation; return this; } /** * Indicates the media type used by the resource. * * @param type the media type */ public void type(String type) { this.type = type; } /** * Specifies an additional name for the link. * * @param name the link name * @return itself */ public Link name(String name) { this.name = name; return this; } public Link profile(URI profile) { this.profile = profile; return this; } public Link title(String title) { this.title = title; return this; } public Link hrefLang(String hrefLang) { this.hrefLang = hrefLang; return this; } public String getHref() { return href; } public Link set(String variableName, Object value) { Link link = new Link(this); link.hrefVars.put(variableName, value); return link; } public String expand() { return UriTemplate.fromTemplate(href).expand(hrefVars); } public boolean isTemplated() { return templated; } public String getType() { return type; } public String getDeprecation() { return deprecation; } public String getName() { return name; } public URI getProfile() { return profile; } public String getTitle() { return title; } public String getHrefLang() { return hrefLang; } }
mpl-2.0
Appverse/appverse-web
framework/modules/backend/core/api/src/main/java/org/appverse/web/framework/backend/api/model/business/StaticDataBusinessBean.java
2054
/* Copyright (c) 2012 GFT Appverse, S.L., Sociedad Unipersonal. This Source Code Form is subject to the terms of the Appverse Public License Version 2.0 (“APL v2.0”). If a copy of the APL was not distributed with this file, You can obtain one at http://www.appverse.mobi/licenses/apl_v2.0.pdf. [^] Redistribution and use in source and binary forms, with or without modification, are permitted provided that the conditions of the AppVerse Public License v2.0 are met. 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. EXCEPT IN CASE OF WILLFUL MISCONDUCT OR GROSS NEGLIGENCE, IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ package org.appverse.web.framework.backend.api.model.business; public class StaticDataBusinessBean extends AbstractBusinessBean { private static final long serialVersionUID = 1L; private String valueDisplayName; private String valueName; private long valueOrder; public String getValueDisplayName() { return valueDisplayName; } public String getValueName() { return valueName; } public long getValueOrder() { return valueOrder; } public void setValueDisplayName(final String valueDisplayName) { this.valueDisplayName = valueDisplayName; } public void setValueName(final String valueName) { this.valueName = valueName; } public void setValueOrder(final long valueOrder) { this.valueOrder = valueOrder; } }
mpl-2.0
seedstack/audit-addon
logback/src/main/java/org/seedstack/audit/logback/internal/AuditLogbackPlugin.java
649
/* * Copyright © 2013-2020, The SeedStack authors <http://seedstack.org> * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.seedstack.audit.logback.internal; import io.nuun.kernel.core.AbstractPlugin; /** * Audit logback plugin. */ public class AuditLogbackPlugin extends AbstractPlugin { @Override public String name() { return "audit-logback"; } @Override public Object nativeUnitModule() { return new AuditLogbackModule(); } }
mpl-2.0
eventsourcing/es4j
examples/foodsourcing/src/main/java/foodsourcing/Order.java
2954
/** * Copyright (c) 2016, All Contributors (see CONTRIBUTORS file) * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package foodsourcing; import com.eventsourcing.EntityHandle; import com.eventsourcing.Repository; import com.eventsourcing.layout.LayoutConstructor; import com.eventsourcing.queries.ModelQueries; import com.googlecode.cqengine.resultset.ResultSet; import foodsourcing.events.OrderConfirmed; import foodsourcing.events.OrderPlaced; import lombok.Getter; import lombok.Value; import lombok.experimental.Accessors; import java.math.BigDecimal; import java.util.Optional; import java.util.UUID; import static com.eventsourcing.queries.QueryFactory.equal; import static foodsourcing.Order.Status.CONFIRMED; public class Order { @Value @Accessors(fluent = true) public static class Item { UUID menuItem; int quantity; @LayoutConstructor public Item(UUID menuItem, int quantity) { this.menuItem = menuItem; this.quantity = quantity; } public Item(MenuItem menuItem, int quantity) { this.menuItem = menuItem.getId(); this.quantity = quantity; } } @Getter private final Repository repository; @Getter private final UUID id; @Override public boolean equals(Object obj) { return obj instanceof Restaurant && getId().equals(((Restaurant) obj).getId()); } @Override public int hashCode() { return id.hashCode(); } public BigDecimal price() { Optional<OrderPlaced> orderPlaced = ModelQueries.lookup(repository, OrderPlaced.class, OrderPlaced.ID, id); return orderPlaced.get().items().stream() .map(i -> MenuItem.lookup(repository, i.menuItem()) .get().price().multiply(new BigDecimal(i.quantity()))) .reduce(BigDecimal.ZERO, BigDecimal::add); } enum Status { PLACED, CONFIRMED } public Status status() { try (ResultSet<EntityHandle<OrderConfirmed>> resultSet = repository .query(OrderConfirmed.class, equal(OrderConfirmed.REFERENCE, getId()))) { return resultSet.isEmpty() ? Status.PLACED : CONFIRMED; } } protected Order(Repository repository, UUID id) { this.repository = repository; this.id = id; } public static Optional<Order> lookup(Repository repository, UUID id) { Optional<OrderPlaced> orderPlaced = ModelQueries.lookup(repository, OrderPlaced.class, OrderPlaced.ID, id); if (orderPlaced.isPresent()) { return Optional.of(new Order(repository, id)); } else { return Optional.empty(); } } }
mpl-2.0
etomica/etomica
etomica-apps/src/main/java/etomica/normalmode/LatticeDynamics.java
3591
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package etomica.normalmode; import etomica.box.Box; import etomica.lattice.crystal.Primitive; import etomica.molecule.MoleculePositionCOMPBC; import etomica.potential.PotentialCallbackMoleculeHessian; import etomica.space.Tensor; import etomica.space.Vector; import etomica.species.SpeciesManager; public class LatticeDynamics implements PotentialCallbackMoleculeHessian.HessianConsumer { protected final int molD; protected final Vector[] waveVectors; protected final Box box; protected final Tensor[][][][] matrix; protected final int numBasis; protected final Vector[] cellPos; public LatticeDynamics(SpeciesManager sm, Box box, Primitive primitive, int numBasis) { this.box = box; this.numBasis = numBasis; WaveVectorFactorySimple kFactory = new WaveVectorFactorySimple(primitive, box.getSpace()); kFactory.makeWaveVectors(box); molD = sm.getSpecies(0).getLeafAtomCount() > 1 ? 2 : 1; waveVectors = kFactory.getWaveVectors(); int numWaveVectors = waveVectors.length; matrix = new Tensor[numWaveVectors][numBasis*molD][numBasis*molD][2]; for (int i=0; i<numWaveVectors; i++) { for (int j=0; j<numBasis*molD; j++) { for (int k=0; k<numBasis*molD; k++) { for (int l=0; l<2; l++) { matrix[i][j][k][l] = box.getSpace().makeTensor(); } } } } int numCells = box.getMoleculeList().size() / numBasis; cellPos = new Vector[numCells]; for (int i=0; i<numCells; i++) { cellPos[i] = box.getSpace().makeVector(); // complete failure for mixtures cellPos[i].E(MoleculePositionCOMPBC.com(box.getBoundary(), box.getMoleculeList().get(i*numBasis))); } } @Override public boolean skipPair(int i, int j) { return box.getLeafList().get(i).getParentGroup().getIndex() >= numBasis && box.getLeafList().get(j).getParentGroup().getIndex() >= numBasis; } @Override public void takeHessian(int i, int j, Tensor tt, Tensor tr, Tensor rt, Tensor rr) { // we take i to be the molecule within the first unit cell and j to be any molecule in the box if (i >= numBasis) return; for (int iwv=0; iwv<waveVectors.length; iwv++) { Vector dr = box.getSpace().makeVector(); dr.Ev1Mv2(cellPos[j/numBasis], cellPos[0]); double kdotr = waveVectors[iwv].dot(dr); double c = Math.cos(kdotr); double s = -Math.sin(kdotr); matrix[iwv][molD*i][molD*(j%numBasis)][0].PEa1Tt1(c, tt); matrix[iwv][molD*i][molD*(j%numBasis)][1].PEa1Tt1(s, tt); if (molD > 1) { matrix[iwv][molD * i][molD * (j % numBasis) + 1][0].PEa1Tt1(c, tr); matrix[iwv][molD * i][molD * (j % numBasis) + 1][1].PEa1Tt1(s, tr); matrix[iwv][molD * i + 1][molD * (j % numBasis)][0].PEa1Tt1(c, rt); matrix[iwv][molD * i + 1][molD * (j % numBasis)][1].PEa1Tt1(s, rt); matrix[iwv][molD * i + 1][molD * (j % numBasis) + 1][0].PEa1Tt1(c, rr); matrix[iwv][molD * i + 1][molD * (j % numBasis) + 1][1].PEa1Tt1(s, rr); } } } public Tensor[][][][] getMatrix() { return matrix; } }
mpl-2.0
seedstack/seed
rest/jersey2/src/test/java/org/seedstack/seed/rest/jersey2/internal/GuiceComponentProviderTest.java
5959
/* * Copyright © 2013-2021, The SeedStack authors <http://seedstack.org> * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.seedstack.seed.rest.jersey2.internal; import com.google.common.collect.Sets; import com.google.inject.Injector; import io.nuun.kernel.api.annotations.Ignore; import mockit.*; import org.glassfish.hk2.api.DynamicConfiguration; import org.glassfish.hk2.api.Factory; import org.glassfish.hk2.api.ServiceLocator; import org.glassfish.hk2.utilities.binding.BindingBuilder; import org.glassfish.hk2.utilities.binding.ServiceBindingBuilder; import org.glassfish.jersey.model.ContractProvider; import org.junit.Test; import org.jvnet.hk2.guice.bridge.api.GuiceBridge; import org.jvnet.hk2.guice.bridge.api.GuiceIntoHK2Bridge; import org.seedstack.seed.SeedException; import javax.servlet.ServletContext; import javax.ws.rs.Path; import javax.ws.rs.ext.Provider; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.fail; public class GuiceComponentProviderTest { @Tested private GuiceComponentProvider underTest; @Mocked private ServiceLocator serviceLocator; @Mocked private ServletContext servletContext; @Mocked private Injector injector; @Mocked private GuiceIntoHK2Bridge guiceIntoHK2Bridge; @Mocked private DynamicConfiguration dynamicConfiguration; @Test public void testInitializeSaveTheServiceLocator() { givenServiceLocator(); underTest.initialize(serviceLocator); ServiceLocator initializedServiceLocator = Deencapsulation.getField(underTest, ServiceLocator.class); assertThat(initializedServiceLocator).isEqualTo(serviceLocator); } @Test public void testGetTheInjector() { givenServiceLocator(); underTest.initialize(serviceLocator); Injector initializedInjector = Deencapsulation.getField(underTest, Injector.class); assertThat(initializedInjector).isEqualTo(injector); } private void givenServiceLocator() { new Expectations() {{ serviceLocator.getService(ServletContext.class); result = servletContext; servletContext.getAttribute(Injector.class.getName()); result = injector; serviceLocator.getService(GuiceIntoHK2Bridge.class); result = guiceIntoHK2Bridge; }}; } @Test public void testMissingServletContext() { givenMissingServletContext(); try { underTest.initialize(serviceLocator); fail(); } catch (SeedException e) { assertThat(e.getErrorCode()).isEqualTo(Jersey2ErrorCode.MISSING_SERVLET_CONTEXT); } } private void givenMissingServletContext() { new Expectations() {{ serviceLocator.getService(ServletContext.class); result = null; }}; } @Test public void testMissingInjector() { givenServletContextAndMissingInjector(); try { underTest.initialize(serviceLocator); fail(); } catch (SeedException e) { assertThat(e.getErrorCode()).isEqualTo(Jersey2ErrorCode.MISSING_INJECTOR); } } private void givenServletContextAndMissingInjector() { new Expectations() {{ serviceLocator.getService(ServletContext.class); result = servletContext; servletContext.getAttribute(Injector.class.getName()); result = null; }}; } @Test public void testPrepareHK2Bridge(@Mocked final GuiceBridge guiceBridge) { givenServiceLocator(); new Expectations() {{ serviceLocator.getService(GuiceIntoHK2Bridge.class); result = guiceIntoHK2Bridge; }}; underTest.initialize(serviceLocator); new Verifications() {{ guiceBridge.initializeGuiceBridge(serviceLocator); serviceLocator.getService(GuiceIntoHK2Bridge.class); guiceIntoHK2Bridge.bridgeGuiceInjector(injector); }}; } @Test public void testDoNotBindNonResourceClasses() { boolean isBound = underTest.bind(String.class, (ContractProvider) null); assertThat(isBound).isFalse(); } @Test public <T> void testBindResourceClasses(@Mocked ServiceBindingBuilder<T> bindingBuilder) { givenServiceLocator(); givenInjections(bindingBuilder); underTest.initialize(serviceLocator); @Ignore @Path("/") class MyResource { } assertThat(underTest.bind(MyResource.class, (ContractProvider) null)).isTrue(); } @Test @SuppressWarnings("unchecked") public <T> void testBind(@Mocked ServiceBindingBuilder<T> bindingBuilder) { givenServiceLocator(); givenInjections(bindingBuilder); underTest.initialize(serviceLocator); underTest.bind(MyProvider.class, Sets.newHashSet(MyProviderImpl.class)); new Verifications() {{ bindingBuilder.to(MyProviderImpl.class); }}; } private <T> void givenInjections(ServiceBindingBuilder<T> bindingBuilder) { new MockUp<GuiceComponentProvider>() { @Mock DynamicConfiguration getConfiguration(final ServiceLocator locator) { return dynamicConfiguration; } @Mock ServiceBindingBuilder<T> newFactoryBinder(final Factory<T> factory) { return bindingBuilder; } @Mock void addBinding(final BindingBuilder<T> builder, final DynamicConfiguration configuration) { } }; } @Ignore @Provider interface MyProvider { } class MyProviderImpl implements MyProvider { } }
mpl-2.0
Appverse/appverse-mobile
appverse-core/src/java/com/gft/unity/core/io/IOService.java
2774
/* Copyright (c) 2012 GFT Appverse, S.L., Sociedad Unipersonal. This Source Code Form is subject to the terms of the Appverse Public License Version 2.0 (“APL v2.0”). If a copy of the APL was not distributed with this file, You can obtain one at http://appverse.org/legal/appverse-license/. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the conditions of the AppVerse Public License v2.0 are met. 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. EXCEPT IN CASE OF WILLFUL MISCONDUCT OR GROSS NEGLIGENCE, 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.gft.unity.core.io; public class IOService { private IOServiceEndpoint endpoint; private String name; private RequestMethod requestMethod; private ServiceType type; public IOService() { } public IOServiceEndpoint getEndpoint() { return endpoint; } public void setEndpoint(IOServiceEndpoint endpoint) { this.endpoint = endpoint; } public String getName() { return name; } public void setName(String name) { this.name = name; } public RequestMethod getRequestMethod() { return requestMethod; } public void setRequestMethod(RequestMethod requestMethod) { this.requestMethod = requestMethod; } public ServiceType getType() { return type; } public void setType(ServiceType type) { this.type = type; } @Override public String toString() { StringBuilder builder = new StringBuilder(); builder.append("IOService [endpoint="); builder.append(endpoint); builder.append(", name="); builder.append(name); builder.append(", requestMethod="); builder.append(requestMethod); builder.append(", type="); builder.append(type); builder.append("]"); return builder.toString(); } }
mpl-2.0
DevinZ1993/LeetCode-Solutions
lintcode/204.java
430
class Solution { /** * @return: The same instance of this class every time */ private static Solution obj; public static Solution getInstance() { // write your code here if (null == obj) { synchronized(Solution.class) { if (null == obj) { obj = new Solution(); } } } return obj; } };
mpl-2.0
servinglynk/hmis-lynk-open-source
hmis-model-v2014/src/main/java/com/servinglynk/hmis/warehouse/model/v2014/Connectionwithsoar.java
7491
package com.servinglynk.hmis.warehouse.model.v2014; import java.io.Serializable; import java.time.LocalDateTime; import java.util.Collections; import java.util.Map; import java.util.WeakHashMap; import javax.persistence.Basic; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.Transient; import org.hibernate.annotations.Type; import org.hibernate.proxy.HibernateProxy; /** * Object mapping for hibernate-handled table: connectionwithsoar. * * * @author Sandeep Dolia */ @Entity(name = "connectionwithsoar") @Table(name = "connectionwithsoar", catalog = "hmis", schema = "v2014") public class Connectionwithsoar extends HmisBaseModel implements Cloneable, Serializable{ /** Serial Version UID. */ private static final long serialVersionUID = -1004181330688157855L; /** Use a WeakHashMap so entries will be garbage collected once all entities referring to a saved hash are garbage collected themselves. */ private static final Map<Serializable, java.util.UUID> SAVED_HASHES = Collections.synchronizedMap(new WeakHashMap<Serializable, java.util.UUID>()); /** hashCode temporary storage. */ private volatile java.util.UUID hashCode; /** Field mapping. */ private Integer connectionwithsoar; /** Field mapping. */ private Exit exitid; /** Field mapping. */ private java.util.UUID id; /** * Default constructor, mainly for hibernate use. */ public Connectionwithsoar() { // Default constructor } /** Constructor taking a given ID. * @param id to set */ public Connectionwithsoar(java.util.UUID id) { this.id = id; } /** Field mapping. */ private Export export; /** * Return the value associated with the column: export. * @return A Export object (this.export) */ @ManyToOne( cascade = { CascadeType.PERSIST, CascadeType.MERGE }, fetch = FetchType.LAZY ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @Basic( optional = true ) @JoinColumn(name = "export_id", nullable = true ) public Export getExport() { return this.export; } /** * Set the value related to the column: export. * @param export the export value you wish to set */ public void setExport(final Export export) { this.export = export; } /** Return the type of this class. Useful for when dealing with proxies. * @return Defining class. */ @Transient public Class<?> getClassType() { return Connectionwithsoar.class; } /** * Return the value associated with the column: connectionwithsoar. * @return A Integer object (this.connectionwithsoar) */ public Integer getConnectionwithsoar() { return this.connectionwithsoar; } /** * Set the value related to the column: connectionwithsoar. * @param connectionwithsoar the connectionwithsoar value you wish to set */ public void setConnectionwithsoar(final Integer connectionwithsoar) { this.connectionwithsoar = connectionwithsoar; } /** * Return the value associated with the column: exitid. * @return A Exit object (this.exitid) */ @ManyToOne( cascade = { CascadeType.PERSIST, CascadeType.MERGE }, fetch = FetchType.LAZY ) @org.hibernate.annotations.Cascade({org.hibernate.annotations.CascadeType.SAVE_UPDATE}) @Basic( optional = true ) @JoinColumn(name = "exitid", nullable = true ) public Exit getExitid() { return this.exitid; } /** * Set the value related to the column: exitid. * @param exitid the exitid value you wish to set */ public void setExitid(final Exit exitid) { this.exitid = exitid; } /** * Return the value associated with the column: id. * @return A java.util.UUID object (this.id) */ @Id @Basic( optional = false ) @Column( name = "id", nullable = false ) @org.hibernate.annotations.Type(type="org.hibernate.type.PostgresUUIDType") public java.util.UUID getId() { return this.id; } /** * Set the value related to the column: id. * @param id the id value you wish to set */ public void setId(final java.util.UUID id) { // If we've just been persisted and hashCode has been // returned then make sure other entities with this // ID return the already returned hash code if ( (this.id == null ) && (id != null) && (this.hashCode != null) ) { SAVED_HASHES.put( id, this.hashCode ); } this.id = id; } /** * Deep copy. * @return cloned object * @throws CloneNotSupportedException on error */ @Override public Connectionwithsoar clone() throws CloneNotSupportedException { final Connectionwithsoar copy = (Connectionwithsoar)super.clone(); copy.setConnectionwithsoar(this.getConnectionwithsoar()); copy.setDateCreated(this.getDateCreated()); copy.setDateUpdated(this.getDateUpdated()); copy.setExitid(this.getExitid()); copy.setId(this.getId()); copy.setUserId(this.getUserId()); return copy; } /** Provides toString implementation. * @see java.lang.Object#toString() * @return String representation of this class. */ @Override public String toString() { StringBuffer sb = new StringBuffer(); sb.append("connectionwithsoar: " + this.getConnectionwithsoar() + ", "); sb.append("dateCreated: " + this.getDateCreated() + ", "); sb.append("dateUpdated: " + this.getDateUpdated() + ", "); sb.append("id: " + this.getId() + ", "); return sb.toString(); } /** Equals implementation. * @see java.lang.Object#equals(java.lang.Object) * @param aThat Object to compare with * @return true/false */ @Override public boolean equals(final Object aThat) { Object proxyThat = aThat; if ( this == aThat ) { return true; } if (aThat instanceof HibernateProxy) { // narrow down the proxy to the class we are dealing with. try { proxyThat = ((HibernateProxy) aThat).getHibernateLazyInitializer().getImplementation(); } catch (org.hibernate.ObjectNotFoundException e) { return false; } } if (aThat == null) { return false; } final Connectionwithsoar that; try { that = (Connectionwithsoar) proxyThat; if ( !(that.getClassType().equals(this.getClassType()))){ return false; } } catch (org.hibernate.ObjectNotFoundException e) { return false; } catch (ClassCastException e) { return false; } boolean result = true; result = result && (((this.getId() == null) && ( that.getId() == null)) || (this.getId() != null && this.getId().equals(that.getId()))); result = result && (((getConnectionwithsoar() == null) && (that.getConnectionwithsoar() == null)) || (getConnectionwithsoar() != null && getConnectionwithsoar().equals(that.getConnectionwithsoar()))); result = result && (((getDateCreated() == null) && (that.getDateCreated() == null)) || (getDateCreated() != null && getDateCreated().equals(that.getDateCreated()))); result = result && (((getDateUpdated() == null) && (that.getDateUpdated() == null)) || (getDateUpdated() != null && getDateUpdated().equals(that.getDateUpdated()))); result = result && (((getExitid() == null) && (that.getExitid() == null)) || (getExitid() != null && getExitid().getId().equals(that.getExitid().getId()))); result = result && (((getUserId() == null) && (that.getUserId() == null)) || (getUserId() != null && getUserId().equals(that.getUserId()))); return result; } }
mpl-2.0
gillion/RDACP
Trunk/00.Coding/cartan/cartan-center/src/test/java/com/cartan/center/ebs/sysUser/SysUserServiceEbsIT.java
7821
/** * Copyright:志远数字商务有限公司 版权所有 违者必究 2013 */ package com.cartan.center.ebs.sysUser; import com.cartan.center.CartanRopClient; import com.cartan.center.ebs.sysUser.request.*; import com.cartan.center.ebs.sysUser.response.*; import com.rop.client.CompositeResponse; import com.rop.client.RopClient; import org.testng.Assert; import org.testng.annotations.Test; import org.unitils.UnitilsTestNG; import org.apache.log4j.Logger; import com.ridge.util.CodeUtils; /** * @author : liuxb(13720880048@163.com) * @date: 2013-09-05 */ public class SysUserServiceEbsIT extends UnitilsTestNG { static Logger logger = Logger.getLogger(SysUserServiceEbsIT.class.getName()); @Test public void testGetSession(){ RopClient ropClient = CartanRopClient.getRopClient(); SysUserGetSessionRequest sysUserRequest = new SysUserGetSessionRequest(); CompositeResponse<SysUserGetSessionResponse> response = ropClient.buildClientRequest().get(sysUserRequest, SysUserGetSessionResponse.class, "sysUser.getSession", "1.0"); Assert.assertTrue(response.isSuccessful()); if (logger.isDebugEnabled()){ if(response.isSuccessful()) logger.debug("成功返回报文!"); } } @Test public void createSysUser(){ RopClient ropClient = CartanRopClient.getRopClient(); SysUserCreateRequest sysUserRequest = new SysUserCreateRequest(); sysUserRequest.setUserId(CodeUtils.uuid()); sysUserRequest.setUserName("1"); sysUserRequest.setPassword("1"); sysUserRequest.setUserType("1"); sysUserRequest.setLastLogonTime("20120101120101"); sysUserRequest.setLastLogonIp("1"); sysUserRequest.setStatus("1"); sysUserRequest.setCreateTime("20120101120101"); CompositeResponse<SysUserCreateResponse> response = ropClient.buildClientRequest().get(sysUserRequest, SysUserCreateResponse.class, "sysUser.createSysUser", "1.0"); Assert.assertTrue(response.isSuccessful()); if (logger.isDebugEnabled()){ if(response.isSuccessful()) logger.debug("成功返回报文!"); } SysUserCreateResponse sysUserResponse = response.getSuccessResponse(); } @Test public void deleteSysUser(){ RopClient ropClient = CartanRopClient.getRopClient(); SysUserDeleteRequest sysUserRequest = new SysUserDeleteRequest(); sysUserRequest.setUserId("1"); CompositeResponse<SysUserDeleteResponse> response = ropClient.buildClientRequest().get(sysUserRequest, SysUserDeleteResponse.class, "sysUser.deleteSysUser", "1.0"); Assert.assertTrue(response.isSuccessful()); if (logger.isDebugEnabled()){ if(response.isSuccessful()) logger.debug("成功返回报文!"); } SysUserDeleteResponse sysUserResponse = response.getSuccessResponse(); } @Test public void updateSysUser(){ RopClient ropClient = CartanRopClient.getRopClient(); SysUserUpdateRequest sysUserRequest = new SysUserUpdateRequest(); sysUserRequest.setUserId("1"); sysUserRequest.setUserName("1"); sysUserRequest.setPassword("1"); sysUserRequest.setUserType("1"); sysUserRequest.setLastLogonTime("20120101120101"); sysUserRequest.setLastLogonIp("1"); sysUserRequest.setStatus("1"); sysUserRequest.setCreateTime("20120101120101"); CompositeResponse<SysUserUpdateResponse> response = ropClient.buildClientRequest().get(sysUserRequest, SysUserUpdateResponse.class, "sysUser.updateSysUser", "1.0"); Assert.assertTrue(response.isSuccessful()); if (logger.isDebugEnabled()){ if(response.isSuccessful()) logger.debug("成功返回报文!"); } SysUserUpdateResponse sysUserResponse = response.getSuccessResponse(); } @Test public void getSysUser(){ RopClient ropClient = CartanRopClient.getRopClient(); SysUserGetRequest sysUserRequest = new SysUserGetRequest(); sysUserRequest.setUserId("1"); CompositeResponse<SysUserGetResponse> response = ropClient.buildClientRequest().get(sysUserRequest, SysUserGetResponse.class, "sysUser.getSysUser", "1.0"); Assert.assertTrue(response.isSuccessful()); if (logger.isDebugEnabled()){ if(response.isSuccessful()) logger.debug("成功返回报文!"); } SysUserGetResponse sysUserResponse = response.getSuccessResponse(); } @Test public void selectAll(){ RopClient ropClient = CartanRopClient.getRopClient(); SysUserSelectAllRequest sysUserRequest = new SysUserSelectAllRequest(); CompositeResponse<SysUserSelectAllResponse> response = ropClient.buildClientRequest().get(sysUserRequest, SysUserSelectAllResponse.class, "sysUser.selectAll", "1.0"); Assert.assertTrue(response.isSuccessful()); if (logger.isDebugEnabled()){ if(response.isSuccessful()) logger.debug("成功返回报文!"); } SysUserSelectAllResponse sysUserResponse = response.getSuccessResponse(); } @Test public void countAll(){ RopClient ropClient = CartanRopClient.getRopClient(); SysUserCountAllRequest sysUserRequest = new SysUserCountAllRequest(); CompositeResponse<SysUserCountAllResponse> response = ropClient.buildClientRequest().get(sysUserRequest, SysUserCountAllResponse.class, "sysUser.countAll", "1.0"); Assert.assertTrue(response.isSuccessful()); if (logger.isDebugEnabled()){ if(response.isSuccessful()) logger.debug("成功返回报文!"); } SysUserCountAllResponse sysUserResponse = response.getSuccessResponse(); Assert.assertNotNull(sysUserResponse.getResultString()); } @Test public void selectSysUser(){ RopClient ropClient = CartanRopClient.getRopClient(); SysUserSelectRequest sysUserRequest = new SysUserSelectRequest(); sysUserRequest.setUserId("1"); sysUserRequest.setUserName("1"); sysUserRequest.setPassword("1"); sysUserRequest.setUserType("1"); sysUserRequest.setLastLogonTime("20120101120101"); sysUserRequest.setLastLogonIp("1"); sysUserRequest.setStatus("1"); sysUserRequest.setCreateTime("20120101120101"); CompositeResponse<SysUserCreateResponse> response = ropClient.buildClientRequest().get(sysUserRequest, SysUserCreateResponse.class, "sysUser.createSysUser", "1.0"); Assert.assertTrue(response.isSuccessful()); sysUserRequest.setUserId("1"); sysUserRequest.setUserName("1"); sysUserRequest.setPassword("1"); sysUserRequest.setUserType("1"); sysUserRequest.setLastLogonTime("20120101120101"); sysUserRequest.setLastLogonIp("1"); sysUserRequest.setStatus("1"); sysUserRequest.setCreateTime("20120101120101"); CompositeResponse<SysUserSelectResponse> response1 = ropClient.buildClientRequest().get(sysUserRequest, SysUserSelectResponse.class, "sysUser.selectSysUser", "1.0"); Assert.assertTrue(response1.isSuccessful()); if (logger.isDebugEnabled()){ if(response.isSuccessful()) logger.debug("成功返回报文!"); } SysUserSelectResponse sysUserResponse = response1.getSuccessResponse(); Assert.assertNotNull(sysUserResponse.getResultJson()); CompositeResponse<SysUserDeleteResponse> response2 = ropClient.buildClientRequest().get(sysUserRequest, SysUserDeleteResponse.class, "sysUser.deleteSysUser", "1.0"); } }
mpl-2.0
powsybl/powsybl-core
loadflow/loadflow-validation/src/test/java/com/powsybl/loadflow/validation/BalanceTypeGuesserTest.java
3019
/** * Copyright (c) 2018, RTE (http://www.rte-france.com) * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package com.powsybl.loadflow.validation; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNull; import java.util.stream.Stream; import org.junit.Test; import org.mockito.Mockito; import com.powsybl.iidm.network.Generator; import com.powsybl.iidm.network.Network; import com.powsybl.iidm.network.Terminal; /** * * @author Massimo Ferraro <massimo.ferraro@techrain.eu> */ public class BalanceTypeGuesserTest { @Test public void test() { Terminal genTerminal1 = Mockito.mock(Terminal.class); Mockito.when(genTerminal1.getP()).thenReturn(-126.083); Generator generator1 = Mockito.mock(Generator.class); Mockito.when(generator1.getId()).thenReturn("gen1"); Mockito.when(generator1.getTerminal()).thenReturn(genTerminal1); Mockito.when(generator1.getTargetP()).thenReturn(126.0); Mockito.when(generator1.getMaxP()).thenReturn(500.0); Mockito.when(generator1.getMinP()).thenReturn(0.0); Terminal genTerminal2 = Mockito.mock(Terminal.class); Mockito.when(genTerminal2.getP()).thenReturn(-129.085); Generator generator2 = Mockito.mock(Generator.class); Mockito.when(generator2.getId()).thenReturn("gen2"); Mockito.when(generator2.getTerminal()).thenReturn(genTerminal2); Mockito.when(generator2.getTargetP()).thenReturn(129.0); Mockito.when(generator2.getMaxP()).thenReturn(500.0); Mockito.when(generator2.getMinP()).thenReturn(0.0); Network network = Mockito.mock(Network.class); Mockito.when(network.getId()).thenReturn("network"); Mockito.when(network.getGeneratorStream()).thenAnswer(dummy -> Stream.of(generator1, generator2)); BalanceTypeGuesser guesser = new BalanceTypeGuesser(network, 0.1); assertEquals(BalanceType.NONE, guesser.getBalanceType()); assertEquals("gen2", guesser.getSlack()); Terminal genTerminal3 = Mockito.mock(Terminal.class); Mockito.when(genTerminal3.getP()).thenReturn(-155.236); Generator generator3 = Mockito.mock(Generator.class); Mockito.when(generator3.getId()).thenReturn("gen3"); Mockito.when(generator3.getTerminal()).thenReturn(genTerminal3); Mockito.when(generator3.getTargetP()).thenReturn(195.107); Mockito.when(generator3.getMaxP()).thenReturn(227.5); Mockito.when(generator3.getMinP()).thenReturn(-227.5); Mockito.when(network.getGeneratorStream()).thenAnswer(dummy -> Stream.of(generator1, generator2, generator3)); guesser = new BalanceTypeGuesser(network, 0.1); assertEquals(BalanceType.PROPORTIONAL_TO_GENERATION_P, guesser.getBalanceType()); assertNull(guesser.getSlack()); } }
mpl-2.0
ProfilingLabs/Usemon2
usemon-agent-commons-java/src/main/java/com/usemon/lib/org/apache/commons/collections/functors/ChainedClosure.java
4601
/* * Copyright 2001-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.usemon.lib.org.apache.commons.collections.functors; import java.io.Serializable; import java.util.Collection; import java.util.Iterator; import com.usemon.lib.org.apache.commons.collections.Closure; /** * Closure implementation that chains the specified closures together. * * @since Commons Collections 3.0 * @version $Revision: 348444 $ $Date: 2005-11-23 14:06:56 +0000 (Wed, 23 Nov 2005) $ * * @author Stephen Colebourne */ public class ChainedClosure implements Closure, Serializable { /** Serial version UID */ private static final long serialVersionUID = -3520677225766901240L; /** The closures to call in turn */ private final Closure[] iClosures; /** * Factory method that performs validation and copies the parameter array. * * @param closures the closures to chain, copied, no nulls * @return the <code>chained</code> closure * @throws IllegalArgumentException if the closures array is null * @throws IllegalArgumentException if any closure in the array is null */ public static Closure getInstance(Closure[] closures) { FunctorUtils.validate(closures); if (closures.length == 0) { return NOPClosure.INSTANCE; } closures = FunctorUtils.copy(closures); return new ChainedClosure(closures); } /** * Create a new Closure that calls each closure in turn, passing the * result into the next closure. The ordering is that of the iterator() * method on the collection. * * @param closures a collection of closures to chain * @return the <code>chained</code> closure * @throws IllegalArgumentException if the closures collection is null * @throws IllegalArgumentException if any closure in the collection is null */ public static Closure getInstance(Collection closures) { if (closures == null) { throw new IllegalArgumentException("Closure collection must not be null"); } if (closures.size() == 0) { return NOPClosure.INSTANCE; } // convert to array like this to guarantee iterator() ordering Closure[] cmds = new Closure[closures.size()]; int i = 0; for (Iterator it = closures.iterator(); it.hasNext();) { cmds[i++] = (Closure) it.next(); } FunctorUtils.validate(cmds); return new ChainedClosure(cmds); } /** * Factory method that performs validation. * * @param closure1 the first closure, not null * @param closure2 the second closure, not null * @return the <code>chained</code> closure * @throws IllegalArgumentException if either closure is null */ public static Closure getInstance(Closure closure1, Closure closure2) { if (closure1 == null || closure2 == null) { throw new IllegalArgumentException("Closures must not be null"); } Closure[] closures = new Closure[] { closure1, closure2 }; return new ChainedClosure(closures); } /** * Constructor that performs no validation. * Use <code>getInstance</code> if you want that. * * @param closures the closures to chain, not copied, no nulls */ public ChainedClosure(Closure[] closures) { super(); iClosures = closures; } /** * Execute a list of closures. * * @param input the input object passed to each closure */ public void execute(Object input) { for (int i = 0; i < iClosures.length; i++) { iClosures[i].execute(input); } } /** * Gets the closures, do not modify the array. * @return the closures * @since Commons Collections 3.1 */ public Closure[] getClosures() { return iClosures; } }
mpl-2.0
Yukarumya/Yukarum-Redfoxes
mobile/android/tests/background/junit4/src/org/mozilla/gecko/sync/repositories/downloaders/BatchingDownloaderTest.java
23704
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.gecko.sync.repositories.downloaders; import android.support.annotation.NonNull; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.mozilla.gecko.background.testhelpers.TestRunner; import org.mozilla.gecko.sync.CryptoRecord; import org.mozilla.gecko.sync.InfoCollections; import org.mozilla.gecko.sync.InfoConfiguration; import org.mozilla.gecko.sync.net.AuthHeaderProvider; import org.mozilla.gecko.sync.net.SyncResponse; import org.mozilla.gecko.sync.net.SyncStorageCollectionRequest; import org.mozilla.gecko.sync.net.SyncStorageResponse; import org.mozilla.gecko.sync.repositories.Repository; import org.mozilla.gecko.sync.repositories.Server11Repository; import org.mozilla.gecko.sync.repositories.Server11RepositorySession; import org.mozilla.gecko.sync.repositories.delegates.RepositorySessionFetchRecordsDelegate; import org.mozilla.gecko.sync.repositories.domain.Record; import java.io.UnsupportedEncodingException; import java.net.URI; import java.net.URISyntaxException; import java.util.concurrent.ExecutorService; import ch.boye.httpclientandroidlib.ProtocolVersion; import ch.boye.httpclientandroidlib.message.BasicHttpResponse; import ch.boye.httpclientandroidlib.message.BasicStatusLine; import static org.junit.Assert.*; import static org.junit.Assert.assertEquals; @RunWith(TestRunner.class) public class BatchingDownloaderTest { private MockSever11Repository serverRepository; private Server11RepositorySession repositorySession; private MockSessionFetchRecordsDelegate sessionFetchRecordsDelegate; private MockDownloader mockDownloader; private String DEFAULT_COLLECTION_NAME = "dummyCollection"; private String DEFAULT_COLLECTION_URL = "http://dummy.url/"; private long DEFAULT_NEWER = 1; private String DEFAULT_SORT = "index"; private String DEFAULT_IDS = "1"; private String DEFAULT_LMHEADER = "12345678"; class MockSessionFetchRecordsDelegate implements RepositorySessionFetchRecordsDelegate { public boolean isFailure; public boolean isFetched; public boolean isSuccess; public Exception ex; public Record record; @Override public void onFetchFailed(Exception ex, Record record) { this.isFailure = true; this.ex = ex; this.record = record; } @Override public void onFetchedRecord(Record record) { this.isFetched = true; this.record = record; } @Override public void onFetchCompleted(long fetchEnd) { this.isSuccess = true; } @Override public RepositorySessionFetchRecordsDelegate deferredFetchDelegate(ExecutorService executor) { return null; } } class MockRequest extends SyncStorageCollectionRequest { public MockRequest(URI uri) { super(uri); } @Override public void get() { } } class MockDownloader extends BatchingDownloader { public long newer; public long limit; public boolean full; public String sort; public String ids; public String offset; public boolean abort; public MockDownloader(Server11Repository repository, Server11RepositorySession repositorySession) { super(repository, repositorySession); } @Override public void fetchWithParameters(long newer, long batchLimit, boolean full, String sort, String ids, SyncStorageCollectionRequest request, RepositorySessionFetchRecordsDelegate fetchRecordsDelegate) throws UnsupportedEncodingException, URISyntaxException { this.newer = newer; this.limit = batchLimit; this.full = full; this.sort = sort; this.ids = ids; MockRequest mockRequest = new MockRequest(new URI(DEFAULT_COLLECTION_URL)); super.fetchWithParameters(newer, batchLimit, full, sort, ids, mockRequest, fetchRecordsDelegate); } @Override public void abortRequests() { this.abort = true; } @Override public SyncStorageCollectionRequest makeSyncStorageCollectionRequest(long newer, long batchLimit, boolean full, String sort, String ids, String offset) throws URISyntaxException, UnsupportedEncodingException { this.offset = offset; return super.makeSyncStorageCollectionRequest(newer, batchLimit, full, sort, ids, offset); } } class MockSever11Repository extends Server11Repository { public MockSever11Repository(@NonNull String collection, @NonNull String storageURL, AuthHeaderProvider authHeaderProvider, @NonNull InfoCollections infoCollections, @NonNull InfoConfiguration infoConfiguration) throws URISyntaxException { super(collection, storageURL, authHeaderProvider, infoCollections, infoConfiguration); } @Override public long getDefaultTotalLimit() { return 200; } } class MockRepositorySession extends Server11RepositorySession { public boolean abort; public MockRepositorySession(Repository repository) { super(repository); } @Override public void abort() { this.abort = true; } } @Before public void setUp() throws Exception { sessionFetchRecordsDelegate = new MockSessionFetchRecordsDelegate(); serverRepository = new MockSever11Repository(DEFAULT_COLLECTION_NAME, DEFAULT_COLLECTION_URL, null, new InfoCollections(), new InfoConfiguration()); repositorySession = new Server11RepositorySession(serverRepository); mockDownloader = new MockDownloader(serverRepository, repositorySession); } @Test public void testFlattenId() { String[] emptyGuid = new String[]{}; String flatten = BatchingDownloader.flattenIDs(emptyGuid); assertEquals("", flatten); String guid0 = "123456789abc"; String[] singleGuid = new String[1]; singleGuid[0] = guid0; flatten = BatchingDownloader.flattenIDs(singleGuid); assertEquals("123456789abc", flatten); String guid1 = "456789abc"; String guid2 = "789abc"; String[] multiGuid = new String[3]; multiGuid[0] = guid0; multiGuid[1] = guid1; multiGuid[2] = guid2; flatten = BatchingDownloader.flattenIDs(multiGuid); assertEquals("123456789abc,456789abc,789abc", flatten); } @Test public void testEncodeParam() throws Exception { String param = "123&123"; String encodedParam = mockDownloader.encodeParam(param); assertEquals("123%26123", encodedParam); } @Test(expected=IllegalArgumentException.class) public void testOverTotalLimit() throws Exception { // Per-batch limits exceed total. Server11Repository repository = new Server11Repository(DEFAULT_COLLECTION_NAME, DEFAULT_COLLECTION_URL, null, new InfoCollections(), new InfoConfiguration()) { @Override public long getDefaultTotalLimit() { return 100; } @Override public long getDefaultBatchLimit() { return 200; } }; MockDownloader mockDownloader = new MockDownloader(repository, repositorySession); assertNull(mockDownloader.getLastModified()); mockDownloader.fetchSince(DEFAULT_NEWER, sessionFetchRecordsDelegate); } @Test public void testTotalLimit() throws Exception { // Total and per-batch limits are the same. Server11Repository repository = new Server11Repository(DEFAULT_COLLECTION_NAME, DEFAULT_COLLECTION_URL, null, new InfoCollections(), new InfoConfiguration()) { @Override public long getDefaultTotalLimit() { return 100; } @Override public long getDefaultBatchLimit() { return 100; } }; MockDownloader mockDownloader = new MockDownloader(repository, repositorySession); assertNull(mockDownloader.getLastModified()); mockDownloader.fetchSince(DEFAULT_NEWER, sessionFetchRecordsDelegate); SyncStorageResponse response = makeSyncStorageResponse(200, DEFAULT_LMHEADER, "100", "100"); SyncStorageCollectionRequest request = new SyncStorageCollectionRequest(new URI(DEFAULT_COLLECTION_URL)); long limit = repository.getDefaultBatchLimit(); mockDownloader.onFetchCompleted(response, sessionFetchRecordsDelegate, request, DEFAULT_NEWER, limit, true, DEFAULT_SORT, DEFAULT_IDS); assertEquals(DEFAULT_LMHEADER, mockDownloader.getLastModified()); assertTrue(sessionFetchRecordsDelegate.isSuccess); assertFalse(sessionFetchRecordsDelegate.isFetched); assertFalse(sessionFetchRecordsDelegate.isFailure); } @Test public void testOverHalfOfTotalLimit() throws Exception { // Per-batch limit is just a bit lower than total. Server11Repository repository = new Server11Repository(DEFAULT_COLLECTION_NAME, DEFAULT_COLLECTION_URL, null, new InfoCollections(), new InfoConfiguration()) { @Override public long getDefaultTotalLimit() { return 100; } @Override public long getDefaultBatchLimit() { return 75; } }; MockDownloader mockDownloader = new MockDownloader(repository, repositorySession); assertNull(mockDownloader.getLastModified()); mockDownloader.fetchSince(DEFAULT_NEWER, sessionFetchRecordsDelegate); String offsetHeader = "75"; String recordsHeader = "75"; SyncStorageResponse response = makeSyncStorageResponse(200, DEFAULT_LMHEADER, offsetHeader, recordsHeader); SyncStorageCollectionRequest request = new SyncStorageCollectionRequest(new URI(DEFAULT_COLLECTION_URL)); long limit = repository.getDefaultBatchLimit(); mockDownloader.onFetchCompleted(response, sessionFetchRecordsDelegate, request, DEFAULT_NEWER, limit, true, DEFAULT_SORT, DEFAULT_IDS); assertEquals(DEFAULT_LMHEADER, mockDownloader.getLastModified()); // Verify the same parameters are used in the next fetch. assertSameParameters(mockDownloader, limit); assertEquals(offsetHeader, mockDownloader.offset); assertFalse(sessionFetchRecordsDelegate.isSuccess); assertFalse(sessionFetchRecordsDelegate.isFetched); assertFalse(sessionFetchRecordsDelegate.isFailure); // The next batch, we still have an offset token but we complete our fetch since we have reached the total limit. offsetHeader = "150"; response = makeSyncStorageResponse(200, DEFAULT_LMHEADER, offsetHeader, recordsHeader); mockDownloader.onFetchCompleted(response, sessionFetchRecordsDelegate, request, DEFAULT_NEWER, limit, true, DEFAULT_SORT, DEFAULT_IDS); assertEquals(DEFAULT_LMHEADER, mockDownloader.getLastModified()); assertTrue(sessionFetchRecordsDelegate.isSuccess); assertFalse(sessionFetchRecordsDelegate.isFetched); assertFalse(sessionFetchRecordsDelegate.isFailure); } @Test public void testHalfOfTotalLimit() throws Exception { // Per-batch limit is half of total. Server11Repository repository = new Server11Repository(DEFAULT_COLLECTION_NAME, DEFAULT_COLLECTION_URL, null, new InfoCollections(), new InfoConfiguration()) { @Override public long getDefaultTotalLimit() { return 100; } @Override public long getDefaultBatchLimit() { return 50; } }; mockDownloader = new MockDownloader(repository, repositorySession); assertNull(mockDownloader.getLastModified()); mockDownloader.fetchSince(DEFAULT_NEWER, sessionFetchRecordsDelegate); String offsetHeader = "50"; String recordsHeader = "50"; SyncStorageResponse response = makeSyncStorageResponse(200, DEFAULT_LMHEADER, offsetHeader, recordsHeader); SyncStorageCollectionRequest request = new SyncStorageCollectionRequest(new URI(DEFAULT_COLLECTION_URL)); long limit = repository.getDefaultBatchLimit(); mockDownloader.onFetchCompleted(response, sessionFetchRecordsDelegate, request, DEFAULT_NEWER, limit, true, DEFAULT_SORT, DEFAULT_IDS); assertEquals(DEFAULT_LMHEADER, mockDownloader.getLastModified()); // Verify the same parameters are used in the next fetch. assertSameParameters(mockDownloader, limit); assertEquals(offsetHeader, mockDownloader.offset); assertFalse(sessionFetchRecordsDelegate.isSuccess); assertFalse(sessionFetchRecordsDelegate.isFetched); assertFalse(sessionFetchRecordsDelegate.isFailure); // The next batch, we still have an offset token but we complete our fetch since we have reached the total limit. offsetHeader = "100"; response = makeSyncStorageResponse(200, DEFAULT_LMHEADER, offsetHeader, recordsHeader); mockDownloader.onFetchCompleted(response, sessionFetchRecordsDelegate, request, DEFAULT_NEWER, limit, true, DEFAULT_SORT, DEFAULT_IDS); assertEquals(DEFAULT_LMHEADER, mockDownloader.getLastModified()); assertTrue(sessionFetchRecordsDelegate.isSuccess); assertFalse(sessionFetchRecordsDelegate.isFetched); assertFalse(sessionFetchRecordsDelegate.isFailure); } @Test public void testFractionOfTotalLimit() throws Exception { // Per-batch limit is a small fraction of the total. Server11Repository repository = new Server11Repository(DEFAULT_COLLECTION_NAME, DEFAULT_COLLECTION_URL, null, new InfoCollections(), new InfoConfiguration()) { @Override public long getDefaultTotalLimit() { return 100; } @Override public long getDefaultBatchLimit() { return 25; } }; mockDownloader = new MockDownloader(repository, repositorySession); assertNull(mockDownloader.getLastModified()); mockDownloader.fetchSince(DEFAULT_NEWER, sessionFetchRecordsDelegate); String offsetHeader = "25"; String recordsHeader = "25"; SyncStorageResponse response = makeSyncStorageResponse(200, DEFAULT_LMHEADER, offsetHeader, recordsHeader); SyncStorageCollectionRequest request = new SyncStorageCollectionRequest(new URI(DEFAULT_COLLECTION_URL)); long limit = repository.getDefaultBatchLimit(); mockDownloader.onFetchCompleted(response, sessionFetchRecordsDelegate, request, DEFAULT_NEWER, limit, true, DEFAULT_SORT, DEFAULT_IDS); assertEquals(DEFAULT_LMHEADER, mockDownloader.getLastModified()); // Verify the same parameters are used in the next fetch. assertSameParameters(mockDownloader, limit); assertEquals(offsetHeader, mockDownloader.offset); assertFalse(sessionFetchRecordsDelegate.isSuccess); assertFalse(sessionFetchRecordsDelegate.isFetched); assertFalse(sessionFetchRecordsDelegate.isFailure); // The next batch, we still have an offset token and has not exceed the total limit. offsetHeader = "50"; response = makeSyncStorageResponse(200, DEFAULT_LMHEADER, offsetHeader, recordsHeader); mockDownloader.onFetchCompleted(response, sessionFetchRecordsDelegate, request, DEFAULT_NEWER, limit, true, DEFAULT_SORT, DEFAULT_IDS); assertEquals(DEFAULT_LMHEADER, mockDownloader.getLastModified()); // Verify the same parameters are used in the next fetch. assertSameParameters(mockDownloader, limit); assertEquals(offsetHeader, mockDownloader.offset); assertFalse(sessionFetchRecordsDelegate.isSuccess); assertFalse(sessionFetchRecordsDelegate.isFetched); assertFalse(sessionFetchRecordsDelegate.isFailure); // The next batch, we still have an offset token and has not exceed the total limit. offsetHeader = "75"; response = makeSyncStorageResponse(200, DEFAULT_LMHEADER, offsetHeader, recordsHeader); mockDownloader.onFetchCompleted(response, sessionFetchRecordsDelegate, request, DEFAULT_NEWER, limit, true, DEFAULT_SORT, DEFAULT_IDS); assertEquals(DEFAULT_LMHEADER, mockDownloader.getLastModified()); // Verify the same parameters are used in the next fetch. assertSameParameters(mockDownloader, limit); assertEquals(offsetHeader, mockDownloader.offset); assertFalse(sessionFetchRecordsDelegate.isSuccess); assertFalse(sessionFetchRecordsDelegate.isFetched); assertFalse(sessionFetchRecordsDelegate.isFailure); // The next batch, we still have an offset token but we complete our fetch since we have reached the total limit. offsetHeader = "100"; response = makeSyncStorageResponse(200, DEFAULT_LMHEADER, offsetHeader, recordsHeader); mockDownloader.onFetchCompleted(response, sessionFetchRecordsDelegate, request, DEFAULT_NEWER, limit, true, DEFAULT_SORT, DEFAULT_IDS); assertEquals(DEFAULT_LMHEADER, mockDownloader.getLastModified()); assertTrue(sessionFetchRecordsDelegate.isSuccess); assertFalse(sessionFetchRecordsDelegate.isFetched); assertFalse(sessionFetchRecordsDelegate.isFailure); } @Test public void testFailureLMChangedMultiBatch() throws Exception { assertNull(mockDownloader.getLastModified()); String lmHeader = "12345678"; String offsetHeader = "100"; SyncStorageResponse response = makeSyncStorageResponse(200, lmHeader, offsetHeader, null); SyncStorageCollectionRequest request = new SyncStorageCollectionRequest(new URI("http://dummy.url")); long limit = 1; mockDownloader.onFetchCompleted(response, sessionFetchRecordsDelegate, request, DEFAULT_NEWER, limit, true, DEFAULT_SORT, DEFAULT_IDS); assertEquals(lmHeader, mockDownloader.getLastModified()); // Verify the same parameters are used in the next fetch. assertEquals(DEFAULT_NEWER, mockDownloader.newer); assertEquals(limit, mockDownloader.limit); assertTrue(mockDownloader.full); assertEquals(DEFAULT_SORT, mockDownloader.sort); assertEquals(DEFAULT_IDS, mockDownloader.ids); assertEquals(offsetHeader, mockDownloader.offset); assertFalse(sessionFetchRecordsDelegate.isSuccess); assertFalse(sessionFetchRecordsDelegate.isFetched); assertFalse(sessionFetchRecordsDelegate.isFailure); // Last modified header somehow changed. lmHeader = "10000000"; response = makeSyncStorageResponse(200, lmHeader, offsetHeader, null); mockDownloader.onFetchCompleted(response, sessionFetchRecordsDelegate, request, DEFAULT_NEWER, limit, true, DEFAULT_SORT, DEFAULT_IDS); assertNotEquals(lmHeader, mockDownloader.getLastModified()); assertTrue(mockDownloader.abort); assertFalse(sessionFetchRecordsDelegate.isSuccess); assertFalse(sessionFetchRecordsDelegate.isFetched); assertTrue(sessionFetchRecordsDelegate.isFailure); } @Test public void testFailureMissingLMMultiBatch() throws Exception { assertNull(mockDownloader.getLastModified()); String offsetHeader = "100"; SyncStorageResponse response = makeSyncStorageResponse(200, null, offsetHeader, null); SyncStorageCollectionRequest request = new SyncStorageCollectionRequest(new URI("http://dummy.url")); mockDownloader.onFetchCompleted(response, sessionFetchRecordsDelegate, request, DEFAULT_NEWER, 1, true, DEFAULT_SORT, DEFAULT_IDS); // Last modified header somehow missing from response. assertNull(null, mockDownloader.getLastModified()); assertTrue(mockDownloader.abort); assertFalse(sessionFetchRecordsDelegate.isSuccess); assertFalse(sessionFetchRecordsDelegate.isFetched); assertTrue(sessionFetchRecordsDelegate.isFailure); } @Test public void testFailureException() throws Exception { Exception ex = new IllegalStateException(); SyncStorageCollectionRequest request = new SyncStorageCollectionRequest(new URI("http://dummy.url")); mockDownloader.onFetchFailed(ex, sessionFetchRecordsDelegate, request); assertFalse(sessionFetchRecordsDelegate.isSuccess); assertFalse(sessionFetchRecordsDelegate.isFetched); assertTrue(sessionFetchRecordsDelegate.isFailure); assertEquals(ex.getClass(), sessionFetchRecordsDelegate.ex.getClass()); assertNull(sessionFetchRecordsDelegate.record); } @Test public void testFetchRecord() { CryptoRecord record = new CryptoRecord(); mockDownloader.onFetchedRecord(record, sessionFetchRecordsDelegate); assertTrue(sessionFetchRecordsDelegate.isFetched); assertFalse(sessionFetchRecordsDelegate.isSuccess); assertFalse(sessionFetchRecordsDelegate.isFailure); assertEquals(record, sessionFetchRecordsDelegate.record); } @Test public void testAbortRequests() { MockRepositorySession mockRepositorySession = new MockRepositorySession(serverRepository); BatchingDownloader downloader = new BatchingDownloader(serverRepository, mockRepositorySession); assertFalse(mockRepositorySession.abort); downloader.abortRequests(); assertTrue(mockRepositorySession.abort); } private void assertSameParameters(MockDownloader mockDownloader, long limit) { assertEquals(DEFAULT_NEWER, mockDownloader.newer); assertEquals(limit, mockDownloader.limit); assertTrue(mockDownloader.full); assertEquals(DEFAULT_SORT, mockDownloader.sort); assertEquals(DEFAULT_IDS, mockDownloader.ids); } private SyncStorageResponse makeSyncStorageResponse(int code, String lastModified, String offset, String records) { BasicHttpResponse response = new BasicHttpResponse( new BasicStatusLine(new ProtocolVersion("HTTP", 1, 1), code, null)); if (lastModified != null) { response.addHeader(SyncResponse.X_LAST_MODIFIED, lastModified); } if (offset != null) { response.addHeader(SyncResponse.X_WEAVE_NEXT_OFFSET, offset); } if (records != null) { response.addHeader(SyncResponse.X_WEAVE_RECORDS, records); } return new SyncStorageResponse(response); } }
mpl-2.0
adamlofting/webmaker-android
app/src/main/java/org/mozilla/webmaker/BaseActivity.java
172
package org.mozilla.webmaker; import android.app.Activity; public class BaseActivity extends Activity { public void goBack() { super.onBackPressed(); } }
mpl-2.0
jatronizer/configurator
src/main/java/org/jatronizer/configurator/ConfigException.java
370
package org.jatronizer.configurator; /** * Signals that an Object could not be used as a configuration. */ public final class ConfigException extends RuntimeException { public ConfigException(String msg) { super(msg); } public ConfigException(Throwable cause) { super(cause); } public ConfigException(String msg, Throwable cause) { super(msg, cause); } }
mpl-2.0
miloszpiglas/h2mod
src/main/org/h2/server/pg/PgServer.java
17325
/* * Copyright 2004-2013 H2 Group. Multiple-Licensed under the H2 License, * Version 1.0, and under the Eclipse Public License, Version 1.0 * (http://h2database.com/html/license.html). * Initial Developer: H2 Group */ package org.h2.server.pg; import java.io.IOException; import java.net.ServerSocket; import java.net.Socket; import java.net.UnknownHostException; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import java.sql.Types; import java.util.Collections; import java.util.HashSet; import java.util.Set; import java.util.concurrent.atomic.AtomicInteger; import org.h2.api.ErrorCode; import org.h2.engine.Constants; import org.h2.message.DbException; import org.h2.server.Service; import org.h2.util.NetUtils; import org.h2.util.New; import org.h2.util.Tool; /** * This class implements a subset of the PostgreSQL protocol as described here: * http://developer.postgresql.org/pgdocs/postgres/protocol.html * The PostgreSQL catalog is described here: * http://www.postgresql.org/docs/7.4/static/catalogs.html * * @author Thomas Mueller * @author Sergi Vladykin 2009-07-03 (convertType) */ public class PgServer implements Service { /** * The default port to use for the PG server. * This value is also in the documentation and in the Server javadoc. */ public static final int DEFAULT_PORT = 5435; /** * The VARCHAR type. */ public static final int PG_TYPE_VARCHAR = 1043; /** * The integer array type (for the column pg_index.indkey). */ public static final int PG_TYPE_INT2VECTOR = 22; public static final int PG_TYPE_BOOL = 16; public static final int PG_TYPE_BYTEA = 17; public static final int PG_TYPE_BPCHAR = 1042; public static final int PG_TYPE_INT8 = 20; public static final int PG_TYPE_INT2 = 21; public static final int PG_TYPE_INT4 = 23; public static final int PG_TYPE_TEXT = 25; public static final int PG_TYPE_OID = 26; public static final int PG_TYPE_FLOAT4 = 700; public static final int PG_TYPE_FLOAT8 = 701; public static final int PG_TYPE_UNKNOWN = 705; public static final int PG_TYPE_TEXTARRAY = 1009; public static final int PG_TYPE_DATE = 1082; public static final int PG_TYPE_TIME = 1083; public static final int PG_TYPE_TIMESTAMP_NO_TMZONE = 1114; public static final int PG_TYPE_NUMERIC = 1700; private final HashSet<Integer> typeSet = New.hashSet(); private int port = PgServer.DEFAULT_PORT; private boolean portIsSet; private boolean stop; private boolean trace; private ServerSocket serverSocket; private final Set<PgServerThread> running = Collections. synchronizedSet(new HashSet<PgServerThread>()); private final AtomicInteger pid = new AtomicInteger(); private String baseDir; private boolean allowOthers; private boolean isDaemon; private boolean ifExists; private String key, keyDatabase; @Override public void init(String... args) { port = DEFAULT_PORT; for (int i = 0; args != null && i < args.length; i++) { String a = args[i]; if (Tool.isOption(a, "-trace")) { trace = true; } else if (Tool.isOption(a, "-pgPort")) { port = Integer.decode(args[++i]); portIsSet = true; } else if (Tool.isOption(a, "-baseDir")) { baseDir = args[++i]; } else if (Tool.isOption(a, "-pgAllowOthers")) { allowOthers = true; } else if (Tool.isOption(a, "-pgDaemon")) { isDaemon = true; } else if (Tool.isOption(a, "-ifExists")) { ifExists = true; } else if (Tool.isOption(a, "-key")) { key = args[++i]; keyDatabase = args[++i]; } } org.h2.Driver.load(); // int testing; // trace = true; } boolean getTrace() { return trace; } /** * Print a message if the trace flag is enabled. * * @param s the message */ void trace(String s) { if (trace) { System.out.println(s); } } /** * Remove a thread from the list. * * @param t the thread to remove */ synchronized void remove(PgServerThread t) { running.remove(t); } /** * Print the stack trace if the trace flag is enabled. * * @param e the exception */ void traceError(Exception e) { if (trace) { e.printStackTrace(); } } @Override public String getURL() { return "pg://" + NetUtils.getLocalAddress() + ":" + port; } @Override public int getPort() { return port; } private boolean allow(Socket socket) { if (allowOthers) { return true; } try { return NetUtils.isLocalAddress(socket); } catch (UnknownHostException e) { traceError(e); return false; } } @Override public void start() { stop = false; try { serverSocket = NetUtils.createServerSocket(port, false); } catch (DbException e) { if (!portIsSet) { serverSocket = NetUtils.createServerSocket(0, false); } else { throw e; } } port = serverSocket.getLocalPort(); } @Override public void listen() { String threadName = Thread.currentThread().getName(); try { while (!stop) { Socket s = serverSocket.accept(); if (!allow(s)) { trace("Connection not allowed"); s.close(); } else { PgServerThread c = new PgServerThread(s, this); running.add(c); c.setProcessId(pid.incrementAndGet()); Thread thread = new Thread(c, threadName+" thread"); thread.setDaemon(isDaemon); c.setThread(thread); thread.start(); } } } catch (Exception e) { if (!stop) { e.printStackTrace(); } } } @Override public void stop() { // TODO server: combine with tcp server if (!stop) { stop = true; if (serverSocket != null) { try { serverSocket.close(); } catch (IOException e) { // TODO log exception e.printStackTrace(); } serverSocket = null; } } // TODO server: using a boolean 'now' argument? a timeout? for (PgServerThread c : New.arrayList(running)) { c.close(); try { Thread t = c.getThread(); if (t != null) { t.join(100); } } catch (Exception e) { // TODO log exception e.printStackTrace(); } } } @Override public boolean isRunning(boolean traceError) { if (serverSocket == null) { return false; } try { Socket s = NetUtils.createLoopbackSocket(serverSocket.getLocalPort(), false); s.close(); return true; } catch (Exception e) { if (traceError) { traceError(e); } return false; } } /** * Get the thread with the given process id. * * @param processId the process id * @return the thread */ PgServerThread getThread(int processId) { for (PgServerThread c : New.arrayList(running)) { if (c.getProcessId() == processId) { return c; } } return null; } String getBaseDir() { return baseDir; } @Override public boolean getAllowOthers() { return allowOthers; } @Override public String getType() { return "PG"; } @Override public String getName() { return "H2 PG Server"; } boolean getIfExists() { return ifExists; } /** * The Java implementation of the PostgreSQL function pg_get_indexdef. The * method is used to get CREATE INDEX command for an index, or the column * definition of one column in the index. * * @param conn the connection * @param indexId the index id * @param ordinalPosition the ordinal position (null if the SQL statement * should be returned) * @param pretty this flag is ignored * @return the SQL statement or the column name */ public static String getIndexColumn(Connection conn, int indexId, Integer ordinalPosition, Boolean pretty) throws SQLException { if (ordinalPosition == null || ordinalPosition.intValue() == 0) { PreparedStatement prep = conn.prepareStatement( "select sql from information_schema.indexes where id=?"); prep.setInt(1, indexId); ResultSet rs = prep.executeQuery(); if (rs.next()) { return rs.getString(1); } return ""; } PreparedStatement prep = conn.prepareStatement( "select column_name from information_schema.indexes " + "where id=? and ordinal_position=?"); prep.setInt(1, indexId); prep.setInt(2, ordinalPosition.intValue()); ResultSet rs = prep.executeQuery(); if (rs.next()) { return rs.getString(1); } return ""; } /** * Get the name of the current schema. * This method is called by the database. * * @param conn the connection * @return the schema name */ public static String getCurrentSchema(Connection conn) throws SQLException { ResultSet rs = conn.createStatement().executeQuery("call schema()"); rs.next(); return rs.getString(1); } /** * Get the OID of an object. This method is called by the database. * * @param conn the connection * @param tableName the table name * @return the oid */ public static int getOid(Connection conn, String tableName) throws SQLException { if (tableName.startsWith("\"") && tableName.endsWith("\"")) { tableName = tableName.substring(1, tableName.length() - 1); } PreparedStatement prep = conn.prepareStatement( "select oid from pg_class where relName = ?"); prep.setString(1, tableName); ResultSet rs = prep.executeQuery(); if (!rs.next()) { return 0; } return rs.getInt(1); } /** * Get the name of this encoding code. * This method is called by the database. * * @param code the encoding code * @return the encoding name */ public static String getEncodingName(int code) { switch (code) { case 0: return "SQL_ASCII"; case 6: return "UTF8"; case 8: return "LATIN1"; default: return code < 40 ? "UTF8" : ""; } } /** * Get the version. This method must return PostgreSQL to keep some clients * happy. This method is called by the database. * * @return the server name and version */ public static String getVersion() { return "PostgreSQL 8.1.4 server protocol using H2 " + Constants.getFullVersion(); } /** * Get the current system time. * This method is called by the database. * * @return the current system time */ public static Timestamp getStartTime() { return new Timestamp(System.currentTimeMillis()); } /** * Get the user name for this id. * This method is called by the database. * * @param conn the connection * @param id the user id * @return the user name */ public static String getUserById(Connection conn, int id) throws SQLException { PreparedStatement prep = conn.prepareStatement( "SELECT NAME FROM INFORMATION_SCHEMA.USERS WHERE ID=?"); prep.setInt(1, id); ResultSet rs = prep.executeQuery(); if (rs.next()) { return rs.getString(1); } return null; } /** * Check if the this session has the given database privilege. * This method is called by the database. * * @param id the session id * @param privilege the privilege to check * @return true */ public static boolean hasDatabasePrivilege(int id, String privilege) { return true; } /** * Check if the current session has access to this table. * This method is called by the database. * * @param table the table name * @param privilege the privilege to check * @return true */ public static boolean hasTablePrivilege(String table, String privilege) { return true; } /** * Get the current transaction id. * This method is called by the database. * * @param table the table name * @param id the id * @return 1 */ public static int getCurrentTid(String table, String id) { return 1; } /** * A fake wrapper around pg_get_expr(expr_text, relation_oid), in PostgreSQL * it "decompiles the internal form of an expression, assuming that any vars * in it refer to the relation indicated by the second parameter". * * @param exprText the expression text * @param relationOid the relation object id * @return always null */ public static String getPgExpr(String exprText, int relationOid) { return null; } /** * Check if the current session has access to this table. * This method is called by the database. * * @param conn the connection * @param pgType the PostgreSQL type oid * @param typeMod the type modifier (typically -1) * @return the name of the given type */ public static String formatType(Connection conn, int pgType, int typeMod) throws SQLException { PreparedStatement prep = conn.prepareStatement( "select typname from pg_catalog.pg_type where oid = ? and typtypmod = ?"); prep.setInt(1, pgType); prep.setInt(2, typeMod); ResultSet rs = prep.executeQuery(); if (rs.next()) { return rs.getString(1); } return null; } /** * Convert the SQL type to a PostgreSQL type * * @param type the SQL type * @return the PostgreSQL type */ public static int convertType(final int type) { switch (type) { case Types.BOOLEAN: return PG_TYPE_BOOL; case Types.VARCHAR: return PG_TYPE_VARCHAR; case Types.CLOB: return PG_TYPE_TEXT; case Types.CHAR: return PG_TYPE_BPCHAR; case Types.SMALLINT: return PG_TYPE_INT2; case Types.INTEGER: return PG_TYPE_INT4; case Types.BIGINT: return PG_TYPE_INT8; case Types.DECIMAL: return PG_TYPE_NUMERIC; case Types.REAL: return PG_TYPE_FLOAT4; case Types.DOUBLE: return PG_TYPE_FLOAT8; case Types.TIME: return PG_TYPE_TIME; case Types.DATE: return PG_TYPE_DATE; case Types.TIMESTAMP: return PG_TYPE_TIMESTAMP_NO_TMZONE; case Types.VARBINARY: return PG_TYPE_BYTEA; case Types.BLOB: return PG_TYPE_OID; case Types.ARRAY: return PG_TYPE_TEXTARRAY; default: return PG_TYPE_UNKNOWN; } } /** * Get the type hash set. * * @return the type set */ HashSet<Integer> getTypeSet() { return typeSet; } /** * Check whether a data type is supported. * A warning is logged if not. * * @param type the type */ void checkType(int type) { if (!typeSet.contains(type)) { trace("Unsupported type: " + type); } } /** * If no key is set, return the original database name. If a key is set, * check if the key matches. If yes, return the correct database name. If * not, throw an exception. * * @param db the key to test (or database name if no key is used) * @return the database name * @throws DbException if a key is set but doesn't match */ public String checkKeyAndGetDatabaseName(String db) { if (key == null) { return db; } if (key.equals(db)) { return keyDatabase; } throw DbException.get(ErrorCode.WRONG_USER_OR_PASSWORD); } @Override public boolean isDaemon() { return isDaemon; } }
mpl-2.0
gnosygnu/xowa_android
_400_xowa/src/main/java/gplx/xowa/langs/Xol_lang_itm_.java
17829
package gplx.xowa.langs; import gplx.*; import gplx.xowa.*; import gplx.core.intls.*; import gplx.xowa.xtns.cites.*; import gplx.xowa.xtns.gallery.*; import gplx.xowa.langs.bldrs.*; import gplx.xowa.langs.numbers.*; import gplx.xowa.langs.kwds.*; import gplx.xowa.apps.fsys.*; public class Xol_lang_itm_ { public static Io_url xo_lang_fil_(Xoa_fsys_mgr app_fsys_mgr, String lang_key) {return app_fsys_mgr.Cfg_lang_core_dir().GenSubFil(lang_key + ".gfs");} public static final byte Char_tid_ltr_l = 0, Char_tid_ltr_u = 1, Char_tid_num = 2, Char_tid_ws = 3, Char_tid_sym = 4, Char_tid_misc = 5; public static byte Char_tid(byte b) { switch (b) { case Byte_ascii.Ltr_A: case Byte_ascii.Ltr_B: case Byte_ascii.Ltr_C: case Byte_ascii.Ltr_D: case Byte_ascii.Ltr_E: case Byte_ascii.Ltr_F: case Byte_ascii.Ltr_G: case Byte_ascii.Ltr_H: case Byte_ascii.Ltr_I: case Byte_ascii.Ltr_J: case Byte_ascii.Ltr_K: case Byte_ascii.Ltr_L: case Byte_ascii.Ltr_M: case Byte_ascii.Ltr_N: case Byte_ascii.Ltr_O: case Byte_ascii.Ltr_P: case Byte_ascii.Ltr_Q: case Byte_ascii.Ltr_R: case Byte_ascii.Ltr_S: case Byte_ascii.Ltr_T: case Byte_ascii.Ltr_U: case Byte_ascii.Ltr_V: case Byte_ascii.Ltr_W: case Byte_ascii.Ltr_X: case Byte_ascii.Ltr_Y: case Byte_ascii.Ltr_Z: return Char_tid_ltr_u; case Byte_ascii.Ltr_a: case Byte_ascii.Ltr_b: case Byte_ascii.Ltr_c: case Byte_ascii.Ltr_d: case Byte_ascii.Ltr_e: case Byte_ascii.Ltr_f: case Byte_ascii.Ltr_g: case Byte_ascii.Ltr_h: case Byte_ascii.Ltr_i: case Byte_ascii.Ltr_j: case Byte_ascii.Ltr_k: case Byte_ascii.Ltr_l: case Byte_ascii.Ltr_m: case Byte_ascii.Ltr_n: case Byte_ascii.Ltr_o: case Byte_ascii.Ltr_p: case Byte_ascii.Ltr_q: case Byte_ascii.Ltr_r: case Byte_ascii.Ltr_s: case Byte_ascii.Ltr_t: case Byte_ascii.Ltr_u: case Byte_ascii.Ltr_v: case Byte_ascii.Ltr_w: case Byte_ascii.Ltr_x: case Byte_ascii.Ltr_y: case Byte_ascii.Ltr_z: return Char_tid_ltr_l; case Byte_ascii.Num_0: case Byte_ascii.Num_1: case Byte_ascii.Num_2: case Byte_ascii.Num_3: case Byte_ascii.Num_4: case Byte_ascii.Num_5: case Byte_ascii.Num_6: case Byte_ascii.Num_7: case Byte_ascii.Num_8: case Byte_ascii.Num_9: return Char_tid_num; case Byte_ascii.Space: case Byte_ascii.Nl: case Byte_ascii.Tab: case Byte_ascii.Cr: return Char_tid_ws; default: return Char_tid_misc; } } public static final byte[] Key_en = Bry_.new_a7("en"); public static Xol_lang_itm Lang_en_make(Xoa_lang_mgr lang_mgr) { Xol_lang_itm rv = new Xol_lang_itm(lang_mgr, Xol_lang_itm_.Key_en); Xol_lang_itm_.Lang_init(rv); rv.Evt_lang_changed(); return rv; } public static void Lang_init(Xol_lang_itm lang) { lang.Num_mgr().Separators_mgr().Set(Xol_num_mgr.Separators_key__grp, Xol_num_mgr.Separators_key__grp); lang.Num_mgr().Separators_mgr().Set(Xol_num_mgr.Separators_key__dec, Xol_num_mgr.Separators_key__dec); lang.Lnki_trail_mgr().Add_range(Byte_ascii.Ltr_a, Byte_ascii.Ltr_z);// REF.MW:MessagesEn.php|$linkTrail = '/^([a-z]+)(.*)$/sD'; Xol_kwd_mgr kwd_mgr = lang.Kwd_mgr(); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_redirect, "#REDIRECT"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_notoc, "__NOTOC__"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_nogallery, "__NOGALLERY__"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_forcetoc, "__FORCETOC__"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_toc, "__TOC__"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_noeditsection, "__NOEDITSECTION__"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_noheader, "__NOHEADER__"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_utc_month_int_len2, "CURRENTMONTH", "CURRENTMONTH2"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_utc_month_int, "CURRENTMONTH1"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_utc_month_name, "CURRENTMONTHNAME"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_utc_month_gen, "CURRENTMONTHNAMEGEN"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_utc_month_abrv, "CURRENTMONTHABBREV"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_utc_day_int, "CURRENTDAY"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_utc_day_int_len2, "CURRENTDAY2"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_utc_day_name, "CURRENTDAYNAME"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_utc_year, "CURRENTYEAR"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_utc_time, "CURRENTTIME"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_utc_hour, "CURRENTHOUR"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_lcl_month_int_len2, "LOCALMONTH", "LOCALMONTH2"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_lcl_month_int, "LOCALMONTH1"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_lcl_month_name, "LOCALMONTHNAME"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_lcl_month_gen, "LOCALMONTHNAMEGEN"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_lcl_month_abrv, "LOCALMONTHABBREV"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_lcl_day_int, "LOCALDAY"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_lcl_day_int_len2, "LOCALDAY2"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_lcl_day_name, "LOCALDAYNAME"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_lcl_year, "LOCALYEAR"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_lcl_time, "LOCALTIME"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_lcl_hour, "LOCALHOUR"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_num_pages, "NUMBEROFPAGES"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_num_articles, "NUMBEROFARTICLES"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_num_files, "NUMBEROFFILES"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_num_users, "NUMBEROFUSERS"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_num_users_active, "NUMBEROFACTIVEUSERS"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_num_edits, "NUMBEROFEDITS"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_num_views, "NUMBEROFVIEWS"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_ttl_page_txt, "PAGENAME"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_ttl_page_url, "PAGENAMEE"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_ns_txt, "NAME"+"SPACE"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_ns_url, "NAME"+"SPACEE"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_ns_talk_txt, "TALKSPACE"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_ns_talk_url, "TALKSPACEE"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_ns_subj_txt, "SUBJECTSPACE", "ARTICLESPACE"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_ns_subj_url, "SUBJECTSPACEE", "ARTICLESPACEE"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_ttl_full_txt, "FULLPAGENAME"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_ttl_full_url, "FULLPAGENAMEE"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_ttl_leaf_txt, "SUBPAGENAME"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_ttl_leaf_url, "SUBPAGENAMEE"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_ttl_base_txt, "BASEPAGENAME"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_ttl_base_url, "BASEPAGENAMEE"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_ttl_talk_txt, "TALKPAGENAME"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_ttl_talk_url, "TALKPAGENAMEE"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_ttl_subj_txt, "SUBJECTPAGENAME", "ARTICLEPAGENAME"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_ttl_subj_url, "SUBJECTPAGENAMEE", "ARTICLEPAGENAMEE"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_msg, "msg"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_subst, "subst:"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_safesubst, "safesubst:"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_msgnw, "msgnw"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_img_thumbnail, "thumbnail", "thumb"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_img_manualthumb, "thumbnail", "thumb"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_img_framed, "framed", "enframed", "frame"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_img_frameless, "frameless"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_img_upright, "upright"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_img_upright_factor, "upright_factor"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_img_border, "border"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_img_align, "align"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_img_valign, "valign"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_img_alt, "alt"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_img_class, "cl"+"ass"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_img_caption, "caption"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_img_link_url, "link-url"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_img_link_title, "link-title"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_img_link_target, "link-target"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_img_link_none, "no-link"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_img_width, "px"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_img_page, "page"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_img_none, "none"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_img_right, "right"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_img_center, "center", "centre"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_img_left, "left"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_img_baseline, "baseline"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_img_sub, "sub"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_img_super, "super", "sup"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_img_top, "top"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_img_text_top, "text-top"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_img_middle, "middle"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_img_bottom, "bottom"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_img_text_bottom, "text-bottom"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_img_link, "link"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_i18n_int, "int"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_site_sitename, "SITENAME"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_url_ns, "ns"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_url_nse, "nse"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_url_localurl, "localurl"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_url_localurle, "localurle"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_site_articlepath, "ARTICLEPATH"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_site_server, "SERVER"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_site_servername, "SERVERNAME"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_site_scriptpath, "SCRIPTPATH"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_site_stylepath, "STYLEPATH"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_i18n_grammar, "grammar"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_i18n_gender, "gender"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_notitleconvert, "__NOTITLECONVERT__", "__NOTC__"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_nocontentconvert, "__NOCONTENTCONVERT__", "__NOCC__"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_utc_week, "CURRENTWEEK"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_utc_dow, "CURRENTDOW"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_lcl_week, "LOCALWEEK"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_lcl_dow, "LOCALDOW"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_rev_id, "REVISIONID"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_rev_day_int, "REVISIONDAY"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_rev_day_int_len2, "REVISIONDAY2"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_rev_month_int_len2, "REVISIONMONTH"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_rev_month_int, "REVISIONMONTH1"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_rev_year, "REVISIONYEAR"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_rev_timestamp, "REVISIONTIMESTAMP"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_rev_user, "REVISIONUSER"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_i18n_plural, "plural"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_url_fullurl, "fullurl"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_url_fullurle, "fullurle"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_str_lcfirst, "lcfirst"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_str_ucfirst, "ucfirst"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_str_lc, "lc"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_str_uc, "uc"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_raw, "raw"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_page_displaytitle, "DISPLAYTITLE"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_str_rawsuffix, "R"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_newsectionlink, "__NEWSECTIONLINK__"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_nonewsectionlink, "__NONEWSECTIONLINK__"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_site_currentversion, "CURRENTVERSION"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_url_urlencode, "urlencode"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_url_anchorencode, "anchorencode"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_utc_timestamp, "CURRENTTIMESTAMP"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_lcl_timestamp, "LOCALTIMESTAMP"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_site_directionmark, "DIRECTIONMARK", "DIRMARK"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_i18n_language, "#language"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_site_contentlanguage, "CONTENTLANGUAGE", "CONTENTLANG"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_site_pagesinnamespace, "PAGESINNAMESPACE", "PAGESINNS"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_num_admins, "NUMBEROFADMINS"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_str_formatnum, "formatnum"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_str_padleft, "padleft"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_str_padright, "padright"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_misc_special, "#special"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_page_defaultsort, "DEFAULTSORT", "DEFAULTSORTKEY", "DEFAULTCATEGORYSORT"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_url_filepath, "filepath"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_misc_tag, "#tag"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_hiddencat, "__HIDDENCAT__"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_site_pagesincategory, "PAGESINCATEGORY", "PAGESINCAT"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_rev_pagesize, "PAGESIZE"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_index, "__INDEX__"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_noindex, "__NOINDEX__"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_site_numberingroup, "NUMBERINGROUP", "NUMINGROUP"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_staticredirect, "__STATICREDIRECT__"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_rev_protectionlevel, "PROTECTIONLEVEL"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_str_formatdate, "#formatdate", "#dateformat"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_url_path, "path"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_url_wiki, "wiki"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_url_query, "query"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_xtn_expr, "#expr"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_xtn_if, "#if"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_xtn_ifeq, "#ifeq"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_xtn_ifexpr, "#ifexpr"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_xtn_iferror, "#iferror"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_xtn_switch, "#switch"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_xtn_default, "#default"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_xtn_ifexist, "#ifexist"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_xtn_time, "#time"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_xtn_timel, "#timel"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_xtn_rel2abs, "#rel2abs"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_xtn_titleparts, "#titleparts"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_xowa_dbg, "#xowa_dbg"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_ogg_noplayer, "noplayer"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_ogg_noicon, "noicon"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_ogg_thumbtime, "thumbtime"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_xtn_geodata_coordinates, "#coordinates"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_url_canonicalurl, "canonicalurl"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_url_canonicalurle, "canonicalurle"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_lst, "#lst", "#section"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_lstx, "#lstx", "#section-x"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_lsth, "#lsth", "#section-h"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_invoke, "#invoke"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_property, "#property"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_noexternallanglinks, "noexternallanglinks"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_ns_num, "name"+"spacenumber"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_page_id, "pageid"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_disambig, "__DISAMBIG__"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_nocommafysuffix, "NOSEP"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_xowa, "#xowa"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_mapSources_deg2dd, "#deg2dd"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_mapSources_dd2dms, "#dd2dms"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_mapSources_geoLink, "#geolink"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_geoCrumbs_isin, "#isin"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_relatedArticles, "#related"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_insider, "#insider"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_massMessage_target, "#target"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_cascadingSources, "CASCADINGSOURCES"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_pendingChangeLevel, "PENDINGCHANGELEVEL"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_pagesUsingPendingChanges, "PAGESUSINGPENDINGCHANGES"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_bang, "!"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_wbreponame, "wbreponame"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_strx_len, "#len"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_strx_pos, "#pos"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_strx_rpos, "#rpos"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_strx_sub, "#sub"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_strx_count, "#count"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_strx_replace, "#replace"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_strx_explode, "#explode"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_strx_urldecode, "#urldecode"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_pagesincategory_pages, "pagesincategory_pages", "pages"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_pagesincategory_subcats, "pagesincategory_subcats", "subcats"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_pagesincategory_files, "pagesincategory_files", "files"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_rev_revisionsize, "REVISIONSIZE"); kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_pagebanner, "PAGEBANNER"); // NOTE: must be casematch; EX: in en.v, {{pagebanner}} is actually template name which calls {{PAGEBANNER}} kwd_mgr.New(Bool_.Y, Xol_kwd_grp_.Id_rev_protectionexpiry, "PROTECTIONEXPIRY"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_new_window_link, "#NewWindowLink"); kwd_mgr.New(Bool_.N, Xol_kwd_grp_.Id_categorytree, "#categorytree"); } }
agpl-3.0
geomajas/geomajas-project-client-gwt2
plugin/print/impl/src/main/java/org/geomajas/gwt2/plugin/print/client/PrintService.java
1904
/* * This is part of Geomajas, a GIS framework, http://www.geomajas.org/. * * Copyright 2008-2015 Geosparc nv, http://www.geosparc.com/, Belgium. * * The program is available in open source according to the GNU Affero * General Public License. All contributions in this program are covered * by the Geomajas Contributors License Agreement. For full licensing * details, see LICENSE.txt in the project root. */ package org.geomajas.gwt2.plugin.print.client; import com.google.gwt.core.client.Callback; import org.geomajas.annotation.Api; import org.geomajas.gwt2.plugin.print.client.event.PrintRequestInfo; import org.geomajas.gwt2.plugin.print.client.event.PrintFinishedInfo; import org.geomajas.gwt2.plugin.print.client.event.PrintRequestHandler; /** * Service for print-related server calls. * * @author Jan Venstermans * @since 2.1.0 */ @Api(allMethods = true) public interface PrintService { /** * Generic print method. Input is a {@link org.geomajas.gwt2.plugin.print.client.event.PrintRequestInfo} object.<br> * After a server processing has finished, a {@link PrintFinishedInfo} is returned in a callback. * This respons object contains an encoded url for the printed object. * * @param printRequestInfo info necessary to create the request (and later process it), containing the template * @param callback callback with the encodeUrl */ void print(PrintRequestInfo printRequestInfo, Callback<PrintFinishedInfo, Void> callback); /** * Print method for a {@link PrintRequestHandler}. * The handler will receive event calls when processing the {@link PrintRequestInfo}. * * @param printRequestInfo info necessary to create the request (and later process it), containing the template * @param printRequestHandler handler that will listen to request events */ void print(PrintRequestInfo printRequestInfo, PrintRequestHandler printRequestHandler); }
agpl-3.0
shenan4321/BIMplatform
generated/cn/dlb/bim/models/ifc4/IfcShell.java
1124
/** * Copyright (C) 2009-2014 BIMserver.org * * 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/>. */ package cn.dlb.bim.models.ifc4; import cn.dlb.bim.ifc.emf.IdEObject; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Ifc Shell</b></em>'. * <!-- end-user-doc --> * * * @see cn.dlb.bim.models.ifc4.Ifc4Package#getIfcShell() * @model interface="true" abstract="true" * @extends IdEObject * @generated */ public interface IfcShell extends IdEObject { } // IfcShell
agpl-3.0
tagland/tagland
anarchia-obj/src/us/anarchia/obj/Link.java
1532
/* * Copyright 2010 Laramie Crocker and tagland.org. This file is part of the software tagland.org. * It is licensed under the GNU Affero General Public License. You may read the software license in the project distribution called LICENSE.txt or here: http://www.gnu.org/licenses/ * Source files may be downloaded from https://sourceforge.net/projects/tagland */ package us.anarchia.obj; //import java.net.MalformedURLException; //import java.net.URL; /** Link identity is provided by the URL field. If two links have equal url's, then they are equal, even if description is different. */ public class Link extends Storable { public Link(){ } //public Link(URL url, String description){ public Link(String urlString, String description){ this.urlString = urlString; this.description = description; } /*public Link(String surl, String description) throws MalformedURLException { this.urlString = new URL(surl); this.description = description; } */ //public URL url; public String urlString; public String description; public boolean equals(Object other){ if (null != other && other instanceof Link){ Link ol = (Link)other; if (ol.urlString.equals(this.urlString)){ return true; } } return false; } public int hashCode(){ return urlString.hashCode(); } public String toString(){ String urlID = "null"; if (null!=urlString){ urlID = urlString; } return "Link["+urlID+"]:"+description; } }
agpl-3.0
GeoNet/GeoNetCWBQuery
src/test/java/gov/usgs/anss/query/cwb/holdings/CWBServerMock.java
1401
/* * Copyright 2010, Institute of Geological & Nuclear Sciences Ltd or * third-party contributors as indicated by the @author tags. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * */ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package gov.usgs.anss.query.cwb.holdings; import gov.usgs.anss.query.cwb.holdings.CWBHoldingsServer; import org.joda.time.DateTime; /** * * @author geoffc */ public class CWBServerMock implements CWBHoldingsServer { public CWBServerMock(String host, int port) { } private String channels; public void setChannels(String channels) { this.channels = channels; } public String listChannels(DateTime begin, Double duration) { return this.channels; } }
agpl-3.0
WebDataConsulting/billing
src/java/com/sapienter/jbilling/server/util/db/PreferenceTypeDTO.java
3633
/* jBilling - The Enterprise Open Source Billing System Copyright (C) 2003-2011 Enterprise jBilling Software Ltd. and Emiliano Conde This file is part of jbilling. jbilling 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. jbilling 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 jbilling. If not, see <http://www.gnu.org/licenses/>. This source was modified by Web Data Technologies LLP (www.webdatatechnologies.in) since 15 Nov 2015. You may download the latest source from webdataconsulting.github.io. */ package com.sapienter.jbilling.server.util.db; import java.io.Serializable; import java.util.HashSet; import java.util.Set; import javax.persistence.*; import com.sapienter.jbilling.server.metafields.db.ValidationRule; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; import com.sapienter.jbilling.server.util.ServerConstants; @Entity @Table(name="preference_type") @Cache(usage = CacheConcurrencyStrategy.READ_ONLY) public class PreferenceTypeDTO extends AbstractDescription implements java.io.Serializable { private int id; private String defaultValue; private Set<PreferenceDTO> preferences = new HashSet<PreferenceDTO>(0); private ValidationRule validationRule; public PreferenceTypeDTO() { } public PreferenceTypeDTO(int id) { this.id = id; } public PreferenceTypeDTO(int id, String defaultValue, Set<PreferenceDTO> preferences) { this.id = id; this.defaultValue = defaultValue; this.preferences = preferences; } @Id @Column(name="id", unique=true, nullable=false) public int getId() { return this.id; } public void setId(int id) { this.id = id; } @Column(name="def_value", length=200) public String getDefaultValue() { return defaultValue; } public void setDefaultValue(String defaultValue) { this.defaultValue = defaultValue; } @OneToMany(cascade=CascadeType.ALL, fetch=FetchType.LAZY, mappedBy="preferenceType") public Set<PreferenceDTO> getPreferences() { return this.preferences; } public void setPreferences(Set<PreferenceDTO> preferences) { this.preferences = preferences; } public void addPreference(PreferenceDTO preference){this.preferences.add(preference);} public void removePreference(PreferenceDTO preference){this.preferences.remove(preference);} @Transient protected String getTable() { return ServerConstants.TABLE_PREFERENCE_TYPE; } @Transient public String getInstructions() { return getDescription(ServerConstants.LANGUAGE_ENGLISH_ID, "instruction"); } @Transient public String getInstructions(Integer languageId) { return getDescription(languageId, "instruction"); } @OneToOne(fetch = FetchType.LAZY, cascade = CascadeType.ALL) @JoinColumn(name = "validation_rule_id", nullable = true) public ValidationRule getValidationRule() { return validationRule; } public void setValidationRule(ValidationRule validationRule) { this.validationRule = validationRule; } }
agpl-3.0
SilverDav/Silverpeas-Core
core-library/src/main/java/org/silverpeas/core/contribution/content/form/Form.java
4942
/* * Copyright (C) 2000 - 2021 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: * "https://www.silverpeas.org/legal/floss_exception.html" * * 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 org.silverpeas.core.contribution.content.form; import org.apache.commons.fileupload.FileItem; import javax.servlet.jsp.JspWriter; import java.util.List; /** * A Form is an object which can display in HTML the content of a DataRecord to a end user and can * retrieve via HTTP any updated values. * @see DataRecord * @see RecordTemplate * @see FieldDisplayer */ public interface Form { /** * Prints the javascripts which will be used to control the new values given to the data record * fields. The error messages may be adapted to a local language. The RecordTemplate gives the * field type and constraints. The RecordTemplate gives the local label too. Never throws an * Exception but log a silvertrace and writes an empty string when : * <ul> * <li>a field is unknown by the template.</li> * <li>a field has not the required type.</li> * </ul> */ void displayScripts(JspWriter out, PagesContext pagesContext); /** * Prints the HTML layout of the dataRecord using the RecordTemplate to extract labels and extra * informations. The value formats may be adapted to a local language. Never throws an Exception * but log a silvertrace and writes an empty string when : * <ul> * <li>a field is unknown by the template.</li> * <li>a field has not the required type.</li> * </ul> */ void display(JspWriter out, PagesContext pagesContext, DataRecord record) throws FormException; void display(JspWriter out, PagesContext pagesContext) throws FormException; /** * Updates the values of the dataRecord using the RecordTemplate to extra control information * (readOnly or mandatory status). The fieldName must be used to retrieve the HTTP parameter from * the request. this method treats only wysiwyg fields. * @throws FormException if the field type is not a managed type or if the field doesn't accept * the new value. */ List<String> updateWysiwyg(List<FileItem> items, DataRecord record, PagesContext pagesContext) throws FormException; /** * Updates the values of the dataRecord using the RecordTemplate to extra control information * (readOnly or mandatory status). The fieldName must be used to retrieve the HTTP parameter from * the request. * @throws FormException if the field type is not a managed type or if the field doesn't accept * the new value. */ List<String> update(List<FileItem> items, DataRecord record, PagesContext pagesContext) throws FormException; /** * Updates the values of the dataRecord using the RecordTemplate to extra control information * (readOnly or mandatory status). The fieldName must be used to retrieve the HTTP parameter from * the request. * @throws FormException if the field type is not a managed type or if the field doesn't * accept the new value. */ List<String> update(List<FileItem> items, DataRecord record, PagesContext pagesContext, boolean updateWysiwyg) throws FormException; /** * Get the form title */ String getTitle(); /** * Gets the template of all fields that make this form * @return a List of FieldTemplate */ List<FieldTemplate> getFieldTemplates(); String toString(PagesContext pagesContext, DataRecord record); String toString(PagesContext pagesContext); boolean isEmpty(List<FileItem> items, DataRecord record, PagesContext pagesContext); void setFormName(String name); void setData(DataRecord data); /** * Defines if this form is a 'view' form (opposite to an 'update' form) * A 'view' form may have some specific behaviors like to not display empty fields * @param viewForm true if this form is a 'view' form */ void setViewForm(boolean viewForm); String getFormName(); DataRecord getData(); }
agpl-3.0
heniancheng/FRODO
src/frodo2/algorithms/dpop/privacy/VarCodenameMsg.java
4483
/* FRODO: a FRamework for Open/Distributed Optimization Copyright (C) 2008-2013 Thomas Leaute, Brammert Ottens & Radoslaw Szymanek FRODO 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. FRODO 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/>. How to contact the authors: <http://frodo2.sourceforge.net/> */ package frodo2.algorithms.dpop.privacy; import java.io.Externalizable; import java.io.IOException; import java.io.ObjectInput; import java.io.ObjectOutput; import java.lang.reflect.Array; import java.util.Arrays; import frodo2.communication.MessageWith3Payloads; /** Message sent by EncryptedUTIL to transmit codeNames * @param <V> Class used for value */ public class VarCodenameMsg<V> extends MessageWith3Payloads < String[], String , V[][] > implements Externalizable { /** Used for serialization */ private static final long serialVersionUID = -893201749257599489L; /** Constructor * @param sender the sender of this message * @param receiver the receiver of this message * @param codeName the code name of the sender * @param domains the domain of the sender variable, in cleartext AND the obfuscated domain */ public VarCodenameMsg(String sender, String receiver, String codeName, V[][] domains){ super(EncryptedUTIL.CODENAME_TYPE, new String[]{sender,receiver}, codeName, domains); } /** * Empty constructor used for Externalization */ public VarCodenameMsg(){ this.type = EncryptedUTIL.CODENAME_TYPE; } /** @return the sender of this message */ public String getSender(){ return this.getPayload1()[0]; } /** @return the receiver of this message */ public String getReceiver(){ return this.getPayload1()[1]; } /** @return the code name of the sender */ public String getCodeName(){ return this.getPayload2(); } /** @return the obfuscated domain */ public V[] getOfuscatedDomain(){ return this.getPayload3()[1]; } /** @return the cleartext domain */ public V[] getCleartextDomain(){ return this.getPayload3()[0]; } /** @return both cleartext and obfuscated domain. Clear in [0] and obfuscated in [1] */ public V[][] getDomains(){ return this.getPayload3(); } /** * @see frodo2.communication.MessageWith3Payloads#toString() */ public String toString(){ return "Message(type = `" + super.type + "')" + "\n\tsender: " + getSender() + "\n\tdest: " + getReceiver() + "\n\tcodeName: " + getCodeName() + "\n\tcleartext domain: " + Arrays.asList(this.getCleartextDomain()) + "\n\tobfuscated domain: " + Arrays.asList(this.getOfuscatedDomain()); } /** @see java.io.Externalizable#readExternal(java.io.ObjectInput) */ @SuppressWarnings("unchecked" ) public void readExternal(ObjectInput in) throws IOException, ClassNotFoundException { String sender = (String) in.readObject(); String receiver = (String) in.readObject(); this.setPayload1(new String[]{sender,receiver}); this.setPayload2((String)in.readObject()); int size = in.readInt(); V v = (V) in.readObject(); V[] vv = (V[]) Array.newInstance(v.getClass(), size); V[][] array = (V[][]) Array.newInstance(vv.getClass(), 2) ; array[0] = vv; array[1] = (V[]) Array.newInstance(v.getClass(), size); array[0][0] = v; //first object of clearText domain if(size > 1) for(int i=1;i<size;i++){ //clearText domain array[0][i] = (V) in.readObject(); } for(int i=0;i<size;i++){ //Obfuscated domain array[1][i] = (V) in.readObject(); } this.setPayload3(array); } /** @see java.io.Externalizable#writeExternal(java.io.ObjectOutput) */ public void writeExternal(ObjectOutput out) throws IOException { out.writeObject(this.getSender()); out.writeObject(this.getReceiver()); out.writeObject(this.getCodeName()); out.writeInt(this.getCleartextDomain().length); for(V val : this.getCleartextDomain()){ out.writeObject(val); } for(V val : this.getOfuscatedDomain()){ out.writeObject(val); } } }
agpl-3.0
subshare/subshare
org.subshare/org.subshare.test/src/test/java/org/subshare/test/IgnoreRuleRepoToRepoSyncIT.java
12312
package org.subshare.test; import static co.codewizards.cloudstore.core.oio.OioFileFactory.*; import static org.assertj.core.api.Assertions.*; import java.util.Properties; import org.junit.Test; import org.subshare.local.UserRepoKeyPublicKeyHelper; import org.subshare.local.persistence.UserRepoKeyPublicKey; import co.codewizards.cloudstore.core.oio.File; import co.codewizards.cloudstore.core.util.PropertiesUtil; import mockit.Mock; import mockit.MockUp; //@RunWith(JMockit.class) public class IgnoreRuleRepoToRepoSyncIT extends AbstractRepoToRepoSyncIT { @Override public void before() throws Exception { super.before(); new MockUp<UserRepoKeyPublicKeyHelper>() { @Mock void createUserIdentities(UserRepoKeyPublicKey userRepoKeyPublicKey) { // Our mock should do nothing, because we don't have a real UserRegistry here. } }; } @Test public void ignoreRulesExistBeforeAffectedFiles() throws Exception { createLocalSourceAndRemoteRepo(); populateLocalSourceRepo(); // Create ignore rules. Properties properties = new Properties(); properties.put("ignore[file1].namePattern", "file1"); properties.put("ignore[dir1].namePattern", "dir1"); PropertiesUtil.store(createFile(localSrcRoot, ".subshare.properties"), properties, null); File src_dir2 = createFile(localSrcRoot, "2"); assertThat(src_dir2.getIoFile()).isDirectory(); File src_file1 = createFileWithRandomContent(localSrcRoot, "file1"); File src_dir1 = createDirectory(localSrcRoot, "dir1"); File src_dir1_aa1 = createFileWithRandomContent(src_dir1, "aa1"); File src_dir1_bb1 = createFileWithRandomContent(src_dir1, "bb1"); File src_dir2_file1 = createFileWithRandomContent(src_dir2, "file1"); File src_dir2_dir1 = createDirectory(src_dir2, "dir1"); File src_dir2_dir1_aa2 = createFileWithRandomContent(src_dir2_dir1, "aa2"); File src_dir2_dir1_bb2 = createFileWithRandomContent(src_dir2_dir1, "bb2"); assertThat(src_file1.getIoFile()).isFile(); assertThat(src_dir2_file1.getIoFile()).isFile(); assertThat(src_dir1.getIoFile()).isDirectory(); assertThat(src_dir1_aa1.getIoFile()).isFile(); assertThat(src_dir1_bb1.getIoFile()).isFile(); assertThat(src_dir2_dir1.getIoFile()).isDirectory(); assertThat(src_dir2_dir1_aa2.getIoFile()).isFile(); assertThat(src_dir2_dir1_bb2.getIoFile()).isFile(); syncFromLocalSrcToRemote(); determineRemotePathPrefix2Encrypted(); createLocalDestinationRepo(); syncFromRemoteToLocalDest(false); File dst_dir2 = createFile(localDestRoot, "2"); assertThat(dst_dir2.getIoFile()).isDirectory(); File dst_file1 = createFile(localDestRoot, "file1"); File dst_dir1 = createFile(localDestRoot, "dir1"); File dst_dir1_aa1 = createFile(dst_dir1, "aa1"); File dst_dir1_bb1 = createFile(dst_dir1, "bb1"); File dst_dir2_file1 = createFile(dst_dir2, "file1"); File dst_dir2_dir1 = createFile(dst_dir2, "dir1"); File dst_dir2_dir1_aa2 = createFile(dst_dir2_dir1, "aa2"); File dst_dir2_dir1_bb2 = createFile(dst_dir2_dir1, "bb2"); assertThat(dst_file1.getIoFile()).doesNotExist(); assertThat(dst_dir2_file1.getIoFile()).doesNotExist(); assertThat(dst_dir1.getIoFile()).doesNotExist(); assertThat(dst_dir1_aa1.getIoFile()).doesNotExist(); assertThat(dst_dir1_bb1.getIoFile()).doesNotExist(); assertThat(dst_dir2_dir1.getIoFile()).doesNotExist(); assertThat(dst_dir2_dir1_aa2.getIoFile()).doesNotExist(); assertThat(dst_dir2_dir1_bb2.getIoFile()).doesNotExist(); } @Test public void ignoreRulesBecomeDisabled() throws Exception { createLocalSourceAndRemoteRepo(); populateLocalSourceRepo(); // Create ignore rules. Properties properties = new Properties(); properties.put("ignore[file1].namePattern", "file1"); properties.put("ignore[dir1].namePattern", "dir1"); PropertiesUtil.store(createFile(localSrcRoot, ".subshare.properties"), properties, null); File src_dir2 = createFile(localSrcRoot, "2"); assertThat(src_dir2.getIoFile()).isDirectory(); File src_file1 = createFileWithRandomContent(localSrcRoot, "file1"); File src_dir1 = createDirectory(localSrcRoot, "dir1"); File src_dir1_aa1 = createFileWithRandomContent(src_dir1, "aa1"); File src_dir1_bb1 = createFileWithRandomContent(src_dir1, "bb1"); File src_dir2_file1 = createFileWithRandomContent(src_dir2, "file1"); File src_dir2_dir1 = createDirectory(src_dir2, "dir1"); File src_dir2_dir1_aa2 = createFileWithRandomContent(src_dir2_dir1, "aa2"); File src_dir2_dir1_bb2 = createFileWithRandomContent(src_dir2_dir1, "bb2"); assertThat(src_file1.getIoFile()).isFile(); assertThat(src_dir1.getIoFile()).isDirectory(); assertThat(src_dir1_aa1.getIoFile()).isFile(); assertThat(src_dir1_bb1.getIoFile()).isFile(); assertThat(src_dir2_file1.getIoFile()).isFile(); assertThat(src_dir2_dir1.getIoFile()).isDirectory(); assertThat(src_dir2_dir1_aa2.getIoFile()).isFile(); assertThat(src_dir2_dir1_bb2.getIoFile()).isFile(); syncFromLocalSrcToRemote(); determineRemotePathPrefix2Encrypted(); createLocalDestinationRepo(); syncFromRemoteToLocalDest(false); File dst_dir2 = createFile(localDestRoot, "2"); assertThat(dst_dir2.getIoFile()).isDirectory(); File dst_file1 = createFile(localDestRoot, "file1"); File dst_dir1 = createFile(localDestRoot, "dir1"); File dst_dir1_aa1 = createFile(dst_dir1, "aa1"); File dst_dir1_bb1 = createFile(dst_dir1, "bb1"); File dst_dir2_file1 = createFile(dst_dir2, "file1"); File dst_dir2_dir1 = createFile(dst_dir2, "dir1"); File dst_dir2_dir1_aa2 = createFile(dst_dir2_dir1, "aa2"); File dst_dir2_dir1_bb2 = createFile(dst_dir2_dir1, "bb2"); assertThat(dst_file1.getIoFile()).doesNotExist(); assertThat(dst_dir1.getIoFile()).doesNotExist(); assertThat(dst_dir1_aa1.getIoFile()).doesNotExist(); assertThat(dst_dir1_bb1.getIoFile()).doesNotExist(); assertThat(dst_dir2_file1.getIoFile()).doesNotExist(); assertThat(dst_dir2_dir1.getIoFile()).doesNotExist(); assertThat(dst_dir2_dir1_aa2.getIoFile()).doesNotExist(); assertThat(dst_dir2_dir1_bb2.getIoFile()).doesNotExist(); syncFromLocalSrcToRemote(); // again - just to make sure there's no deletion synced back. properties = new Properties(); properties.put("ignore[file1].enabled", "false"); properties.put("ignore[dir1].enabled", "false"); PropertiesUtil.store(createFile(src_dir2, ".subshare.properties"), properties, null); syncFromLocalSrcToRemote(); syncFromRemoteToLocalDest(false); assertThat(src_file1.getIoFile()).isFile(); assertThat(src_dir1.getIoFile()).isDirectory(); assertThat(src_dir1_aa1.getIoFile()).isFile(); assertThat(src_dir1_bb1.getIoFile()).isFile(); assertThat(src_dir2_file1.getIoFile()).isFile(); assertThat(src_dir2_dir1.getIoFile()).isDirectory(); assertThat(src_dir2_dir1_aa2.getIoFile()).isFile(); assertThat(src_dir2_dir1_bb2.getIoFile()).isFile(); assertThat(dst_file1.getIoFile()).doesNotExist(); assertThat(dst_dir1.getIoFile()).doesNotExist(); assertThat(dst_dir1_aa1.getIoFile()).doesNotExist(); assertThat(dst_dir1_bb1.getIoFile()).doesNotExist(); assertThat(dst_dir2_file1.getIoFile()).isFile(); assertThat(dst_dir2_dir1.getIoFile()).isDirectory(); assertThat(dst_dir2_dir1_aa2.getIoFile()).isFile(); assertThat(dst_dir2_dir1_bb2.getIoFile()).isFile(); } @Test public void ignoreRulesAddedAfterFilesSynced() throws Exception { createLocalSourceAndRemoteRepo(); populateLocalSourceRepo(); File src_dir2 = createFile(localSrcRoot, "2"); assertThat(src_dir2.getIoFile()).isDirectory(); File src_file1 = createFileWithRandomContent(localSrcRoot, "file1"); File src_dir1 = createDirectory(localSrcRoot, "dir1"); File src_dir1_aa1 = createFileWithRandomContent(src_dir1, "aa1"); File src_dir1_bb1 = createFileWithRandomContent(src_dir1, "bb1"); File src_dir2_file1 = createFileWithRandomContent(src_dir2, "file1"); File src_dir2_dir1 = createDirectory(src_dir2, "dir1"); File src_dir2_dir1_aa2 = createFileWithRandomContent(src_dir2_dir1, "aa2"); File src_dir2_dir1_bb2 = createFileWithRandomContent(src_dir2_dir1, "bb2"); assertThat(src_file1.getIoFile()).isFile(); assertThat(src_dir1.getIoFile()).isDirectory(); assertThat(src_dir1_aa1.getIoFile()).isFile(); assertThat(src_dir1_bb1.getIoFile()).isFile(); assertThat(src_dir2_file1.getIoFile()).isFile(); assertThat(src_dir2_dir1.getIoFile()).isDirectory(); assertThat(src_dir2_dir1_aa2.getIoFile()).isFile(); assertThat(src_dir2_dir1_bb2.getIoFile()).isFile(); syncFromLocalSrcToRemote(); determineRemotePathPrefix2Encrypted(); createLocalDestinationRepo(); syncFromRemoteToLocalDest(false); File dst_dir2 = createFile(localDestRoot, "2"); assertThat(dst_dir2.getIoFile()).isDirectory(); File dst_file1 = createFile(localDestRoot, "file1"); File dst_dir1 = createFile(localDestRoot, "dir1"); File dst_dir1_aa1 = createFile(dst_dir1, "aa1"); File dst_dir1_bb1 = createFile(dst_dir1, "bb1"); File dst_dir2_file1 = createFile(dst_dir2, "file1"); File dst_dir2_dir1 = createFile(dst_dir2, "dir1"); File dst_dir2_dir1_aa2 = createFile(dst_dir2_dir1, "aa2"); File dst_dir2_dir1_bb2 = createFile(dst_dir2_dir1, "bb2"); assertThat(src_file1.getIoFile()).isFile(); assertThat(src_dir1.getIoFile()).isDirectory(); assertThat(src_dir1_aa1.getIoFile()).isFile(); assertThat(src_dir1_bb1.getIoFile()).isFile(); assertThat(src_dir2_file1.getIoFile()).isFile(); assertThat(src_dir2_dir1.getIoFile()).isDirectory(); assertThat(src_dir2_dir1_aa2.getIoFile()).isFile(); assertThat(src_dir2_dir1_bb2.getIoFile()).isFile(); assertThat(dst_file1.getIoFile()).isFile(); assertThat(dst_dir1.getIoFile()).isDirectory(); assertThat(dst_dir1_aa1.getIoFile()).isFile(); assertThat(dst_dir1_bb1.getIoFile()).isFile(); assertThat(dst_dir2_file1.getIoFile()).isFile(); assertThat(dst_dir2_dir1.getIoFile()).isDirectory(); assertThat(dst_dir2_dir1_aa2.getIoFile()).isFile(); assertThat(dst_dir2_dir1_bb2.getIoFile()).isFile(); // TODO: modify files on both sides and check whether they're synced! They should be neither deleted nor synced! // TODO 2: Check HistoCryptoRepoFile.deletedByIgnoreRule - should be true! Maybe add a real deletion as contrast and check whether it is false there. // Create ignore rules. Properties properties = new Properties(); properties.put("ignore[file1].namePattern", "file1"); properties.put("ignore[dir1].namePattern", "dir1"); PropertiesUtil.store(createFile(localSrcRoot, ".subshare.properties"), properties, null); syncFromLocalSrcToRemote(); syncFromRemoteToLocalDest(false); assertThat(src_file1.getIoFile()).isFile(); assertThat(src_dir1.getIoFile()).isDirectory(); assertThat(src_dir1_aa1.getIoFile()).isFile(); assertThat(src_dir1_bb1.getIoFile()).isFile(); assertThat(src_dir2_file1.getIoFile()).isFile(); assertThat(src_dir2_dir1.getIoFile()).isDirectory(); assertThat(src_dir2_dir1_aa2.getIoFile()).isFile(); assertThat(src_dir2_dir1_bb2.getIoFile()).isFile(); assertThat(dst_file1.getIoFile()).isFile(); assertThat(dst_dir1.getIoFile()).isDirectory(); assertThat(dst_dir1_aa1.getIoFile()).isFile(); assertThat(dst_dir1_bb1.getIoFile()).isFile(); assertThat(dst_dir2_file1.getIoFile()).isFile(); assertThat(dst_dir2_dir1.getIoFile()).isDirectory(); assertThat(dst_dir2_dir1_aa2.getIoFile()).isFile(); assertThat(dst_dir2_dir1_bb2.getIoFile()).isFile(); syncFromLocalSrcToRemote(); syncFromRemoteToLocalDest(false); assertThat(src_file1.getIoFile()).isFile(); assertThat(src_dir1.getIoFile()).isDirectory(); assertThat(src_dir1_aa1.getIoFile()).isFile(); assertThat(src_dir1_bb1.getIoFile()).isFile(); assertThat(src_dir2_file1.getIoFile()).isFile(); assertThat(src_dir2_dir1.getIoFile()).isDirectory(); assertThat(src_dir2_dir1_aa2.getIoFile()).isFile(); assertThat(src_dir2_dir1_bb2.getIoFile()).isFile(); assertThat(dst_file1.getIoFile()).isFile(); assertThat(dst_dir1.getIoFile()).isDirectory(); assertThat(dst_dir1_aa1.getIoFile()).isFile(); assertThat(dst_dir1_bb1.getIoFile()).isFile(); assertThat(dst_dir2_file1.getIoFile()).isFile(); assertThat(dst_dir2_dir1.getIoFile()).isDirectory(); assertThat(dst_dir2_dir1_aa2.getIoFile()).isFile(); assertThat(dst_dir2_dir1_bb2.getIoFile()).isFile(); } }
agpl-3.0
NicolasEYSSERIC/Silverpeas-Core
ejb-core/formtemplate/src/test/java/com/silverpeas/workflow/engine/model/ProcessModelManagerImplTest.java
3918
/** * Copyright (C) 2000 - 2012 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://www.silverpeas.org/docs/core/legal/floss_exception.html" * * 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/>. */ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.silverpeas.workflow.engine.model; import java.io.File; import com.silverpeas.workflow.api.model.Role; import com.silverpeas.workflow.api.model.ProcessModel; import org.apache.commons.io.FileUtils; import static org.junit.Assert.*; /** * * @author ehugonnet */ public class ProcessModelManagerImplTest { public ProcessModelManagerImplTest() { } @org.junit.BeforeClass public static void setUpClass() throws Exception { } @org.junit.AfterClass public static void tearDownClass() throws Exception { } @org.junit.Before public void setUp() throws Exception { } @org.junit.After public void tearDown() throws Exception { } /** * Test of loadProcessModel method, of class ProcessModelManagerImpl. */ @org.junit.Test public void testLoadProcessModel() throws Exception { System.out.println("loadProcessModel"); String processFileName = "DemandeCongesSimple.xml"; boolean absolutePath = false; ProcessModelManagerImpl instance = new ProcessModelManagerImpl(); ProcessModel result = instance.loadProcessModel(processFileName, absolutePath); assertNotNull(result); Role[] roles = result.getRoles(); assertNotNull(roles); assertEquals(3, roles.length); assertNotNull(result.getRole("Employe")); assertEquals("Demandeur", result.getRole("Employe").getLabel("Employe", "fr")); assertEquals("Demandeur", result.getRole("Employe").getLabel("Employe", "en")); } /** * Test of saveProcessModel method, of class ProcessModelManagerImpl. */ @org.junit.Test public void testSaveProcessModel() throws Exception { System.out.println("saveProcessModel"); String processFileName = "DemandeCongesSimple.xml"; boolean absolutePath = false; ProcessModelManagerImpl instance = new ProcessModelManagerImpl(); ProcessModel process = instance.loadProcessModel(processFileName, absolutePath); String resultFileName = "DemandeCongesSimpleSerial.xml"; instance.saveProcessModel(process, resultFileName); FileUtils.contentEquals(new File(instance.getProcessPath(processFileName)), new File(instance.getProcessPath(resultFileName))); } /** * Test of getProcessModelDir method, of class ProcessModelManagerImpl. */ @org.junit.Test public void testGetProcessModelDir() { System.out.println("getProcessModelDir"); ProcessModelManagerImpl instance = new ProcessModelManagerImpl(); String expResult = System.getProperty("basedir") + File.separatorChar + "target" + File.separatorChar + "test-classes" + File.separatorChar; String result = instance.getProcessModelDir(); assertEquals(expResult, result); } }
agpl-3.0
WaywardRealms/Wayward
WaywardEconomy/src/main/java/net/wayward_realms/waywardeconomy/currency/CurrencyImpl.java
2269
package net.wayward_realms.waywardeconomy.currency; import net.wayward_realms.waywardlib.economy.Currency; import java.util.HashMap; import java.util.Map; public class CurrencyImpl implements Currency { private String name; private String nameSingular; private String namePlural; private int rate; private int defaultAmount; @Override public String getName() { return name; } @Override public void setName(String name) { this.name = name; } @Override public String getNameSingular() { return nameSingular; } @Override public void setNameSingular(String name) { this.nameSingular = name; } @Override public String getNamePlural() { return namePlural; } @Override public void setNamePlural(String name) { this.namePlural = name; } @Override public int convert(int amount, Currency currency) { return (amount * getRate()) / currency.getRate(); } @Override public int getRate() { return rate; } @Override public void setRate(int rate) { this.rate = rate; } @Override public int getDefaultAmount() { return defaultAmount; } @Override public void setDefaultAmount(int amount) { this.defaultAmount = amount; } @Override public Map<String, Object> serialize() { Map<String, Object> serialised = new HashMap<>(); serialised.put("name", name); serialised.put("name-singular", nameSingular); serialised.put("name-plural", namePlural); serialised.put("rate", rate); serialised.put("default-amount", defaultAmount); return serialised; } public static CurrencyImpl deserialize(Map<String, Object> serialised) { CurrencyImpl deserialised = new CurrencyImpl(); deserialised.name = (String) serialised.get("name"); deserialised.nameSingular = (String) serialised.get("name-singular"); deserialised.namePlural = (String) serialised.get("name-plural"); deserialised.rate = (int) serialised.get("rate"); deserialised.defaultAmount = (int) serialised.get("default-amount"); return deserialised; } }
agpl-3.0
bitblit11/yamcs
yamcs-simulation/src/main/java/org/yamcs/simulation/generated/PpSimulation.java
18895
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2014.06.02 at 02:49:47 PM CEST // package org.yamcs.simulation.generated; import java.math.BigDecimal; import java.util.ArrayList; import java.util.List; 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.XmlRootElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; import javax.xml.datatype.XMLGregorianCalendar; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;element name="description" type="{http://www.w3.org/2001/XMLSchema}string"/&gt; * &lt;element name="parameterSequence" maxOccurs="unbounded"&gt; * &lt;complexType&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;element name="parameter" maxOccurs="unbounded"&gt; * &lt;complexType&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;attribute name="spaceSystem" type="{http://www.w3.org/2001/XMLSchema}string" /&gt; * &lt;attribute name="paraName" type="{http://www.w3.org/2001/XMLSchema}string" /&gt; * &lt;attribute name="valueType" type="{http://www.w3.org/2001/XMLSchema}string" /&gt; * &lt;attribute name="value" type="{http://www.w3.org/2001/XMLSchema}decimal" /&gt; * &lt;attribute name="monitoringResult" type="{http://www.w3.org/2001/XMLSchema}string" /&gt; * &lt;attribute name="generationStep" type="{http://www.w3.org/2001/XMLSchema}int" /&gt; * &lt;attribute name="aquisitionStep" type="{http://www.w3.org/2001/XMLSchema}int" /&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * &lt;/element&gt; * &lt;/sequence&gt; * &lt;attribute name="repeat" type="{http://www.w3.org/2001/XMLSchema}int" /&gt; * &lt;attribute name="loop" type="{http://www.w3.org/2001/XMLSchema}boolean" /&gt; * &lt;attribute name="stepOffset" type="{http://www.w3.org/2001/XMLSchema}int" /&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * &lt;/element&gt; * &lt;/sequence&gt; * &lt;attribute name="startDate" type="{http://www.w3.org/2001/XMLSchema}dateTime" /&gt; * &lt;attribute name="stepLengthMs" type="{http://www.w3.org/2001/XMLSchema}int" /&gt; * &lt;attribute name="loop" type="{http://www.w3.org/2001/XMLSchema}boolean" /&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "description", "parameterSequence" }) @XmlRootElement(name = "ppSimulation") public class PpSimulation { @XmlElement(required = true) protected String description; @XmlElement(required = true) protected List<PpSimulation.ParameterSequence> parameterSequence; @XmlAttribute(name = "startDate") @XmlSchemaType(name = "dateTime") protected XMLGregorianCalendar startDate; @XmlAttribute(name = "stepLengthMs") protected Integer stepLengthMs; @XmlAttribute(name = "loop") protected Boolean loop; /** * Gets the value of the description property. * * @return * possible object is * {@link String } * */ public String getDescription() { return description; } /** * Sets the value of the description property. * * @param value * allowed object is * {@link String } * */ public void setDescription(String value) { this.description = value; } /** * Gets the value of the parameterSequence property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the parameterSequence property. * * <p> * For example, to add a new item, do as follows: * <pre> * getParameterSequence().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link PpSimulation.ParameterSequence } * * */ public List<PpSimulation.ParameterSequence> getParameterSequence() { if (parameterSequence == null) { parameterSequence = new ArrayList<PpSimulation.ParameterSequence>(); } return this.parameterSequence; } /** * Gets the value of the startDate property. * * @return * possible object is * {@link XMLGregorianCalendar } * */ public XMLGregorianCalendar getStartDate() { return startDate; } /** * Sets the value of the startDate property. * * @param value * allowed object is * {@link XMLGregorianCalendar } * */ public void setStartDate(XMLGregorianCalendar value) { this.startDate = value; } /** * Gets the value of the stepLengthMs property. * * @return * possible object is * {@link Integer } * */ public Integer getStepLengthMs() { return stepLengthMs; } /** * Sets the value of the stepLengthMs property. * * @param value * allowed object is * {@link Integer } * */ public void setStepLengthMs(Integer value) { this.stepLengthMs = value; } /** * Gets the value of the loop property. * * @return * possible object is * {@link Boolean } * */ public Boolean isLoop() { return loop; } /** * Sets the value of the loop property. * * @param value * allowed object is * {@link Boolean } * */ public void setLoop(Boolean value) { this.loop = value; } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;sequence&gt; * &lt;element name="parameter" maxOccurs="unbounded"&gt; * &lt;complexType&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;attribute name="spaceSystem" type="{http://www.w3.org/2001/XMLSchema}string" /&gt; * &lt;attribute name="paraName" type="{http://www.w3.org/2001/XMLSchema}string" /&gt; * &lt;attribute name="valueType" type="{http://www.w3.org/2001/XMLSchema}string" /&gt; * &lt;attribute name="value" type="{http://www.w3.org/2001/XMLSchema}decimal" /&gt; * &lt;attribute name="monitoringResult" type="{http://www.w3.org/2001/XMLSchema}string" /&gt; * &lt;attribute name="generationStep" type="{http://www.w3.org/2001/XMLSchema}int" /&gt; * &lt;attribute name="aquisitionStep" type="{http://www.w3.org/2001/XMLSchema}int" /&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * &lt;/element&gt; * &lt;/sequence&gt; * &lt;attribute name="repeat" type="{http://www.w3.org/2001/XMLSchema}int" /&gt; * &lt;attribute name="loop" type="{http://www.w3.org/2001/XMLSchema}boolean" /&gt; * &lt;attribute name="stepOffset" type="{http://www.w3.org/2001/XMLSchema}int" /&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "parameter" }) public static class ParameterSequence { @XmlElement(required = true) protected List<PpSimulation.ParameterSequence.Parameter> parameter; @XmlAttribute(name = "repeat") protected Integer repeat; @XmlAttribute(name = "loop") protected Boolean loop; @XmlAttribute(name = "stepOffset") protected Integer stepOffset; /** * Gets the value of the parameter property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the parameter property. * * <p> * For example, to add a new item, do as follows: * <pre> * getParameter().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link PpSimulation.ParameterSequence.Parameter } * * */ public List<PpSimulation.ParameterSequence.Parameter> getParameter() { if (parameter == null) { parameter = new ArrayList<PpSimulation.ParameterSequence.Parameter>(); } return this.parameter; } /** * Gets the value of the repeat property. * * @return * possible object is * {@link Integer } * */ public Integer getRepeat() { return repeat; } /** * Sets the value of the repeat property. * * @param value * allowed object is * {@link Integer } * */ public void setRepeat(Integer value) { this.repeat = value; } /** * Gets the value of the loop property. * * @return * possible object is * {@link Boolean } * */ public Boolean isLoop() { return loop; } /** * Sets the value of the loop property. * * @param value * allowed object is * {@link Boolean } * */ public void setLoop(Boolean value) { this.loop = value; } /** * Gets the value of the stepOffset property. * * @return * possible object is * {@link Integer } * */ public Integer getStepOffset() { return stepOffset; } /** * Sets the value of the stepOffset property. * * @param value * allowed object is * {@link Integer } * */ public void setStepOffset(Integer value) { this.stepOffset = value; } /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType&gt; * &lt;complexContent&gt; * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"&gt; * &lt;attribute name="spaceSystem" type="{http://www.w3.org/2001/XMLSchema}string" /&gt; * &lt;attribute name="paraName" type="{http://www.w3.org/2001/XMLSchema}string" /&gt; * &lt;attribute name="valueType" type="{http://www.w3.org/2001/XMLSchema}string" /&gt; * &lt;attribute name="value" type="{http://www.w3.org/2001/XMLSchema}decimal" /&gt; * &lt;attribute name="monitoringResult" type="{http://www.w3.org/2001/XMLSchema}string" /&gt; * &lt;attribute name="generationStep" type="{http://www.w3.org/2001/XMLSchema}int" /&gt; * &lt;attribute name="aquisitionStep" type="{http://www.w3.org/2001/XMLSchema}int" /&gt; * &lt;/restriction&gt; * &lt;/complexContent&gt; * &lt;/complexType&gt; * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "") public static class Parameter { @XmlAttribute(name = "spaceSystem") protected String spaceSystem; @XmlAttribute(name = "paraName") protected String paraName; @XmlAttribute(name = "valueType") protected String valueType; @XmlAttribute(name = "value") protected BigDecimal value; @XmlAttribute(name = "monitoringResult") protected String monitoringResult; @XmlAttribute(name = "generationStep") protected Integer generationStep; @XmlAttribute(name = "aquisitionStep") protected Integer aquisitionStep; /** * Gets the value of the spaceSystem property. * * @return * possible object is * {@link String } * */ public String getSpaceSystem() { return spaceSystem; } /** * Sets the value of the spaceSystem property. * * @param value * allowed object is * {@link String } * */ public void setSpaceSystem(String value) { this.spaceSystem = value; } /** * Gets the value of the paraName property. * * @return * possible object is * {@link String } * */ public String getParaName() { return paraName; } /** * Sets the value of the paraName property. * * @param value * allowed object is * {@link String } * */ public void setParaName(String value) { this.paraName = value; } /** * Gets the value of the valueType property. * * @return * possible object is * {@link String } * */ public String getValueType() { return valueType; } /** * Sets the value of the valueType property. * * @param value * allowed object is * {@link String } * */ public void setValueType(String value) { this.valueType = value; } /** * Gets the value of the value property. * * @return * possible object is * {@link BigDecimal } * */ public BigDecimal getValue() { return value; } /** * Sets the value of the value property. * * @param value * allowed object is * {@link BigDecimal } * */ public void setValue(BigDecimal value) { this.value = value; } /** * Gets the value of the monitoringResult property. * * @return * possible object is * {@link String } * */ public String getMonitoringResult() { return monitoringResult; } /** * Sets the value of the monitoringResult property. * * @param value * allowed object is * {@link String } * */ public void setMonitoringResult(String value) { this.monitoringResult = value; } /** * Gets the value of the generationStep property. * * @return * possible object is * {@link Integer } * */ public Integer getGenerationStep() { return generationStep; } /** * Sets the value of the generationStep property. * * @param value * allowed object is * {@link Integer } * */ public void setGenerationStep(Integer value) { this.generationStep = value; } /** * Gets the value of the aquisitionStep property. * * @return * possible object is * {@link Integer } * */ public Integer getAquisitionStep() { return aquisitionStep; } /** * Sets the value of the aquisitionStep property. * * @param value * allowed object is * {@link Integer } * */ public void setAquisitionStep(Integer value) { this.aquisitionStep = value; } } } }
agpl-3.0
Tesora/tesora-dve-pub
tesora-dve-core/src/main/java/com/tesora/dve/sql/raw/jaxb/DynamicPersistentGroupType.java
2995
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.4-2 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2014.11.23 at 04:49:45 PM EST // package com.tesora.dve.sql.raw.jaxb; /* * #%L * Tesora Inc. * Database Virtualization Engine * %% * Copyright (C) 2011 - 2014 Tesora Inc. * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License, version 3, * as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU 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/>. * #L% */ import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for DynamicPersistentGroupType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="DynamicPersistentGroupType"> * &lt;complexContent> * &lt;extension base="{}GroupType"> * &lt;attribute name="sites" use="required" type="{http://www.w3.org/2001/XMLSchema}int" /> * &lt;attribute name="persistentgroup" use="required" type="{http://www.w3.org/2001/XMLSchema}string" /> * &lt;/extension> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "DynamicPersistentGroupType") public class DynamicPersistentGroupType extends GroupType { @XmlAttribute(name = "sites", required = true) protected int sites; @XmlAttribute(name = "persistentgroup", required = true) protected String persistentgroup; /** * Gets the value of the sites property. * */ public int getSites() { return sites; } /** * Sets the value of the sites property. * */ public void setSites(int value) { this.sites = value; } /** * Gets the value of the persistentgroup property. * * @return * possible object is * {@link String } * */ public String getPersistentgroup() { return persistentgroup; } /** * Sets the value of the persistentgroup property. * * @param value * allowed object is * {@link String } * */ public void setPersistentgroup(String value) { this.persistentgroup = value; } }
agpl-3.0
moparisthebest/MoparScape
servers/server508/src/main/java/DavidScape/world/items/Items.java
14654
package DavidScape.world.items; import DavidScape.Engine; import DavidScape.io.Frames; import DavidScape.players.Player; import DavidScape.util.Misc; import java.io.BufferedReader; import java.io.FileReader; public class Items { public int maxItemAmount = 999999999; public int maxBankSize = 352; public int maxListedItems = 15000; public ItemList[] itemLists = new ItemList[maxListedItems]; public GroundItem[] groundItems = new GroundItem[1000]; private int untradable[] = {6570}; private Engine engine; private Frames frames; private BankUtils bu = new BankUtils(); /** * Constructs a new Items class. * * @param game The engine to get data from. */ public Items(Engine game) { engine = game; frames = engine.frames; loadItemList(); loadItemLists(); } /** * Checks if an item is tradable or not. * * @param The item to check. * @return Returns if the itemId is tradable. */ public boolean isUntradable(int item) { for (int i = 0; i < untradable.length; i++) { if (untradable[i] == item) { return true; } } return false; } /** * This method is called every 600 milliseconds. */ public void process() { for (GroundItem g : groundItems) { if (g == null) { continue; } else if (g.itemId > -1 && g.itemAmt > 0) { g.itemGroundTime--; if (g.itemGroundTime == 60) { if (!isUntradable(g.itemId) && !g.itemDroppedBy.equals("")) { frames.removeGroundItem( engine.players[engine.getIdFromName(g.itemDroppedBy)], g.itemId, g.itemX, g.itemY, g.itemHeight); createGlobalItem(g.itemId, g.itemAmt, g.itemX, g.itemY, g.itemHeight); } } else if (g.itemGroundTime <= 0) { if (isUntradable(g.itemId)) { frames.removeGroundItem( engine.players[engine.getIdFromName(g.itemDroppedBy)], g.itemId, g.itemX, g.itemY, g.itemHeight); } else { removeGlobalItem(g.itemId, g.itemX, g.itemY, g.itemHeight); } discardItem(g); } } else if (g.itemId < 0) { discardItem(g); } else if (g.itemAmt <= 0) { discardItem(g); } } } /** * Remove a ground item. * * @param g The ground item to discard. */ public void discardItem(GroundItem g) { groundItems[g.index] = null; } /** * Removes an item for everyone within distance. */ public void removeGlobalItem(int id, int x, int y, int height) { if (id < 0 || id >= maxListedItems) { return; } for (Player p : engine.players) { if (p == null) { continue; } frames.removeGroundItem(p, id, x, y, height); } } /** * Creates an item on the ground for everyone within distance. */ public void createGlobalItem(int id, int amt, int x, int y, int height) { if (id < 0 || amt < 0 || id >= maxListedItems) { return; } for (Player p : engine.players) { if (p == null) { continue; } frames.createGroundItem(p, id, amt, x, y, height); } } /** * Creates a new ground item. */ public void createGroundItem(int id, int amt, int x, int y, int height, String owner) { if (id < 0 || amt < 0 || id >= maxListedItems) { return; } if (id >= 9747 && id <= 9814 || id >= 9848 && id <= 9950 || id >= 12169 && id <= 12171)//Skill Capes don't show up on the ground so no one can loot. { return; } /* * Set the owner to "" for an item everyone can see. */ int index = -1; for (int i = 0; i < groundItems.length; i++) { if (groundItems[i] == null) { index = i; break; } } if (index == -1) { Misc.println("Max number of items spawned."); return; } groundItems[index] = new GroundItem(index, id, amt, x, y, height, owner); if (groundItems[index].itemDroppedBy.equals("")) { createGlobalItem(id, amt, x, y, height); } else { frames.createGroundItem(engine.players[engine.getIdFromName(owner)], id, amt, x, y, height); } } /** * Checks if an item exists at the params. * * @param itemId The item id to look for. * @param itemX The x coordinate to look for the item. * @param itemY The y coordinate to look for the item. * @param height The height level to look for the item. * @return Returns the ground item index, or -1 if the item isnt found. */ public int itemExists(int itemId, int itemX, int itemY, int height) { if (itemId < 0 || itemId >= maxListedItems) { return -1; } for (GroundItem g : groundItems) { if (g == null) { continue; } if (g.itemId == itemId && g.itemX == itemX && g.itemY == itemY && g.itemHeight == height) { return g.index; } } return -1; } /** * Finds an item at the params and removes it. * * @param itemId The item id to look for. * @param itemX The x coordinate of the item. * @param itemY The y coordinate of the item. * @param height The height level of the item. * @param Returns true if the item was successfully found and removed. */ public boolean itemPickedup(int itemId, int itemX, int itemY, int height) { if (itemId < 0 || itemId >= maxListedItems) { return false; } int amt = 0; for (GroundItem g : groundItems) { if (g == null) { continue; } if (g.itemId == itemId && g.itemX == itemX && g.itemY == itemY && g.itemHeight == height) { amt = g.itemAmt; if ((g.itemGroundTime <= 60 || g.itemDroppedBy.equals("")) && !isUntradable(g.itemId)) { removeGlobalItem(g.itemId, g.itemX, g.itemY, g.itemHeight); } else { frames.removeGroundItem( engine.players[engine.getIdFromName(g.itemDroppedBy)], g.itemId, g.itemX, g.itemY, g.itemHeight); } discardItem(g); return true; } } return false; } /** * Loads other item lists. */ private void loadItemLists() { int itemId = -1, counter = 0; String name = null; try { BufferedReader in = new BufferedReader( new FileReader(DavidScape.Server.workingDir + "data/items/stackable.dat")); while ((name = in.readLine()) != null) { itemId = Integer.parseInt(name); if (itemId != -1) { if (itemLists[itemId] != null) { itemLists[itemId].itemStackable = true; } } } in.close(); in = null; } catch (Exception e) { Misc.println("Error loading stackable list."); } try { BufferedReader in = new BufferedReader( new FileReader(DavidScape.Server.workingDir + "data/items/equipment.dat")); while ((name = in.readLine()) != null) { itemId = Integer.parseInt(name.substring(0, name.indexOf(":"))); int equipId = Integer.parseInt( name.substring(name.indexOf(":") + 1)); if (itemLists[itemId] != null) { itemLists[itemId].equipId = equipId; } } in.close(); in = null; } catch (Exception e) { Misc.println("Error loading equipment list."); } } /** * Returns if the itemId is stackable. */ public boolean notedAndStackable(int itemId) { String itemName = getItemName(itemId); String item2Name = getItemName(itemId - 1); if (itemName.startsWith(item2Name) && itemName.endsWith(item2Name)) { itemLists[itemId].itemStackable = true; return true; } return false; } public boolean stackable(int itemId) { if (itemId < 0 || itemId >= maxListedItems || itemLists[itemId] == null) { return false; } if (bu.isNote(itemId)) { return true; } if (itemLists[itemId] != null) { return (itemLists[itemId].itemStackable); } return false; } /** * Returns if the itemId is noted. */ public boolean noted(int itemId) { if (itemId < 0 || itemId >= maxListedItems) { return false; } if (itemLists[itemId] != null) { return (itemLists[itemId].itemIsNote); } return false; } /** * Returns the name of itemId. */ public String getItemName(int itemId) { if (itemId == -1 || itemId >= maxListedItems) { return new String("Unarmed"); } if (itemLists[itemId] != null) { return (itemLists[itemId].itemName); } return new String("Item " + itemId); } public int getIdFromName(String itemName) { for (int i = 0; i <= maxListedItems; i++) { if (itemLists[i] == null) { return -1; } if (itemLists[i].itemName.toLowerCase() == itemName.toLowerCase()) { return i; } } return -1; } /** * Returns the equipment mask of itemId. */ public int getEquipId(int itemId) { if (itemId < 0 || itemId >= maxListedItems) { return 0; } if (itemLists[itemId] != null) { return (itemLists[itemId].equipId); } return 0; } /** * Returns the description of itemId. */ public String getItemDescription(int itemId) { if (itemId == -1 || itemId >= maxListedItems) { return new String("An item."); } if (itemLists[itemId] != null) { return (itemLists[itemId].itemDescription); } return new String("Item " + itemId); } /** * Returns the value of itemId. */ public int getItemValue(int itemId) { if (itemId < 0 || itemId >= maxListedItems) { return 0; } if (itemLists[itemId] != null) { return (itemLists[itemId].lowAlch); } return 1; } /** * Load item data from a file. */ private boolean loadItemList() { String line = "", token = "", token2 = "", token2_2 = "", token3[] = new String[10]; BufferedReader list = null; try { list = new BufferedReader(new FileReader(DavidScape.Server.workingDir + "data/items/items.cfg")); line = list.readLine().trim(); } catch (Exception e) { Misc.println("Error loading item list."); return false; } while (line != null) { int spot = line.indexOf("="); if (spot > -1) { token = line.substring(0, spot).trim(); token2 = line.substring(spot + 1).trim(); token2_2 = token2.replaceAll("\t\t", "\t"); token2_2 = token2_2.replaceAll("\t\t", "\t"); token2_2 = token2_2.replaceAll("\t\t", "\t"); token3 = token2_2.split("\t"); if (token.equals("item")) { int[] bonuses = new int[12]; for (int i = 0; i < 12; i++) { if (token3[(6 + i)] != null) { bonuses[i] = Integer.parseInt(token3[(6 + i)]); } else { break; } } newItemList(Integer.parseInt(token3[0]), token3[1].replaceAll("_", " "), token3[2].replaceAll("_", " "), Integer.parseInt(token3[3]), Integer.parseInt(token3[4]), Integer.parseInt(token3[6]), bonuses); } } else { if (line.equals("[ENDOFITEMLIST]")) { try { list.close(); } catch (Exception exception) { } list = null; return true; } } try { line = list.readLine().trim(); } catch (Exception exception1) { try { list.close(); } catch (Exception exception) { } list = null; return true; } } return false; } /** * Sets a new item list. */ private void newItemList(int ItemId, String ItemName, String ItemDescription, int ShopValue, int LowAlch, int HighAlch, int Bonuses[]) { if (ItemId > maxListedItems) { Misc.println("maxListedItems to low."); return; } itemLists[ItemId] = new ItemList(ItemId, ItemName, ItemDescription, ShopValue, LowAlch, Bonuses); } }
agpl-3.0
opensourceBIM/bimql
BimQL/src/nl/wietmazairac/bimql/set/attribute/SetAttributeSubIfcPreDefinedSymbol.java
1925
package nl.wietmazairac.bimql.set.attribute; /****************************************************************************** * Copyright (C) 2009-2017 BIMserver.org * * 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 {@literal<http://www.gnu.org/licenses/>}. *****************************************************************************/ public class SetAttributeSubIfcPreDefinedSymbol { // fields private Object object; private String attributeName; private String attributeNewValue; // constructors public SetAttributeSubIfcPreDefinedSymbol() { } public SetAttributeSubIfcPreDefinedSymbol(Object object, String attributeName, String attributeNewValue) { this.object = object; this.attributeName = attributeName; this.attributeNewValue = attributeNewValue; } // methods public Object getObject() { return object; } public void setObject(Object object) { this.object = object; } public String getAttributeName() { return attributeName; } public void setAttributeName(String attributeName) { this.attributeName = attributeName; } public String getAttributeNewValue() { return attributeNewValue; } public void setAttributeNewValue(String attributeNewValue) { this.attributeNewValue = attributeNewValue; } public void setAttribute() { } }
agpl-3.0
ungerik/ephesoft
Ephesoft_Community_Release_4.0.2.0/source/dcma-util/src/main/java/com/ephesoft/dcma/util/EphesoftStringUtil.java
14606
/********************************************************************************* * Ephesoft is a Intelligent Document Capture and Mailroom Automation program * developed by Ephesoft, Inc. Copyright (C) 2015 Ephesoft Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by the * Free Software Foundation with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY EPHESOFT, EPHESOFT DISCLAIMS THE WARRANTY * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * 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 or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. * * You can contact Ephesoft, Inc. headquarters at 111 Academy Way, * Irvine, CA 92617, USA. or at email address info@ephesoft.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License version 3, * these Appropriate Legal Notices must retain the display of the "Ephesoft" logo. * If the display of the logo is not reasonably feasible for * technical reasons, the Appropriate Legal Notices must display the words * "Powered by Ephesoft". ********************************************************************************/ package com.ephesoft.dcma.util; import java.io.UnsupportedEncodingException; import java.net.URLDecoder; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Arrays; import java.util.Collection; import java.util.List; import java.util.regex.Pattern; import org.apache.commons.codec.DecoderException; import org.apache.commons.codec.binary.Hex; import org.apache.commons.lang3.StringUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.ephesoft.dcma.util.exception.HexDecoderException; /** * Performs methods like concatenate, encode, split, null check, etc. on strings. * * @author Ephesoft <b>created on</b> 18-Jun-2013 <br/> * @version 1.0 $LastChangedDate: 2014-04-21 09:56:23 +0530 (Mon, 21 Apr 2014) $ <br/> * $LastChangedRevision: 10919 $ <br/> */ public final class EphesoftStringUtil { /** * String constant for char encoder. */ private static final String CHAR_ENCODER = "UTF-8"; /** * String constant for plus character. */ private static final String CHARACTER_PLUS = "+"; /** * String constant for encoded value for Plus character. */ private static final String ENCODED_PLUS = "%20"; /** * Initialising logger {@link Logger}. */ private static final Logger LOGGER = LoggerFactory.getLogger(EphesoftStringUtil.class); /** * String constant for single comma delimiter. */ private static final String DELIMITER = ","; /** * String constant for true */ private static final String TRUE = "true"; /** * String constant for false */ private static final String FALSE = "false"; /** * Constructor. */ private EphesoftStringUtil() { super(); } /** * Returns encoded value for a string. * * @param toEncodeString {@link String} the string to be encoded. * @return {@link String} Encoded String, null if toEncodeString is null. */ public static String getEncodedString(final String toEncodeString) { String encodedString = null; if (null != toEncodeString) { try { encodedString = URLEncoder.encode(toEncodeString, CHAR_ENCODER); } catch (final UnsupportedEncodingException encodingException) { LOGGER.error(concatenate(toEncodeString, "could not be encoded. ", CHAR_ENCODER, " encoding is not supported : ", encodingException)); } } return encodedString; } /** * Returns decoded value for a string. * * @param toDecodeString {@link String} the string to be decoded. * @return {@link String} Decoded String, null if toDecodeString is null. */ public static String getDecodedString(final String toDecodeString) { String decodedString = null; if (null != toDecodeString) { try { decodedString = URLDecoder.decode(toDecodeString, CHAR_ENCODER); } catch (final UnsupportedEncodingException encodingException) { LOGGER.error(concatenate(toDecodeString, "could not be decoded. ", CHAR_ENCODER, " decoding is not supported : ", encodingException)); } } return decodedString; } /** * Splits input string by comma delimiter. * * @param inputString {@link String} string to split * @return {@link List<{@link String}>} List of strings, null if inputString is null/empty. */ public static List<String> convertDelimitedStringToList(final String inputString) { List<String> listOfTokens = null; if (!isNullOrEmpty(inputString)) { final String[] stringArray = inputString.split(DELIMITER); listOfTokens = new ArrayList<String>(stringArray.length); if (stringArray.length > 0) { listOfTokens = Arrays.asList(stringArray); } } return listOfTokens; } /** * Splits the string passed on the basis of sub String length and returns the array of strings computed by splitting this string. * * @param inputString {@link String} The string to split. * @param subStringLength {@link String} The length of the subString. * @return {@link String[]} The array of strings computed by splitting this string, null if inputString is null/empty or * subStringLength is <=0. */ public static String[] splitString(final String inputString, final int subStringLength) { String[] chunks = null; if (!isNullOrEmpty(inputString) && subStringLength > 0) { final int stringLength = inputString.length(); final int fullChunks = stringLength / subStringLength; boolean lastChunkEmpty = false; if (stringLength % subStringLength == 0) { lastChunkEmpty = true; } int size = fullChunks; if (!lastChunkEmpty) { size++; } chunks = new String[size]; int num = 0; for (num = 0; num < fullChunks; num++) { chunks[num] = inputString.substring(num * subStringLength, num * subStringLength + subStringLength); } if (!lastChunkEmpty) { chunks[num] = inputString.substring(num * subStringLength, stringLength); } } return chunks; } /** * Concatenates a number of objects together in the form of a String. * * @param objects {@link Object} Objects for concatenation to form a String. * @return {@link String} concatenated string, null if objects is null. */ public static String concatenate(final Object... objects) { String concatenatedString = null; if (null != objects) { StringBuilder concatenatedStringBuilder = null; for (final Object object : objects) { if (null == concatenatedStringBuilder) { concatenatedStringBuilder = new StringBuilder(); } if (null != object) { concatenatedStringBuilder.append(object); } } concatenatedString = concatenatedStringBuilder.toString(); } return concatenatedString; } /** * Concatenates a number of Strings together in the form of a String. * * @param strings {@link String} Strings for concatenation. * @return {@link String} concatenated string, null if strings is null. */ public static String concatenate(final String... strings) { String concatenatedString = null; if (null != strings) { StringBuilder concatenatedStringBuilder = null; for (final String string : strings) { if (null == concatenatedStringBuilder) { concatenatedStringBuilder = new StringBuilder(); } if (null != string) { concatenatedStringBuilder.append(string); } } concatenatedString = concatenatedStringBuilder.toString(); } return concatenatedString; } /** * Encodes a string using URLEncoder. * * @param inputString {@link String} the string for encoding. * @return {@link String} Encoded String, null if encoding fails due to inputString being empty/null or encoder not able to encode. */ public static String encode(final String inputString) { String encodedString = getEncodedString(inputString); if (null == encodedString) { encodedString = inputString; } else { encodedString = encodedString.replace(CHARACTER_PLUS, ENCODED_PLUS); } return encodedString; } /** * Checks if a string is null or empty. * * @param paramToCheck {@link String} String to check for empty or null * @return boolean, true if paramToCheck is null or empty. */ public static boolean isNullOrEmpty(final String paramToCheck) { return (null == paramToCheck || paramToCheck.isEmpty()); } /** * Returns array of string separated by the given split pattern. In case the split pattern is empty, then the input string will be * split character-wise. * * @param inputString {@link String} the input string that is to be split. * @param splitPattern {@link String} the parameter on which input string should be split. * @return {@link String[]} The array of strings computed by splitting this string, null if inputString being empty/null or * splitPattern is null. */ public static String[] splitString(final String inputString, final String splitPattern) { String[] tokens = null; if (!isNullOrEmpty(inputString) && null != splitPattern) { final Pattern pattern = Pattern.compile(splitPattern); tokens = pattern.split(inputString); } return tokens; } /** * Checks if the input string is valid boolean value i.e. is <b>TRUE</b> or <b>FALSE</b> * * @param value {@link String} is the string provided * @return <b>TRUE</b> if is a valid boolean value and <b>FALSE</b> if not */ public static boolean isValidBooleanValue(final String value) { boolean isValidBooleanValue = false; if ((!isNullOrEmpty(value)) && (value.equalsIgnoreCase(TRUE) || value.equalsIgnoreCase(FALSE))) { isValidBooleanValue = true; } return isValidBooleanValue; } /** * Checks case insensitively if toBeChecked parameter is contained in original string or not. * * @param original {@link String} * @param toBeChecked {@link String} * @return boolean True if toBeChecked string is contained in original string when checked with case insensitivity. */ public static boolean containsIgnoreCase(final String original, final String toBeChecked) { boolean doesContain; if (null != original && null != toBeChecked) { doesContain = StringUtils.containsIgnoreCase(original, toBeChecked); } else { doesContain = false; } return doesContain; } /** * Joins the collection values passed as a parameter separated by the delimiter passed as a parameter. * * @param collection {@link Collection} collection whose values needs to be joined. * @param separator delimiter to be used as a separator between values. * @return {@link String} joined string. */ public static <E> String join(final Collection<E> collection, final char separator) { String joinString = null; if (!CollectionUtil.isEmpty(collection) && 0 != separator) { joinString = StringUtils.join(collection.toArray(), separator); } return joinString; } /** * Encodes the String value to its corresponding Hex representation. * * @param originalData byte[] data to be encoded. * @return {@link String} Hex representation of the String. */ public static String toHexString(final byte[] originalData) { String encodedString = null; if (originalData != null) { char[] encodedCharacters = Hex.encodeHex(originalData); encodedString = new String(encodedCharacters); } return encodedString; } /** * Decodes the hex String to its original String representation. * * @param hexString {@link String} encoded hex string representation of a String value. * @return {@link String} decoded String which is the UTF-8 representation of the Hex value. * @throws HexDecoderException when hex string is invalid and cannot be decoded to original String. */ public static byte[] decodeHexString(final String hexString) throws HexDecoderException { byte[] decodedValue = null; try { if (!isNullOrEmpty(hexString)) { decodedValue = Hex.decodeHex(hexString.toCharArray()); } } catch (DecoderException decoderException) { throw new HexDecoderException(concatenate("Could not decode the hexvalue ", hexString), decoderException); } return decodedValue; } /** * Concatenates the {@link List} of {@link String} using the separator. Final result is the concatenated list of Strings in each * separated by a <code>separator</code> * * @param objectsToConcatenate []{@link Object} of Strings to concatenate. * @param separator {@link String} separator to separate the two {@link String} in the final String. * @return {@link String} concatenated {@link String} each separated by the <code>separator</code>. */ public static String concatenateUsingSeperator(String separator, Object... objectsToConcatenate) { String concatenatedString = null; if (objectsToConcatenate != null && !isNullOrEmpty(separator)) { StringBuilder concatenationBuilder = new StringBuilder(); int listSize = objectsToConcatenate.length; for (int listIndex = 0; listIndex < listSize; listIndex++) { if (objectsToConcatenate[listIndex] != null) { concatenationBuilder.append(objectsToConcatenate[listIndex].toString()); if (listIndex != listSize - 1) { concatenationBuilder.append(separator); } } } concatenatedString = concatenationBuilder.toString(); } return concatenatedString; } /** * Replace if contains oldString with newString in String Builder object. * * @param builder String on which replacement needs to be performed. * @param oldString the old string pattern * @param newString the new string pattern */ public static void replaceIfContains(StringBuilder builder, final String oldString, final String newString) { String tempString = builder.toString(); if (tempString.contains(oldString)) { tempString = tempString.replaceAll(oldString, newString); builder = builder.replace(0, builder.length(), tempString); } } }
agpl-3.0
dhosa/yamcs
yamcs-xtce/src/main/java/org/yamcs/xtce/Parameter.java
1395
package org.yamcs.xtce; /** * A Parameter is a description of something that can have a value; it is not the value itself. */ public class Parameter extends NameDescription { private static final long serialVersionUID = 2L; ParameterType parameterType; DataSource dataSource; /** * This is used for recording; if the recordingGroup is not set, the subsystem name is used. * Currently it is only set for DaSS processed parameters for compatibility with the old recorder */ String recordingGroup = null; public Parameter(String name) { super(name); } public DataSource getDataSource() { return dataSource; } public void setDataSource(DataSource dataSource) { this.dataSource = dataSource; } public void setParameterType(ParameterType pm) { parameterType = pm; } public ParameterType getParameterType() { return parameterType; } public String getRecordingGroup() { if(recordingGroup == null) { return getSubsystemName(); } else { return recordingGroup; } } public void setRecordingGroup(String g) { this.recordingGroup = g; } @Override public String toString() { return "ParaName: " + this.getName() + " paraType:" + parameterType +" opsname: "+getOpsName(); } }
agpl-3.0
StratusLab/claudia
clotho/src/main/java/com/telefonica/claudia/slm/naming/DirectoryEntry.java
1367
/* * Claudia Project * http://claudia.morfeo-project.org * * (C) Copyright 2010 Telefonica Investigacion y Desarrollo * S.A.Unipersonal (Telefonica I+D) * * See CREDITS file for info about members and contributors. * * This program is free software; you can redistribute it and/or modify * it under the terms of the Affero GNU General Public License (AGPL) 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 Affero GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. * * If you want to use this software an plan to distribute a * proprietary application in any way, and you are not licensing and * distributing your source code under AGPL, you probably need to * purchase a commercial license of the product. Please contact * claudia-support@lists.morfeo-project.org for more information. */ package com.telefonica.claudia.slm.naming; public interface DirectoryEntry { public FQN getFQN(); }
agpl-3.0
kuzavas/ephesoft
dcma-da/src/main/java/com/ephesoft/dcma/docassembler/classification/DocumentClassification.java
3199
/********************************************************************************* * Ephesoft is a Intelligent Document Capture and Mailroom Automation program * developed by Ephesoft, Inc. Copyright (C) 2010-2012 Ephesoft Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by the * Free Software Foundation with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY EPHESOFT, EPHESOFT DISCLAIMS THE WARRANTY * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * 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 or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. * * You can contact Ephesoft, Inc. headquarters at 111 Academy Way, * Irvine, CA 92617, USA. or at email address info@ephesoft.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License version 3, * these Appropriate Legal Notices must retain the display of the "Ephesoft" logo. * If the display of the logo is not reasonably feasible for * technical reasons, the Appropriate Legal Notices must display the words * "Powered by Ephesoft". ********************************************************************************/ package com.ephesoft.dcma.docassembler.classification; import com.ephesoft.dcma.batch.service.PluginPropertiesService; import com.ephesoft.dcma.core.exception.DCMAApplicationException; import com.ephesoft.dcma.docassembler.DocumentAssembler; /** * This class does the actual processing of document assembly. It will read * all the pages of the document type Unknown and then create new documents for * all these pages found. * * @author Ephesoft * @version 1.0 * @see com.ephesoft.dcma.docassembler.DocumentAssembler */ public interface DocumentClassification { /** * This method will process all the unclassified pages present at document * type Unknown. Process every page one by one and create new documents. * * @param documentAssembler {@link DocumentAssembler} * @param batchInstanceIdentifier {@link String} * @param pluginPropertiesService {@link PluginPropertiesService} * @throws DCMAApplicationException {@link DCMAApplicationException} If any invalid parameter found. */ void processUnclassifiedPages(final DocumentAssembler documentAssembler, final String batchInstanceIdentifier, final PluginPropertiesService pluginPropertiesService) throws DCMAApplicationException; }
agpl-3.0
ratsam/loyalty-task
app/domain/src/main/java/com/loyaltyplant/test/repository/OperationRepository.java
524
package com.loyaltyplant.test.repository; import com.loyaltyplant.test.domain.operation.AbstractOperation; import org.springframework.data.jpa.repository.Modifying; import org.springframework.data.repository.RepositoryDefinition; /** * @author Maksim Zakharov * @since 1.0 */ @RepositoryDefinition(domainClass = AbstractOperation.class, idClass = Integer.class) public interface OperationRepository { @Modifying <T extends AbstractOperation> T save(T operation); AbstractOperation findById(Integer id); }
agpl-3.0
HiOA-ABI/nikita-noark5-core
src/main/java/nikita/webapp/web/controller/hateoas/metadata/CountryController.java
10528
package nikita.webapp.web.controller.hateoas.metadata; import com.codahale.metrics.annotation.Counted; import io.swagger.annotations.ApiOperation; import io.swagger.annotations.ApiParam; import io.swagger.annotations.ApiResponse; import io.swagger.annotations.ApiResponses; import nikita.common.config.Constants; import nikita.common.model.noark5.v4.hateoas.metadata.MetadataHateoas; import nikita.common.model.noark5.v4.metadata.Country; import nikita.common.util.CommonUtils; import nikita.common.util.exceptions.NikitaException; import nikita.webapp.service.interfaces.metadata.ICountryService; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.*; import javax.servlet.http.HttpServletRequest; import static nikita.common.config.Constants.*; import static nikita.common.config.N5ResourceMappings.*; import static org.springframework.http.HttpHeaders.ETAG; /** * Created by tsodring on 14/03/18. */ @RestController @RequestMapping( value = Constants.HATEOAS_API_PATH + SLASH + NOARK_METADATA_PATH + SLASH, produces = {NOARK5_V4_CONTENT_TYPE_JSON, NOARK5_V4_CONTENT_TYPE_JSON_XML}) @SuppressWarnings("unchecked") public class CountryController { private ICountryService countryService; public CountryController(ICountryService countryService) { this.countryService = countryService; } // API - All POST Requests (CRUD - CREATE) // Creates a new land // POST [contextPath][api]/metadata/land/ny-land @ApiOperation( value = "Persists a new Country object", notes = "Returns the newly created Country object after it " + "is persisted to the database", response = Country.class) @ApiResponses(value = { @ApiResponse( code = 200, message = "Country " + API_MESSAGE_OBJECT_ALREADY_PERSISTED, response = Country.class), @ApiResponse( code = 201, message = "Country " + API_MESSAGE_OBJECT_SUCCESSFULLY_CREATED, response = Country.class), @ApiResponse(code = 401, message = API_MESSAGE_UNAUTHENTICATED_USER), @ApiResponse( code = 403, message = API_MESSAGE_UNAUTHORISED_FOR_USER), @ApiResponse( code = 404, message = API_MESSAGE_MALFORMED_PAYLOAD), @ApiResponse( code = 409, message = API_MESSAGE_CONFLICT), @ApiResponse( code = 500, message = API_MESSAGE_INTERNAL_SERVER_ERROR)}) @Counted @RequestMapping( method = RequestMethod.POST, value = COUNTRY + SLASH + NEW_COUNTRY ) public ResponseEntity<MetadataHateoas> createCountry( HttpServletRequest request, @RequestBody Country country) throws NikitaException { MetadataHateoas metadataHateoas = countryService.createNewCountry(country); return ResponseEntity.status(HttpStatus.CREATED) .allow(CommonUtils.WebUtils. getMethodsForRequestOrThrow(request.getServletPath())) .eTag(metadataHateoas.getEntityVersion().toString()) .body(metadataHateoas); } // API - All GET Requests (CRUD - READ) // Retrieves all country // GET [contextPath][api]/metadata/land/ @ApiOperation( value = "Retrieves all Country ", response = Country.class) @ApiResponses(value = { @ApiResponse( code = 200, message = "Country codes found", response = Country.class), @ApiResponse( code = 404, message = "No Country found"), @ApiResponse( code = 401, message = API_MESSAGE_UNAUTHENTICATED_USER), @ApiResponse( code = 403, message = API_MESSAGE_UNAUTHORISED_FOR_USER), @ApiResponse( code = 500, message = API_MESSAGE_INTERNAL_SERVER_ERROR)}) @Counted @RequestMapping( method = RequestMethod.GET, value = COUNTRY ) public ResponseEntity<MetadataHateoas> findAll(HttpServletRequest request) { return ResponseEntity.status(HttpStatus.OK) .allow(CommonUtils.WebUtils. getMethodsForRequestOrThrow(request.getServletPath())) .body(countryService.findAll()); } // Retrieves a given country identified by a systemId // GET [contextPath][api]/metadata/land/{systemId}/ @ApiOperation( value = "Gets country identified by its systemId", notes = "Returns the requested country object", response = Country.class) @ApiResponses(value = { @ApiResponse( code = 200, message = "Country " + API_MESSAGE_OBJECT_ALREADY_PERSISTED, response = Country.class), @ApiResponse( code = 201, message = "Country " + API_MESSAGE_OBJECT_SUCCESSFULLY_CREATED, response = Country.class), @ApiResponse( code = 401, message = API_MESSAGE_UNAUTHENTICATED_USER), @ApiResponse( code = 403, message = API_MESSAGE_UNAUTHORISED_FOR_USER), @ApiResponse( code = 404, message = API_MESSAGE_MALFORMED_PAYLOAD), @ApiResponse( code = 409, message = API_MESSAGE_CONFLICT), @ApiResponse( code = 500, message = API_MESSAGE_INTERNAL_SERVER_ERROR)}) @Counted @RequestMapping( value = COUNTRY + SLASH + LEFT_PARENTHESIS + SYSTEM_ID + RIGHT_PARENTHESIS + SLASH, method = RequestMethod.GET ) public ResponseEntity<MetadataHateoas> findBySystemId( @PathVariable("systemID") final String systemId, HttpServletRequest request) { MetadataHateoas metadataHateoas = countryService.find(systemId); return ResponseEntity.status(HttpStatus.OK) .allow(CommonUtils.WebUtils. getMethodsForRequestOrThrow(request.getServletPath())) .eTag(metadataHateoas.getEntityVersion().toString()) .body(metadataHateoas); } // Create a suggested country(like a template) with default values // (nothing persisted) // GET [contextPath][api]/metadata/ny-land @ApiOperation( value = "Creates a suggested Country", response = Country.class) @ApiResponses(value = { @ApiResponse( code = 200, message = "Country codes found", response = Country.class), @ApiResponse( code = 404, message = "No Country found"), @ApiResponse( code = 401, message = API_MESSAGE_UNAUTHENTICATED_USER), @ApiResponse( code = 403, message = API_MESSAGE_UNAUTHORISED_FOR_USER), @ApiResponse( code = 500, message = API_MESSAGE_INTERNAL_SERVER_ERROR)}) @Counted @RequestMapping( method = RequestMethod.GET, value = NEW_COUNTRY ) public ResponseEntity<MetadataHateoas> generateDefaultCountry(HttpServletRequest request) { MetadataHateoas metadataHateoas = new MetadataHateoas (countryService.generateDefaultCountry()); return ResponseEntity.status(HttpStatus.OK) .allow(CommonUtils.WebUtils. getMethodsForRequestOrThrow(request.getServletPath())) .body(metadataHateoas); } // API - All PUT Requests (CRUD - UPDATE) // Update a land // PUT [contextPath][api]/metatdata/land/ @ApiOperation( value = "Updates a Country object", notes = "Returns the newly updated Country object after it " + "is persisted to the database", response = Country.class) @ApiResponses(value = { @ApiResponse( code = 200, message = "Country " + API_MESSAGE_OBJECT_ALREADY_PERSISTED, response = Country.class), @ApiResponse( code = 401, message = API_MESSAGE_UNAUTHENTICATED_USER), @ApiResponse( code = 403, message = API_MESSAGE_UNAUTHORISED_FOR_USER), @ApiResponse( code = 404, message = API_MESSAGE_MALFORMED_PAYLOAD), @ApiResponse( code = 409, message = API_MESSAGE_CONFLICT), @ApiResponse( code = 500, message = API_MESSAGE_INTERNAL_SERVER_ERROR)}) @Counted @RequestMapping( method = RequestMethod.PUT, value = COUNTRY + SLASH + COUNTRY ) public ResponseEntity<MetadataHateoas> updateCountry( @ApiParam(name = "systemID", value = "systemId of fonds to update.", required = true) @PathVariable("systemID") String systemID, @RequestBody Country country, HttpServletRequest request) { MetadataHateoas metadataHateoas = countryService.handleUpdate (systemID, CommonUtils.Validation.parseETAG( request.getHeader(ETAG)), country); return ResponseEntity.status(HttpStatus.OK) .allow(CommonUtils.WebUtils. getMethodsForRequestOrThrow(request.getServletPath())) .body(metadataHateoas); } }
agpl-3.0
matsjj/thundernetwork
thunder-core/src/main/java/network/thunder/core/communication/objects/messages/interfaces/helper/LNEventListener.java
1385
package network.thunder.core.communication.objects.messages.interfaces.helper; import network.thunder.core.communication.objects.messages.impl.message.gossip.objects.PubkeyIPObject; import network.thunder.core.communication.objects.subobjects.PaymentSecret; import network.thunder.core.database.objects.Channel; import network.thunder.core.database.objects.Payment; import network.thunder.core.database.objects.PaymentWrapper; import network.thunder.core.mesh.NodeClient; /** * Created by matsjerratsch on 08/02/2016. */ public abstract class LNEventListener { public void onConnectionOpened (NodeClient node) { onEvent(); } public void onConnectionClosed (NodeClient node) { onEvent(); } public void onChannelOpened (Channel channel) { onEvent(); } public void onChannelClosed (Channel channel) { onEvent(); } public void onReceivedIP (PubkeyIPObject ip) { onEvent(); } public void onPaymentRelayed (PaymentWrapper wrapper) { onEvent(); } public void onPaymentRefunded (Payment payment) { onEvent(); } public void onPaymentCompleted (PaymentSecret payment) { onEvent(); } public void onPaymentExchangeDone () { onEvent(); } public void onP2PDataReceived () { onEvent(); } public void onEvent () { } }
agpl-3.0
diqube/diqube
diqube-execution/src/main/java/org/diqube/execution/ColumnVersionBuiltHelper.java
4401
/** * diqube: Distributed Query Base. * * Copyright (C) 2015 Bastian Gloeckle * * This file is part of diqube. * * diqube 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/>. */ package org.diqube.execution; import java.util.Collection; import java.util.NavigableSet; import java.util.Set; import java.util.stream.Collectors; import org.diqube.execution.consumers.ColumnVersionBuiltConsumer; import org.diqube.execution.consumers.GenericConsumer; import org.diqube.executionenv.ExecutionEnvironment; import org.diqube.executionenv.querystats.QueryableColumnShard; /** * Helper class providing methods for handling row IDs when a {@link ColumnVersionBuiltConsumer} is in place. * * @author Bastian Gloeckle */ public class ColumnVersionBuiltHelper { /** * Finds those row IDs out of a set of row IDs whose values are all available in specific columns of an * {@link ExecutionEnvironment} and manages a set of row IDs that could not be processed yet. * * @param env * The {@link ExecutionEnvironment} that is queried for the rows that are available in the specified columns. * @param columns * The columns that should be checked in "env" for the availability of values for the given rowIds. * @param activeRowIds * The row IDs that should be worked on now as provided by any other input {@link GenericConsumer}. This set * will be adjusted accordingly. After this method returns, the activeRowIds will contain only row IDs that * are available in {@link ExecutionEnvironment}. It might contain any additional row IDs of the * notYetProcessedRowIds parameter object, as those row IDs were not processed yet, but it might be possible * to process them now as the corresponding rows became available in the {@link ExecutionEnvironment}. Those * row IDs that are added to activeRowIds from notYetProcessedRowIds are removed from the latter. * @param notYetProcessedRowIds * A set containing those row IDs that have not yet been processed. See details above. * @return The maximum row ID for which all columns contain values or -1 if not all columns are available in the given * env. */ public long publishActiveRowIds(ExecutionEnvironment env, Collection<String> columns, NavigableSet<Long> activeRowIds, NavigableSet<Long> notYetProcessedRowIds) { long maxRowId; Collection<QueryableColumnShard> cols = columns.stream().map(colName -> env.getColumnShard(colName)).collect(Collectors.toList()); if (cols.stream().anyMatch(col -> col == null)) { // at least one of the needed columns is not available at all yet. notYetProcessedRowIds.addAll(activeRowIds); activeRowIds.clear(); return -1L; } if (cols.stream().anyMatch(col -> env.getPureStandardColumnShard(col.getName()) != null)) { maxRowId = cols.stream().filter(col -> env.getPureStandardColumnShard(col.getName()) != null) .mapToLong(column -> column.getFirstRowId() + env.getPureStandardColumnShard(column.getName()).getNumberOfRowsInColumnShard() - 1) . // min().getAsLong(); } else // only ConstantColumnShards maxRowId = cols.iterator().next().getFirstRowId(); Set<Long> activeRowIdsNotAvailable = activeRowIds.tailSet(maxRowId, false); if (!activeRowIdsNotAvailable.isEmpty()) { notYetProcessedRowIds.addAll(activeRowIdsNotAvailable); activeRowIdsNotAvailable.clear(); } Set<Long> notYetProcessedAvailable = notYetProcessedRowIds.headSet(maxRowId, true); if (!notYetProcessedAvailable.isEmpty()) { activeRowIds.addAll(notYetProcessedAvailable); notYetProcessedAvailable.clear(); } return maxRowId; } }
agpl-3.0
geomajas/geomajas-project-client-gwt2
plugin/geocoder/geocoder/src/main/java/org/geomajas/gwt2/plugin/geocoder/client/event/SelectLocationHandler.java
1275
/* * This is part of Geomajas, a GIS framework, http://www.geomajas.org/. * * Copyright 2008-2015 Geosparc nv, http://www.geosparc.com/, Belgium. * * The program is available in open source according to the GNU Affero * General Public License. All contributions in this program are covered * by the Geomajas Contributors License Agreement. For full licensing * details, see LICENSE.txt in the project root. */ package org.geomajas.gwt2.plugin.geocoder.client.event; import org.geomajas.annotation.Api; import org.geomajas.annotation.UserImplemented; import com.google.gwt.event.shared.EventHandler; import com.google.gwt.event.shared.GwtEvent; /** * Handler for {@link SelectLocationEvent}. * * @author Joachim Van der Auwera * @author Pieter De Graef * @since 2.0.0 */ @Api(allMethods = true) @UserImplemented public interface SelectLocationHandler extends EventHandler { /** Event type. */ GwtEvent.Type<SelectLocationHandler> TYPE = new GwtEvent.Type<SelectLocationHandler>(); /** * Called when the location is selected either because the geocoder returned a match or because the user * chose one of the alternatives. * * @param event event, contains the location which is selected */ void onSelectLocation(SelectLocationEvent event); }
agpl-3.0
AlienQueen/HatchetHarry
src/main/java/org/alienlabs/hatchetharry/model/Counter.java
3797
package org.alienlabs.hatchetharry.model; import java.io.Serializable; import javax.persistence.CascadeType; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.FetchType; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.Index; import javax.persistence.JoinColumn; import javax.persistence.ManyToOne; import javax.persistence.Table; import org.hibernate.annotations.Cache; import org.hibernate.annotations.CacheConcurrencyStrategy; @Entity @Table(name = "Counter", indexes = { @Index(columnList = "card"), @Index(columnList = "token") }) @Cache(usage = CacheConcurrencyStrategy.NONSTRICT_READ_WRITE) public class Counter implements Serializable, Comparable<Counter> { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long counterId; @Column(name = "VERSION", length = 20) private String version; @Column private String counterName; @Column private Long numberOfCounters = 0L; @ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL, targetEntity = MagicCard.class) @JoinColumn(name = "card") private MagicCard card; @ManyToOne(fetch = FetchType.EAGER, cascade = CascadeType.ALL, targetEntity = Token.class) @JoinColumn(name = "token") private Token token; public String getCounterName() { return this.counterName; } public void setCounterName(final String _counterName) { this.counterName = _counterName; } public Long getNumberOfCounters() { return this.numberOfCounters; } public void setNumberOfCounters(final Long _numberOfCounters) { this.numberOfCounters = _numberOfCounters; } public MagicCard getCard() { return this.card; } public void setCard(final MagicCard _card) { this.card = _card; } public Long getId() { return this.counterId; } public void setId(final Long _id) { this.counterId = _id; } public Token getToken() { return this.token; } public void setToken(final Token _token) { this.token = _token; } public String getVersion() { return this.version; } public void setVersion(final String _version) { this.version = _version; } /** * This class defines a compareTo(...) method and doesn't inherit its * equals() method from java.lang.Object. Generally, the value of compareTo * should return zero if and only if equals returns true. If this is * violated, weird and unpredictable failures will occur in classes such as * PriorityQueue. In Java 5 the PriorityQueue.remove method uses the * compareTo method, while in Java 6 it uses the equals method. From the * JavaDoc for the compareTo method in the Comparable interface: It is * strongly recommended, but not strictly required that (x.compareTo(y)==0) * == (x.equals(y)). Generally speaking, any class that implements the * Comparable interface and violates this condition should clearly indicate * this fact. The recommended language is * "Note: this class has a natural ordering that is inconsistent with equals." */ @Override public int compareTo(final Counter c) { if (this.equals(c)) { return 0; } if (this.getCounterName().equals(c.getCounterName())) { return -1; } return this.getCounterName().compareTo(c.getCounterName()); } @Override public boolean equals(final Object o) { if (this == o) { return true; } if (!(o instanceof Counter)) { return false; } final Counter counter = (Counter)o; if (this.counterId != null ? !this.counterId.equals(counter.counterId) : counter.counterId != null) { return false; } return true; } @Override public int hashCode() { return this.counterId != null ? this.counterId.hashCode() : 0; } }
agpl-3.0
cehardin/crackle
crackle-api/src/main/java/org/crackle/Creator.java
1152
/** * This file is part of crackle-api. * * crackle-api 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. * * crackle-api 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 crackle-api. If not, see <http://www.gnu.org/licenses/>. */ package org.crackle; /** * A creator of actors. * * @author Chad Hardin */ @FunctionalInterface public interface Creator { /** * Creates an actor and returns its address. * * @param behavior The initial behavior of the actor * @return The address of the newly created actor, never null * @throws NullPointerException If the behavior is null */ Address create(Behavior<?> behavior) throws NullPointerException; }
agpl-3.0
Gildorym/GildorymAPI
src/com/gildorymrp/api/plugin/dungeon/GildorymDungeonPlugin.java
505
package com.gildorymrp.api.plugin.dungeon; import java.util.Collection; /** * Represents a dungeon plugin * @author Lucariatias * */ public interface GildorymDungeonPlugin { /** * Gets a collection containing the dungeons * * @return collection containing all dungeons */ public Collection<Dungeon> getDungeons(); /** * Gets a dungeon by name * * @param name the name of the dungeon * @return the dungeon with the given name */ public Dungeon getDungeon(String name); }
agpl-3.0
moparisthebest/MoparScape
clients/renamed508/src/main/java/Class106.java
4828
/* Class106 - Decompiled by JODE * Visit http://jode.sourceforge.net/ */ final class Class106 { static GameSocket aClass61_1800; static int anInt1801 = 1; static MutableString aClass100_1802; static int anInt1803; static double aDouble1804 = -1.0; static NodeCache aClass113_1805; static int packetSize; static int anInt1807; static int anInt1808; static int anInt1809; static MutableString aClass100_1810; static int[] anIntArray1811; static MutableString aClass100_1812; static final int[] method1651(int[] is, int i) { try { anInt1809++; if (i > -28) return null; if (is == null) return null; int[] is_0_ = new int[is.length]; Class39.method466(is, 0, is_0_, 0, is.length); return is_0_; } catch (RuntimeException runtimeexception) { throw Class107.getException(runtimeexception, "sf.A(" + (is != null ? "{...}" : "null") + ',' + i + ')'); } } static final int method1652(int i, boolean bool) { if (bool != false) method1653(30); anInt1807++; return 0xff & i; } public static void method1653(int i) { aClass61_1800 = null; aClass100_1810 = null; anIntArray1811 = null; if (i != 0) aClass61_1800 = null; aClass100_1802 = null; aClass113_1805 = null; aClass100_1812 = null; } static final void method1654(byte i) { int i_1_ = -62 / (-i / 39); anInt1808++; for (Class68_Sub20_Sub4 class68_sub20_sub4 = ((Class68_Sub20_Sub4) Widget.aClass16_886.method293((byte) 76)); class68_sub20_sub4 != null; class68_sub20_sub4 = ((Class68_Sub20_Sub4) Widget.aClass16_886.method290((byte) 10))) { Class1_Sub1 class1_sub1 = ((Class68_Sub20_Sub4) class68_sub20_sub4).aClass1_Sub1_4216; if (((Class1_Sub1) class1_sub1).anInt2424 != GameSocket.plane || (((Class1_Sub1) class1_sub1).anInt2410 < Class68_Sub3.loopCycle)) class68_sub20_sub4.unlink(); else if (Class68_Sub3.loopCycle >= ((Class1_Sub1) class1_sub1).anInt2395) { if (((Class1_Sub1) class1_sub1).anInt2419 > 0) { NPC class1_sub6_sub1 = (Class102.localNPCs[((Class1_Sub1) class1_sub1).anInt2419 - 1]); if (class1_sub6_sub1 != null && ((Character) class1_sub6_sub1).x >= 0 && ((Character) class1_sub6_sub1).x < 13312 && ((Character) class1_sub6_sub1).y >= 0 && ((Character) class1_sub6_sub1).y < 13312) class1_sub1.method64(((Character) class1_sub6_sub1).x, (byte) -8, ((Character) class1_sub6_sub1).y, (Player.fixZ(((Character) class1_sub6_sub1).x, ((Class1_Sub1) class1_sub1).anInt2424, ((Character) class1_sub6_sub1).y)) - ((Class1_Sub1) class1_sub1).anInt2422, Class68_Sub3.loopCycle); } if (((Class1_Sub1) class1_sub1).anInt2419 < 0) { int i_2_ = -1 - ((Class1_Sub1) class1_sub1).anInt2419; Player class1_sub6_sub2; if (Class68_Sub10.localPlayerInteractingEntity != i_2_) class1_sub6_sub2 = (Class68_Sub13_Sub4.localPlayers[i_2_]); else class1_sub6_sub2 = Class68_Sub7.localPlayer; if (class1_sub6_sub2 != null && ((Character) class1_sub6_sub2).x >= 0 && ((Character) class1_sub6_sub2).x < 13312 && ((Character) class1_sub6_sub2).y >= 0 && ((Character) class1_sub6_sub2).y < 13312) class1_sub1.method64(((Character) class1_sub6_sub2).x, (byte) -103, ((Character) class1_sub6_sub2).y, (Player.fixZ(((Character) class1_sub6_sub2).x, ((Class1_Sub1) class1_sub1).anInt2424, ((Character) class1_sub6_sub2).y)) - ((Class1_Sub1) class1_sub1).anInt2422, Class68_Sub3.loopCycle); } class1_sub1.method66(Class109.anInt1846, false); Class68_Sub20_Sub4.method1061(GameSocket.plane, (int) ((Class1_Sub1) class1_sub1).aDouble2408, (int) ((Class1_Sub1) class1_sub1).aDouble2400, (int) ((Class1_Sub1) class1_sub1).aDouble2392, 60, class1_sub1, ((Class1_Sub1) class1_sub1).anInt2409, -1L, false); } } } static { anInt1803 = 127; aClass100_1802 = Class112.makeMutableString(43, ")1"); anIntArray1811 = new int[2000]; aClass100_1810 = (Class112.makeMutableString(43, "Ihre Ignorieren)2Liste ist voll)1 Sie k-Onnen nur 100 Spieler darauf eintragen)3")); packetSize = 0; aClass100_1812 = Class112.makeMutableString(43, "Schrifts-=tze geladen)3"); aClass113_1805 = new NodeCache(512); } }
agpl-3.0
VladRodionov/bigbase
block-cache/src/main/java/com/koda/integ/hbase/storage/FileExtMultiStorage.java
6054
/******************************************************************************* * Copyright (c) 2013, 2014 Vladimir Rodionov. All Rights Reserved * * This code is released under the GNU Affero General Public License. * * See: http://www.fsf.org/licensing/licenses/agpl-3.0.html * * VLADIMIR RODIONOV MAKES NO REPRESENTATIONS OR WARRANTIES ABOUT THE SUITABILITY * OF THE SOFTWARE, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE * IMPLIED WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE, OR * NON-INFRINGEMENT. Vladimir Rodionov SHALL NOT BE LIABLE FOR ANY DAMAGES SUFFERED * BY LICENSEE AS A RESULT OF USING, MODIFYING OR DISTRIBUTING THIS SOFTWARE OR * ITS DERIVATIVES. * * Author: Vladimir Rodionov * *******************************************************************************/ package com.koda.integ.hbase.storage; import java.io.IOException; import java.nio.ByteBuffer; import java.util.List; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.apache.hadoop.conf.Configuration; import com.koda.cache.OffHeapCache; import com.koda.integ.hbase.util.ConfigHelper; import com.koda.util.Utils; /** * This class implements file-based L3 cache with multiple cache directories. * It supports up to 127 cache directories (it can do 256, but do we really need this?). * */ public class FileExtMultiStorage implements ExtStorage { /** The Constant LOG. */ static final Log LOG = LogFactory.getLog(FileExtMultiStorage.class); private FileExtStorage[] storages; /** The max storage size. */ private long maxStorageSize ; @Override public void config(Configuration cfg, OffHeapCache cache) throws IOException { String value = cfg.get(FileExtStorage.FILE_STORAGE_BASE_DIR); if( value == null){ throw new IOException("[FileExtMultiStorage] Base directory not specified."); } String[] cacheDirs = value.split(","); value = cfg.get(FileExtStorage.FILE_STORAGE_MAX_SIZE); if( value == null){ throw new IOException("[FileExtMultiStorage] Maximum storage size not specified."); } else{ maxStorageSize = Long.parseLong(value); LOG.info("[FileExtMultiStorage] Maximum storage size: "+maxStorageSize); } storages = new FileExtStorage[cacheDirs.length]; long maxStorSize = this.maxStorageSize / storages.length; for(int i = 0; i < cacheDirs.length; i++){ Configuration config = ConfigHelper.copy(cfg); config.set(FileExtStorage.FILE_STORAGE_BASE_DIR, cacheDirs[i]); config.set(FileExtStorage.FILE_STORAGE_MAX_SIZE, Long.toString(maxStorSize)); storages[i] = new FileExtStorage(); storages[i].config(config, cache); } } @Override public StorageHandle storeData(ByteBuffer buf) { int numStorages = storages.length; // Key length (16) int length = buf.getInt(4); int hash = Utils.hash(buf, 8, length, 0); int storageId = Math.abs(hash) % numStorages; FileStorageHandle handle = (FileStorageHandle) storages[storageId].storeData(buf); addCacheRootId(handle, storageId); return handle; } @Override public List<StorageHandle> storeDataBatch(ByteBuffer buf) { throw new RuntimeException("not implemented"); } @Override public StorageHandle getData(StorageHandle storeHandle, ByteBuffer buf) { int id = getCacheRootId((FileStorageHandle) storeHandle); return addCacheRootId((FileStorageHandle)storages[id].getData(clearHandle((FileStorageHandle)storeHandle), buf), id); } @Override public void close() throws IOException { LOG.info("Closing down L3 cache storage"); long start = System.currentTimeMillis(); for(FileExtStorage storage: storages) { storage.close(); } long end = System.currentTimeMillis(); LOG.info("Completed in "+(end-start)+"ms"); } @Override public void flush() throws IOException { LOG.info("Flushing down L3 cache storage"); long start = System.currentTimeMillis(); for(FileExtStorage storage: storages) { storage.flush(); } long end = System.currentTimeMillis(); LOG.info("Completed in "+(end-start)+"ms"); } @Override public long size() { long size = 0; for(FileExtStorage storage: storages) { size += storage.size(); } return size; } @Override public void shutdown(boolean isPersistent) throws IOException { LOG.info("Shutting down L3 cache storage"); long start = System.currentTimeMillis(); for(FileExtStorage storage: storages) { storage.shutdown(isPersistent); } long end = System.currentTimeMillis(); LOG.info("Completed in "+(end-start)+"ms"); } @Override public long getMaxStorageSize() { return maxStorageSize; } @Override public StorageHandle newStorageHandle() { return new FileStorageHandle(); } @Override public boolean isValid(StorageHandle h) { FileStorageHandle hh = ((FileStorageHandle) h).copy(); int storageId = getCacheRootId((FileStorageHandle)hh); hh = clearHandle(hh); return storages[storageId].isValid(hh); } public long getFlushInterval() { if(storages[0] != null) return storages[0].getFlushInterval(); else return -1; } public long getCurrentStorageSize() { long size = 0; for(FileExtStorage stor : storages) { size += stor.getCurrentStorageSize(); } return size; } public int getMinId() { int min = Integer.MAX_VALUE; for(FileExtStorage stor: storages) { int v = stor.getMinId().get(); if( v < min) min = v; } return min; } public int getMaxId() { int max = Integer.MIN_VALUE; for(FileExtStorage stor: storages) { int v = stor.getMaxId().get(); if( v > max) max = v; } return max; } private final FileStorageHandle addCacheRootId(FileStorageHandle h, int id) { h.id = id << 24 | h.id; return h; } private final int getCacheRootId(FileStorageHandle h) { return h.id >>> 24; } private final FileStorageHandle clearHandle(FileStorageHandle h) { h.id = h.id & 0xffffff; return h; } public String getFilePath(FileStorageHandle h) { int id = getCacheRootId(h); return storages[id].getFilePath(h.getId() & 0xffffff); } }
agpl-3.0
shenan4321/BIMplatform
generated/cn/dlb/bim/models/ifc2x3tc1/impl/IfcTankTypeImpl.java
2174
/** * Copyright (C) 2009-2014 BIMserver.org * * 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/>. */ package cn.dlb.bim.models.ifc2x3tc1.impl; import org.eclipse.emf.ecore.EClass; import cn.dlb.bim.models.ifc2x3tc1.Ifc2x3tc1Package; import cn.dlb.bim.models.ifc2x3tc1.IfcTankType; import cn.dlb.bim.models.ifc2x3tc1.IfcTankTypeEnum; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Ifc Tank Type</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link cn.dlb.bim.models.ifc2x3tc1.impl.IfcTankTypeImpl#getPredefinedType <em>Predefined Type</em>}</li> * </ul> * * @generated */ public class IfcTankTypeImpl extends IfcFlowStorageDeviceTypeImpl implements IfcTankType { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected IfcTankTypeImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return Ifc2x3tc1Package.Literals.IFC_TANK_TYPE; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public IfcTankTypeEnum getPredefinedType() { return (IfcTankTypeEnum) eGet(Ifc2x3tc1Package.Literals.IFC_TANK_TYPE__PREDEFINED_TYPE, true); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public void setPredefinedType(IfcTankTypeEnum newPredefinedType) { eSet(Ifc2x3tc1Package.Literals.IFC_TANK_TYPE__PREDEFINED_TYPE, newPredefinedType); } } //IfcTankTypeImpl
agpl-3.0
Sage-Bionetworks/rstudio
src/gwt/src/org/rstudio/studio/client/projects/events/SwitchToProjectHandler.java
674
/* * SwitchToProjectHandler.java * * Copyright (C) 2009-11 by RStudio, Inc. * * This program is licensed to you under the terms of version 3 of the * GNU Affero General Public License. This program is distributed WITHOUT * ANY EXPRESS OR IMPLIED WARRANTY, INCLUDING THOSE OF NON-INFRINGEMENT, * MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE. Please refer to the * AGPL (http://www.gnu.org/licenses/agpl-3.0.txt) for more details. * */ package org.rstudio.studio.client.projects.events; import com.google.gwt.event.shared.EventHandler; public interface SwitchToProjectHandler extends EventHandler { void onSwitchToProject(SwitchToProjectEvent event); }
agpl-3.0
indexdata/mkjsf
src/main/java/com/indexdata/mkjsf/utils/FileUpload.java
1516
package com.indexdata.mkjsf.utils; import java.io.IOException; import java.io.Serializable; import javax.faces.context.ExternalContext; import javax.faces.context.FacesContext; import org.apache.commons.io.FilenameUtils; import org.apache.log4j.Logger; import org.apache.myfaces.custom.fileupload.UploadedFile; /** * Helper class for file uploads. * * @author Niels Erik * */ public abstract class FileUpload implements Serializable { private static Logger logger = Logger.getLogger(FileUpload.class); private static final long serialVersionUID = 748784638056392862L; public FileUpload() { } public abstract UploadedFile getUploadedFile(); public abstract void setUploadedFile(UploadedFile uploadedFile); public void downloadDoc() throws IOException { logger.info(Utils.objectId(this) + " got a download request"); FacesContext facesContext = FacesContext.getCurrentInstance(); ExternalContext externalContext = facesContext.getExternalContext(); externalContext.setResponseHeader("Content-Type", getUploadedFile().getContentType()); externalContext.setResponseHeader("Content-Length", String.valueOf((getUploadedFile().getBytes().length))); externalContext.setResponseHeader("Content-Disposition", "attachment;filename=\"" + FilenameUtils.getBaseName(getUploadedFile().getName()) + "\""); externalContext.getResponseOutputStream().write(getUploadedFile().getBytes()); facesContext.responseComplete(); } }
agpl-3.0
maduhu/mycollab
mycollab-services/src/main/java/com/esofthead/mycollab/module/crm/domain/Product.java
31598
/** * This file is part of mycollab-services. * * mycollab-services 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. * * mycollab-services 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 mycollab-services. If not, see <http://www.gnu.org/licenses/>. */ /*Domain class of table m_crm_product*/ package com.esofthead.mycollab.module.crm.domain; import com.esofthead.mycollab.core.arguments.ValuedBean; import com.esofthead.mycollab.core.db.metadata.Column; import com.esofthead.mycollab.core.db.metadata.Table; import java.util.Date; import org.apache.commons.lang3.builder.EqualsBuilder; import org.apache.commons.lang3.builder.HashCodeBuilder; import org.hibernate.validator.constraints.Length; @SuppressWarnings("ucd") @Table("m_crm_product") public class Product extends ValuedBean { /** * This field was generated by MyBatis Generator. * This field corresponds to the database column m_crm_product.id * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ @Column("id") private Integer id; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column m_crm_product.productname * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ @Length(max=255, message="Field value is too long") @Column("productname") private String productname; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column m_crm_product.status * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ @Length(max=45, message="Field value is too long") @Column("status") private String status; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column m_crm_product.accountid * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ @Column("accountid") private Integer accountid; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column m_crm_product.website * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ @Length(max=255, message="Field value is too long") @Column("website") private String website; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column m_crm_product.quantity * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ @Column("quantity") private Integer quantity; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column m_crm_product.serialnumber * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ @Length(max=45, message="Field value is too long") @Column("serialnumber") private String serialnumber; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column m_crm_product.assessnumber * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ @Length(max=45, message="Field value is too long") @Column("assessnumber") private String assessnumber; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column m_crm_product.contactid * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ @Column("contactid") private Integer contactid; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column m_crm_product.supportstartdate * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ @Column("supportstartdate") private Date supportstartdate; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column m_crm_product.supportenddate * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ @Column("supportenddate") private Date supportenddate; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column m_crm_product.salesdate * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ @Column("salesdate") private Date salesdate; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column m_crm_product.unitprice * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ @Column("unitprice") private Double unitprice; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column m_crm_product.description * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ @Length(max=4000, message="Field value is too long") @Column("description") private String description; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column m_crm_product.producturl * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ @Length(max=255, message="Field value is too long") @Column("producturl") private String producturl; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column m_crm_product.supportcontact * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ @Length(max=255, message="Field value is too long") @Column("supportcontact") private String supportcontact; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column m_crm_product.supportterm * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ @Length(max=45, message="Field value is too long") @Column("supportterm") private String supportterm; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column m_crm_product.supportdesc * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ @Length(max=100, message="Field value is too long") @Column("supportdesc") private String supportdesc; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column m_crm_product.cost * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ @Column("cost") private Double cost; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column m_crm_product.listprice * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ @Column("listprice") private Double listprice; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column m_crm_product.groupid * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ @Column("groupid") private Integer groupid; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column m_crm_product.tax * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ @Column("tax") private Double tax; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column m_crm_product.taxClass * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ @Length(max=45, message="Field value is too long") @Column("taxClass") private String taxclass; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column m_crm_product.mftNumber * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ @Length(max=45, message="Field value is too long") @Column("mftNumber") private String mftnumber; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column m_crm_product.vendorPartNumber * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ @Length(max=45, message="Field value is too long") @Column("vendorPartNumber") private String vendorpartnumber; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column m_crm_product.createdTime * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ @Column("createdTime") private Date createdtime; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column m_crm_product.createdUser * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ @Length(max=45, message="Field value is too long") @Column("createdUser") private String createduser; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column m_crm_product.sAccountId * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ @Column("sAccountId") private Integer saccountid; /** * This field was generated by MyBatis Generator. * This field corresponds to the database column m_crm_product.lastUpdatedTime * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ @Column("lastUpdatedTime") private Date lastupdatedtime; private static final long serialVersionUID = 1; public final boolean equals(Object obj) { if (obj == null) { return false;} if (obj == this) { return true;} if (obj.getClass() != getClass()) { return false;} Product item = (Product)obj; return new EqualsBuilder().append(id, item.id).build(); } public final int hashCode() { return new HashCodeBuilder(1825, 371).append(id).build(); } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column m_crm_product.id * * @return the value of m_crm_product.id * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ public Integer getId() { return id; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column m_crm_product.id * * @param id the value for m_crm_product.id * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ public void setId(Integer id) { this.id = id; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column m_crm_product.productname * * @return the value of m_crm_product.productname * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ public String getProductname() { return productname; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column m_crm_product.productname * * @param productname the value for m_crm_product.productname * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ public void setProductname(String productname) { this.productname = productname; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column m_crm_product.status * * @return the value of m_crm_product.status * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ public String getStatus() { return status; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column m_crm_product.status * * @param status the value for m_crm_product.status * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ public void setStatus(String status) { this.status = status; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column m_crm_product.accountid * * @return the value of m_crm_product.accountid * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ public Integer getAccountid() { return accountid; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column m_crm_product.accountid * * @param accountid the value for m_crm_product.accountid * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ public void setAccountid(Integer accountid) { this.accountid = accountid; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column m_crm_product.website * * @return the value of m_crm_product.website * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ public String getWebsite() { return website; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column m_crm_product.website * * @param website the value for m_crm_product.website * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ public void setWebsite(String website) { this.website = website; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column m_crm_product.quantity * * @return the value of m_crm_product.quantity * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ public Integer getQuantity() { return quantity; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column m_crm_product.quantity * * @param quantity the value for m_crm_product.quantity * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ public void setQuantity(Integer quantity) { this.quantity = quantity; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column m_crm_product.serialnumber * * @return the value of m_crm_product.serialnumber * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ public String getSerialnumber() { return serialnumber; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column m_crm_product.serialnumber * * @param serialnumber the value for m_crm_product.serialnumber * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ public void setSerialnumber(String serialnumber) { this.serialnumber = serialnumber; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column m_crm_product.assessnumber * * @return the value of m_crm_product.assessnumber * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ public String getAssessnumber() { return assessnumber; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column m_crm_product.assessnumber * * @param assessnumber the value for m_crm_product.assessnumber * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ public void setAssessnumber(String assessnumber) { this.assessnumber = assessnumber; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column m_crm_product.contactid * * @return the value of m_crm_product.contactid * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ public Integer getContactid() { return contactid; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column m_crm_product.contactid * * @param contactid the value for m_crm_product.contactid * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ public void setContactid(Integer contactid) { this.contactid = contactid; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column m_crm_product.supportstartdate * * @return the value of m_crm_product.supportstartdate * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ public Date getSupportstartdate() { return supportstartdate; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column m_crm_product.supportstartdate * * @param supportstartdate the value for m_crm_product.supportstartdate * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ public void setSupportstartdate(Date supportstartdate) { this.supportstartdate = supportstartdate; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column m_crm_product.supportenddate * * @return the value of m_crm_product.supportenddate * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ public Date getSupportenddate() { return supportenddate; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column m_crm_product.supportenddate * * @param supportenddate the value for m_crm_product.supportenddate * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ public void setSupportenddate(Date supportenddate) { this.supportenddate = supportenddate; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column m_crm_product.salesdate * * @return the value of m_crm_product.salesdate * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ public Date getSalesdate() { return salesdate; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column m_crm_product.salesdate * * @param salesdate the value for m_crm_product.salesdate * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ public void setSalesdate(Date salesdate) { this.salesdate = salesdate; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column m_crm_product.unitprice * * @return the value of m_crm_product.unitprice * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ public Double getUnitprice() { return unitprice; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column m_crm_product.unitprice * * @param unitprice the value for m_crm_product.unitprice * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ public void setUnitprice(Double unitprice) { this.unitprice = unitprice; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column m_crm_product.description * * @return the value of m_crm_product.description * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ public String getDescription() { return description; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column m_crm_product.description * * @param description the value for m_crm_product.description * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ public void setDescription(String description) { this.description = description; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column m_crm_product.producturl * * @return the value of m_crm_product.producturl * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ public String getProducturl() { return producturl; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column m_crm_product.producturl * * @param producturl the value for m_crm_product.producturl * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ public void setProducturl(String producturl) { this.producturl = producturl; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column m_crm_product.supportcontact * * @return the value of m_crm_product.supportcontact * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ public String getSupportcontact() { return supportcontact; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column m_crm_product.supportcontact * * @param supportcontact the value for m_crm_product.supportcontact * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ public void setSupportcontact(String supportcontact) { this.supportcontact = supportcontact; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column m_crm_product.supportterm * * @return the value of m_crm_product.supportterm * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ public String getSupportterm() { return supportterm; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column m_crm_product.supportterm * * @param supportterm the value for m_crm_product.supportterm * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ public void setSupportterm(String supportterm) { this.supportterm = supportterm; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column m_crm_product.supportdesc * * @return the value of m_crm_product.supportdesc * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ public String getSupportdesc() { return supportdesc; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column m_crm_product.supportdesc * * @param supportdesc the value for m_crm_product.supportdesc * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ public void setSupportdesc(String supportdesc) { this.supportdesc = supportdesc; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column m_crm_product.cost * * @return the value of m_crm_product.cost * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ public Double getCost() { return cost; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column m_crm_product.cost * * @param cost the value for m_crm_product.cost * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ public void setCost(Double cost) { this.cost = cost; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column m_crm_product.listprice * * @return the value of m_crm_product.listprice * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ public Double getListprice() { return listprice; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column m_crm_product.listprice * * @param listprice the value for m_crm_product.listprice * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ public void setListprice(Double listprice) { this.listprice = listprice; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column m_crm_product.groupid * * @return the value of m_crm_product.groupid * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ public Integer getGroupid() { return groupid; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column m_crm_product.groupid * * @param groupid the value for m_crm_product.groupid * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ public void setGroupid(Integer groupid) { this.groupid = groupid; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column m_crm_product.tax * * @return the value of m_crm_product.tax * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ public Double getTax() { return tax; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column m_crm_product.tax * * @param tax the value for m_crm_product.tax * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ public void setTax(Double tax) { this.tax = tax; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column m_crm_product.taxClass * * @return the value of m_crm_product.taxClass * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ public String getTaxclass() { return taxclass; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column m_crm_product.taxClass * * @param taxclass the value for m_crm_product.taxClass * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ public void setTaxclass(String taxclass) { this.taxclass = taxclass; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column m_crm_product.mftNumber * * @return the value of m_crm_product.mftNumber * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ public String getMftnumber() { return mftnumber; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column m_crm_product.mftNumber * * @param mftnumber the value for m_crm_product.mftNumber * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ public void setMftnumber(String mftnumber) { this.mftnumber = mftnumber; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column m_crm_product.vendorPartNumber * * @return the value of m_crm_product.vendorPartNumber * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ public String getVendorpartnumber() { return vendorpartnumber; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column m_crm_product.vendorPartNumber * * @param vendorpartnumber the value for m_crm_product.vendorPartNumber * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ public void setVendorpartnumber(String vendorpartnumber) { this.vendorpartnumber = vendorpartnumber; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column m_crm_product.createdTime * * @return the value of m_crm_product.createdTime * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ public Date getCreatedtime() { return createdtime; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column m_crm_product.createdTime * * @param createdtime the value for m_crm_product.createdTime * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ public void setCreatedtime(Date createdtime) { this.createdtime = createdtime; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column m_crm_product.createdUser * * @return the value of m_crm_product.createdUser * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ public String getCreateduser() { return createduser; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column m_crm_product.createdUser * * @param createduser the value for m_crm_product.createdUser * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ public void setCreateduser(String createduser) { this.createduser = createduser; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column m_crm_product.sAccountId * * @return the value of m_crm_product.sAccountId * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ public Integer getSaccountid() { return saccountid; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column m_crm_product.sAccountId * * @param saccountid the value for m_crm_product.sAccountId * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ public void setSaccountid(Integer saccountid) { this.saccountid = saccountid; } /** * This method was generated by MyBatis Generator. * This method returns the value of the database column m_crm_product.lastUpdatedTime * * @return the value of m_crm_product.lastUpdatedTime * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ public Date getLastupdatedtime() { return lastupdatedtime; } /** * This method was generated by MyBatis Generator. * This method sets the value of the database column m_crm_product.lastUpdatedTime * * @param lastupdatedtime the value for m_crm_product.lastUpdatedTime * * @mbggenerated Mon Sep 21 13:52:02 ICT 2015 */ public void setLastupdatedtime(Date lastupdatedtime) { this.lastupdatedtime = lastupdatedtime; } public enum Field { id, productname, status, accountid, website, quantity, serialnumber, assessnumber, contactid, supportstartdate, supportenddate, salesdate, unitprice, description, producturl, supportcontact, supportterm, supportdesc, cost, listprice, groupid, tax, taxclass, mftnumber, vendorpartnumber, createdtime, createduser, saccountid, lastupdatedtime; public boolean equalTo(Object value) { return name().equals(value); } } }
agpl-3.0
dzc34/Asqatasun
rules/rules-rgaa3.2017/src/main/java/org/asqatasun/rules/rgaa32017/Rgaa32017Rule042003.java
1527
/* * Asqatasun - Automated webpage assessment * Copyright (C) 2008-2019 Asqatasun.org * * 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/>. * * Contact us by mail: asqatasun AT asqatasun DOT org */ package org.asqatasun.rules.rgaa32017; import org.asqatasun.ruleimplementation.AbstractNotTestedRuleImplementation; /** * Implementation of the rule 4.20.3 of the referential RGAA 3.2017 * * For more details about the implementation, refer to <a href="https://doc.asqatasun.org/en/90_Rules/rgaa3.2017/04.Multimedia/Rule-4-20-3.html">the rule 4.20.3 design page.</a> * @see <a href="http://references.modernisation.gouv.fr/rgaa-accessibilite/criteres.html#test-4-20-3">4.20.3 rule specification</a> * * @author */ public class Rgaa32017Rule042003 extends AbstractNotTestedRuleImplementation { /** * Default constructor */ public Rgaa32017Rule042003 () { super(); } }
agpl-3.0
ungerik/ephesoft
Ephesoft_Community_Release_4.0.2.0/source/gxt/gxt-admin/src/main/java/com/ephesoft/gxt/admin/client/regexbuilder/RegexBuilderConstants.java
20438
/********************************************************************************* * Ephesoft is a Intelligent Document Capture and Mailroom Automation program * developed by Ephesoft, Inc. Copyright (C) 2015 Ephesoft Inc. * * This program is free software; you can redistribute it and/or modify it under * the terms of the GNU Affero General Public License version 3 as published by the * Free Software Foundation with the addition of the following permission added * to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED WORK * IN WHICH THE COPYRIGHT IS OWNED BY EPHESOFT, EPHESOFT DISCLAIMS THE WARRANTY * OF NON INFRINGEMENT OF THIRD PARTY RIGHTS. * * 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 or write to the Free * Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA * 02110-1301 USA. * * You can contact Ephesoft, Inc. headquarters at 111 Academy Way, * Irvine, CA 92617, USA. or at email address info@ephesoft.com. * * The interactive user interfaces in modified source and object code versions * of this program must display Appropriate Legal Notices, as required under * Section 5 of the GNU Affero General Public License version 3. * * In accordance with Section 7(b) of the GNU Affero General Public License version 3, * these Appropriate Legal Notices must retain the display of the "Ephesoft" logo. * If the display of the logo is not reasonably feasible for * technical reasons, the Appropriate Legal Notices must display the words * "Powered by Ephesoft". ********************************************************************************/ package com.ephesoft.gxt.admin.client.regexbuilder; /** * This is a common constants file for the Regex Builder Utitlity. * * @author Ephesoft * * <b>created on</b> 19-Dec-2014 <br/> * @version $LastChangedDate: 2013-07-01 15:36:20 +0530 (Mon, 19-Dec-2014) $ <br/> * $LastChangedRevision: 6241 $ <br/> */ public final class RegexBuilderConstants { /** * A private constructor for avoiding instantiation of constants class. */ private RegexBuilderConstants() { // Do Nothing } /** * AS_FEW_AS_POSSIBLE {@link String}. */ public static final String AS_FEW_AS_POSSIBLE = "as_few_as_possible"; /** * REGEX_QUANTIFIER {@link String}. */ public static final String REGEX_QUANTIFIER = "regex_quantifier"; /** * EXACTLY_ONE_TIME {@link String}. */ public static final String EXACTLY_ONE_TIME = "exactly_one_time"; /** * BETWEEN_0_AND_1_TIME {@link String}. */ public static final String BETWEEN_0_AND_1_TIME = "between_0_and_1_time"; /** * ANY_NO_OF_TIMES {@link String}. */ public static final String ANY_NO_OF_TIMES = "any_number_of_times"; /** * ONE_OR_MORE_TIMES {@link String}. */ public static final String ONE_OR_MORE_TIMES = "one_or_more_times"; /** * EXACTLY_NO_OF_TIMES {@link String}. */ public static final String EXACTLY_NO_OF_TIMES = "number_of_time"; /** * BETWEEN_MIN_AND_MAX_TIME {@link String}. */ public static final String BETWEEN_MIN_AND_MAX_TIME = "between_min_and_max_time"; /** * INVALID_DIGIT_RANGE {@link String}. */ public static final String INVALID_DIGIT_RANGE = "invalid_digit_range"; /** * CASE_INSENSETIVE {@link String}. */ public static final String CASE_INSENSETIVE = "case_insensetive"; /** * START_GROUP {@link String}. */ public static final String START_GROUP = "start_group"; /** * END_GROUP {@link String}. */ public static final String END_GROUP = "end_group"; /** * CAPTURE_GROUP {@link String}. */ public static final String CAPTURE_GROUP = "capture_group"; /** * NON_CAPTURE_GROUP {@link String}. */ public static final String NON_CAPTURE_GROUP = "non_capture_group"; /** * EXACT_TEXT {@link String}. */ public static final String EXACT_TEXT = "exact_text"; /** * MATCH_EXACT_TEXT {@link String}. */ public static final String MATCH_EXACT_TEXT = "match_exact_text"; /** * TEXT_IN_RANGE {@link String}. */ public static final String TEXT_IN_RANGE = "text_in_range"; /** * LOWER_CASE_LETTER {@link String}. */ public static final String LOWER_CASE_LETTER = "lower_case_letter"; /** * UPPER_CASE_LETTER {@link String}. */ public static final String UPPER_CASE_LETTER = "upper_case_letter"; /** * ANY_DIGIT {@link String}. */ public static final String ANY_DIGIT = "any_digit"; /** * ANY_CHARACTER {@link String}. */ public static final String ANY_CHARACTER = "any_character"; /** * WORD_BOUNDARY {@link String}. */ public static final String WORD_BOUNDARY = "word_boundary"; /** * FREE_TEXT {@link String}. */ public static final String FREE_TEXT = "free_text"; /** * ANY_SPECIAL_CHARACTER_TEXT {@link String}. */ public static final String ANY_SPECIAL_CHARACTER_TEXT = "special_character_text"; /** * ANY_LETTER_TEXT {@link String}. */ public static final String ANY_LETTER_TEXT = "any_letter"; /** * ANY_WHITE_SPACE_CHARACTER {@link String}. */ public static final String ANY_WHITE_SPACE_CHARACTER = "white_space_character"; /** * ANY_DIGIT_IN_RANGE {@link String}. */ public static final String ANY_DIGIT_IN_RANGE = "digit_in_range"; /** * LOWER_CASE_LETTER_RANGE {@link String}. */ public static final String LOWER_CASE_LETTER_RANGE = "lower_case_lettter_range"; /** * UPPER_CASE_LETTER_RANGE {@link String}. */ public static final String UPPER_CASE_LETTER_RANGE = "upper_Case_letter_range"; /** * MATCH_STRING_CONTAINS {@link String}. */ public static final String MATCH_STRING_CONTAINS = "match_string_contains"; /** * MATCH_STRING_STARTS_WITH {@link String}. */ public static final String MATCH_STRING_STARTS_WITH = "match_string_starts_with"; /** * MATCH_STRING_ENDS_IN {@link String}. */ public static final String MATCH_STRING_ENDS_IN = "match_string_ends_in"; /** * MATCH_STRING_STARTS_WITH_ENDS_IN {@link String}. */ public static final String MATCH_STRING_STARTS_WITH_ENDS_IN = "match_string_starts_with_ends_in"; /** * MATCH_IF_PRESENT {@link String}. */ public static final String MATCH_IF_PRESENT = "match_only_if_present"; /** * MATCH_IF_ABSENT {@link String}. */ public static final String MATCH_IF_ABSENT = "match_only_if_absent"; /** * FOLLOWED_BY {@link String}. */ public static final String FOLLOWED_BY = "followed_by"; /** * OR_REGEX {@link String}. */ public static final String OR_REGEX = "or_regex"; /** * DOT_REGEX {@link String}. */ public static final String DOT_REGEX = "."; /** * ENDS_IN {@link String}. */ public static final String ENDS_IN = "ends_in"; /** * ONLY_IF_FOLLOWED_BY {@link String}. */ public static final String ONLY_IF_FOLLOWED_BY = "only_if_followed_by"; /** * ONLY_IF_NOT_FOLLOWED_BY {@link String}. */ public static final String ONLY_IF_NOT_FOLLOWED_BY = "only_if_not_followed_by"; /** * ONLY_IF_PRECEDED_BY {@link String}. */ public static final String ONLY_IF_PRECEDED_BY = "only_if_preceded_by"; /** * ONLY_IF_NOT_PRECEDED_BY {@link String}. */ public static final String ONLY_IF_NOT_PRECEDED_BY = "only_if_not_preceded_by"; /** * STARTS_WITH {@link String}. */ public static final String STARTS_WITH = "starts_with"; /** * STARTS_WITH_ENDS_IN {@link String}. */ public static final String STARTS_WITH_ENDS_IN = "starts_with_and_ends_in"; /** * DASH {@link String}. */ public static final String DASH = "-"; /** * ADD_BUTTON_REGEX {@link String}. */ public static final String ADD_BUTTON_REGEX = "add_regex_button"; /** * REMOVE_BUTTON_REGEX {@link String}. */ public static final String REMOVE_BUTTON_REGEX = "remove_regex_button"; /** * RESET_BUTTON_REGEX {@link String}. */ public static final String RESET_BUTTON_REGEX = "reset_regex_button"; /** * CLOSE_BUTTON_REGEX {@link String}. */ public static final String CLOSE_BUTTON_REGEX = "close_regex_button"; /** * REGEX_GENERATED {@link String}. */ public static final String REGEX_GENERATED = "regex_pattern"; /** * STR_TO_BE_MATCHED {@link String}. */ public static final String STR_TO_BE_MATCHED = "str_to_be_matched"; /** * FIND_ALL_MATCHES {@link String}. */ public static final String FIND_ALL_MATCHES = "find_all_matches"; /** * MATCH_EXACT_PATTERN {@link String}. */ public static final String MATCH_EXACT_PATTERN = "match_exact_pattern"; /** * REGEX_STR {@link String}. */ public static final String REGEX_STR = "regex"; /** * GENERATE_REGEX {@link String}. */ public static final String GENERATE_REGEX = "generate_regex"; /** * EXACTLY_ONE_TIME_HELP_MESSAGE {@link String}. */ public static final String EXACTLY_ONE_TIME_HELP_MESSAGE = "only_one_time"; /** * BETWEEN_0_OR_1_TIME_HELP_MESSAGE {@link String}. */ public static final String BETWEEN_0_OR_1_TIME_HELP_MESSAGE = "repeat_zero_or_one_time"; /** * ANY_NO_OF_TIMES_HELP_MESSAGE {@link String}. */ public static final String ANY_NO_OF_TIMES_HELP_MESSAGE = "repeat_any_number_of_times"; /** * ONE_OR_MORE_TIME_HELP_MESSAGE {@link String}. */ public static final String ONE_OR_MORE_TIME_HELP_MESSAGE = "repeat_one_or_more_times"; /** * REPEAT_N_TIMES_HELP_MESSAGE {@link String}. */ public static final String REPEAT_N_TIMES_HELP_MESSAGE = "repeat_n_times"; /** * BETWEEN_MAX_AND_MIN_TIME_HELP_MESSAGE {@link String}. */ public static final String BETWEEN_MAX_AND_MIN_TIME_HELP_MESSAGE = "between_min_and_max_help"; /** * AS_FEW_AS_POSSIBLE_HELP_MESSAGE {@link String}. */ public static final String AS_FEW_AS_POSSIBLE_HELP_MESSAGE = "as_few_as_possible_help"; /** * CASE_INSENSETIVE_HELP_MESSAGE {@link String}. */ public static final String CASE_INSENSETIVE_HELP_MESSAGE = "case_insensetive_help"; /** * START_GROUP_HELP_MESSAGE {@link String}. */ public static final String START_GROUP_HELP_MESSAGE = "start_group_help"; /** * END_GROUP_HELP_MESSAGE {@link String}. */ public static final String END_GROUP_HELP_MESSAGE = "end_group_help"; /** * CAPTURE_GROUP_HELP_MESSAGE {@link String}. */ public static final String CAPTURE_GROUP_HELP_MESSAGE = "capture_group_help"; /** * NON_CAPTURE_GROUP_HELP_MESSAGE {@link String}. */ public static final String NON_CAPTURE_GROUP_HELP_MESSAGE = "non_capture_group_help"; /** * MATCH_EXACT_TEXT_HELP_MESSAGE {@link String}. */ public static final String MATCH_EXACT_TEXT_HELP_MESSAGE = "match_exact_text_help"; /** * TEXT_IN_RANGE_HELP_MESSAGE {@link String}. */ public static final String TEXT_IN_RANGE_HELP_MESSAGE = "text_in_range_help"; /** * LOWER_CASE_LETTER_HELP_MESSAGE {@link String}. */ public static final String LOWER_CASE_LETTER_HELP_MESSAGE = "lower_case_letter_help"; /** * UPPER_CASE_LETTER_HELP_MESSAGE {@link String}. */ public static final String UPPER_CASE_LETTER_HELP_MESSAGE = "upper_case_letter_help"; /** * ANY_DIGIT_HELP_MESSAGE {@link String}. */ public static final String ANY_DIGIT_HELP_MESSAGE = "digit_help"; /** * ANY_CHARACTER_HELP_MESSAGE {@link String}. */ public static final String ANY_CHARACTER_HELP_MESSAGE = "any_character_help"; /** * WORD_BOUNDARY_HELP_MESSAGE {@link String}. */ public static final String WORD_BOUNDARY_HELP_MESSAGE = "word_boundary_help"; /** * FREE_TEXT_HELP_MESSAGE {@link String}. */ public static final String FREE_TEXT_HELP_MESSAGE = "free_text_help"; /** * ANY_SPECIAL_CHARACTER_TEXT_HELP_MESSAGE {@link String}. */ public static final String ANY_SPECIAL_CHARACTER_TEXT_HELP_MESSAGE = "any_special_character_text_help"; /** * ANY_LETTER_TEXT_HELP_MESSAGE {@link String}. */ public static final String ANY_LETTER_TEXT_HELP_MESSAGE = "any_letter_text_help"; /** * ANY_WHITE_SPACE_CHARACTER_HELP_MESSAGE {@link String}. */ public static final String ANY_WHITE_SPACE_CHARACTER_HELP_MESSAGE = "any_white_space_character_help"; /** * ANY_DIGIT_IN_RANGE_HELP_MESSAGE {@link String}. */ public static final String ANY_DIGIT_IN_RANGE_HELP_MESSAGE = "any_digit_in_range_help"; /** * LOWER_CASE_LETTER_RANGE_HELP_MESSAGE {@link String}. */ public static final String LOWER_CASE_LETTER_RANGE_HELP_MESSAGE = "lower_case_letter_range_help"; /** * UPPER_CASE_LETTER_RANGE_HELP_MESSAGE {@link String}. */ public static final String UPPER_CASE_LETTER_RANGE_HELP_MESSAGE = "upper_case_letter_range_help"; /** * LOWER_CASE_LETTER_REGEX {@link String}. */ public static final String LOWER_CASE_LETTER_REGEX = "a-z"; /** * UPEER_CASE_LETTER_REGEX {@link String}. */ public static final String UPEER_CASE_LETTER_REGEX = "A-Z"; /** * DIGIT_RANGE_REGEX {@link String}. */ public static final String DIGIT_RANGE_REGEX = "0-9"; /** * WHITE_SPACE_CHARACTER_REGEX {@link String}. */ public static final String WHITE_SPACE_CHARACTER_REGEX = "\\s"; /** * ANY_LETTER_REGEX {@link String}. */ public static final String ANY_LETTER_REGEX = "a-zA-Z"; /** * RANGE_START_REGEX {@link String}. */ public static final String RANGE_START_REGEX = "["; /** * RANGE_END_REGEX {@link String}. */ public static final String RANGE_END_REGEX = "]"; /** * RANGE_START_END_REGEX {@link String}. */ public static final String RANGE_START_END_REGEX = "[]"; /** * MATCH_ONLY_IF_ABSENT_REGEX {@link String}. */ public static final String MATCH_ONLY_IF_ABSENT_REGEX = "^"; /** * REGEX_PATTERN_EMPTY {@link String}. */ public static final String REGEX_PATTERN_EMPTY_ERROR_MESSAGE = "regex_pattern_empty_error_message"; /** * STRING_MATCHED_EMPTY {@link String}. */ public static final String STRING_MATCHED_EMPTY_ERROR_MESSAGE = "string_matched_empty_error_message"; /** * REGEX_PATTERN_VALID {@link String}. */ public static final String REGEX_PATTERN_VALID = "regex_pattern_valid"; /** * REGEX_PATTERN_INVALID {@link String}. */ public static final String REGEX_PATTERN_INVALID = "regex_pattern_invalid"; /** * ERROR_OCCURRED_VERIFYING_REGEX {@link String}. */ public static final String ERROR_OCCURRED_VERIFYING_REGEX = "error_occurred_verifying_regex"; /** * NO_MATCH_FOUND_ERROR_MESSAGE {@link String}. */ public static final String NO_MATCH_FOUND_ERROR_MESSAGE = "no_match_found_error_message"; /** * REGEX_BUILDER_DIALOG_TITLE {@link String}. */ public static final String REGEX_BUILDER_DIALOG_TITLE = "regex_builder"; /** * CASE_INSENSETIVE_REGEX_STRING {@link String}. */ public static final String CASE_INSENSETIVE_REGEX_STRING = "(?i)"; /** * START_BRACKET_REGEX_STRING {@link String}. */ public static final String START_BRACKET_REGEX_STRING = "("; /** * END_BRACKET_REGEX_STRING {@link String}. */ public static final String END_BRACKET_REGEX_STRING = ")"; /** * OR_OPERATOR_REGEX_STRING {@link String}. */ public static final String OR_OPERATOR_REGEX_STRING = "|"; /** * IS_FOLLOWED_BY_REGEX_STRING {@link String}. */ public static final String IS_FOLLOWED_BY_REGEX_STRING = "(?="; /** * IS_NOT_FOLLOWED_BY_REGEX_STRING {@link String}. */ public static final String IS_NOT_FOLLOWED_BY_REGEX_STRING = "(?!"; /** * IS_PRECEDED_BY_REGEX_STRING {@link String}. */ public static final String IS_PRECEDED_BY_REGEX_STRING = "(?<="; /** * IS_NOT_PRECEDED_BY_REGEX_STRING {@link String}. */ public static final String IS_NOT_PRECEDED_BY_REGEX_STRING = "(?<!"; /** * START_CURLY_BRACES_REGEX_STRING {@link String}. */ public static final String START_CURLY_BRACES_REGEX_STRING = "{"; /** * END_CURLY_BRACES_REGEX_STRING {@link String}. */ public static final String END_CURLY_BRACES_REGEX_STRING = "}"; /** * LAZY_QUANTIFIER {@link String}. */ public static final String LAZY_QUANTIFIER_REGEX_STRING = "?"; /** * ONE_OR_MORE_TIME_REGEX_STRING {@link String}. */ public static final String ONE_OR_MORE_TIME_REGEX_STRING = "+"; /** * ZERO_OR_MORE_TIME_REGEX_STRING {@link String}. */ public static final String ZERO_OR_MORE_TIME_REGEX_STRING = "*"; /** * STARTS_WITH_REGEX_STRING {@link String}. */ public static final String STARTS_WITH_REGEX_STRING = "^"; /** * ENDS_WITH_REGEX_STRING {@link String}. */ public static final String ENDS_WITH_REGEX_STRING = "$"; /** * ZERO_OR_ONE_TIME_REGEX_STRING {@link String}. */ public static final String ZERO_OR_ONE_TIME_REGEX_STRING = "?"; /** * WORD_BOUNDARY_REGEX_STRING {@link String}. */ public static final String WORD_BOUNDARY_REGEX_STRING = "\\b"; /** * NON_CAPTURE_GROUP_REGEX_STRING {@link String}. */ public static final String NON_CAPTURE_GROUP_REGEX_STRING = "(?:"; /** * DIGIT_RANGE_REGEX_STRING {@link String}. */ public static final String DIGIT_RANGE_REGEX_STRING = "[0-9]"; /** * INVALID_LOWER_CASE_RANGE {@link String}. */ public static final String INVALID_LOWER_CASE_RANGE = "invalid_lower_case_range"; /** * INVALID_UPPER_CASE_RANGE {@link String}. */ public static final String INVALID_UPPER_CASE_RANGE = "invalid_upper_case_range"; /** * APPLY_QUANTIFIER_TO_ENTIRE_REGEX {@link String} a constant used for the label text to be shown for regex builder quantifier * section. */ public static final String APPLY_QUANTIFIER_TO_ENTIRE_REGEX = "apply_quantifier_to_the_entire_group"; /** * APPLY_QUANTIFIER_TO_ENTIRE_REGEX_HELP_MESSAGE {@link String} a constant used for showing the help message for the regex builder * qunatifier section. */ public static final String APPLY_QUANTIFIER_TO_ENTIRE_REGEX_HELP_MESSAGE = "apply_quantifier_to_the_entire_group_help"; /** * GENERATE_REGEX_PATTERN {@link String} a constant used to show the text for generating the regex pattern. */ public static final String GENERATE_REGEX_PATTERN = "generate_regex_pattern"; /** * BACKSLASH_CHARACTER {@link String}. */ public static final String BACKSLASH_CHARACTER = "backslash_caharacter"; /** * WHITESPACE_CHARACTER {@link String}. */ public static final String WHITESPACE_CHARACTER = "whitespace_character"; /** * NON_WHITESPACE_CHARACTER {@link String}. */ public static final String NON_WHITESPACE_CHARACTER = "non_whitespace_character"; /** * WORD_CHARACTER {@link String}. */ public static final String WORD_CHARACTER = "word_character"; /** * NON_WORD_CHARACTER {@link String}. */ public static final String NON_WORD_CHARACTER = "non_word_character"; /** * NON_DIGIT {@link String}. */ public static final String NON_DIGIT = "non_digit"; /** * BACKSLASH_REGEX {@link String}. */ public static final String BACKSLASH_REGEX = "\\"; /** * NON_WHITESPACE_CHARACTER_REGEX {@link String}. */ public static final String NON_WHITESPACE_CHARACTER_REGEX = "\\S"; /** * WORD_CAHARCTER_REGEX {@link String}. */ public static final String WORD_CAHARCTER_REGEX = "\\w"; /** * NON_WORD_CAHARCTER_REGEX {@link String}. */ public static final String NON_WORD_CAHARCTER_REGEX = "\\W"; /** * NON_DIGIT_REGEX {@link String}. */ public static final String NON_DIGIT_REGEX = "\\D"; /** * LOWER_CASE_LETTER_RANGE_REGEX {@link String}. */ public static final String LOWER_CASE_LETTER_RANGE_REGEX = "[a-z]"; /** * UPPER_CASE_LETTER_RANGE_REGEX {@link String}. */ public static final String UPPER_CASE_LETTER_RANGE_REGEX = "[A-Z]"; /** * LETTER_RANGE {@link String}. */ public static final String LETTER_RANGE_REGEX = "[a-zA-Z]"; /** * <code>SELECT_LABEL</code> a {@link String} constant used to epresent the locale object name for the constant to be displayed * Select value in the list box. */ public static final String SELECT_LABEL = "select"; /** * Select regex pattern constant string. */ public static final String SELECT_REGEX_PATTERN = "select_regex_pattern"; /** * REGEX_BUILDER_GROUP {@link String}. */ public static final String REGEX_BUILDER_GROUP = "regex_group"; /** * SELECT_REGEX {@link String} a constant used to show the text on the button for copying the generated regex pattern to the text * field. */ public static final String SELECT_REGEX = "select_regex"; }
agpl-3.0
opensourceBIM/BIMserver
PluginBase/generated/org/bimserver/models/ifc2x3tc1/IfcStyledRepresentation.java
1761
/** * Copyright (C) 2009-2014 BIMserver.org * * 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/>. */ package org.bimserver.models.ifc2x3tc1; /****************************************************************************** * Copyright (C) 2009-2019 BIMserver.org * * 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 {@literal<http://www.gnu.org/licenses/>}. *****************************************************************************/ public interface IfcStyledRepresentation extends IfcStyleModel { } // IfcStyledRepresentation
agpl-3.0
lolski/grakn
common/iterator/MappedIterator.java
1354
/* * Copyright (C) 2021 Grakn Labs * * 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 <https://www.gnu.org/licenses/>. * */ package grakn.core.common.iterator; import java.util.function.Function; class MappedIterator<T, U> extends AbstractResourceIterator<U> { private final ResourceIterator<T> iterator; private final Function<T, U> function; MappedIterator(ResourceIterator<T> iterator, Function<T, U> function) { this.iterator = iterator; this.function = function; } @Override public boolean hasNext() { return iterator.hasNext(); } @Override public U next() { return function.apply(iterator.next()); } @Override public void recycle() { iterator.recycle(); } }
agpl-3.0
metreeca/metreeca
fore/_bean/src/main/java/com/metreeca/_bean/shared/Meta.java
1551
/* * Copyright © 2013-2018 Metreeca srl. All rights reserved. * * This file is part of Metreeca. * * Metreeca 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. * * Metreeca 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 Metreeca. If not, see <http://www.gnu.org/licenses/>. */ package com.metreeca._bean.shared; import java.util.Map; public interface Meta<T> { public Class<T> type(); public Map<String, Class<?>> key(); public Map<String, Class<?>> fields(); public T create() throws MetaException; public T create(Map<String, Object> values) throws MetaException; public Object get(final Object bean, final String field) throws MetaException; public void set(final Object bean, final String field, final Object value) throws MetaException; public Bean.Info encode(final Bean.Info info); // !!! remove public Bean.Info decode(final Bean.Info info); // !!! remove public static interface Factory { public Meta<?> meta(final String type) throws MetaException; public <T> Meta<T> meta(final Class<T> type) throws MetaException; } }
agpl-3.0
deerwalk/voltdb
src/frontend/org/voltdb/compiler/StatementCompiler.java
23303
/* This file is part of VoltDB. * Copyright (C) 2008-2017 VoltDB Inc. * * 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 VoltDB. If not, see <http://www.gnu.org/licenses/>. */ package org.voltdb.compiler; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import org.hsqldb_voltpatches.HSQLInterface; import org.hsqldb_voltpatches.VoltXMLElement; import org.voltdb.CatalogContext.ProcedurePartitionInfo; import org.voltdb.VoltDB; import org.voltdb.VoltType; import org.voltdb.catalog.Catalog; import org.voltdb.catalog.CatalogMap; import org.voltdb.catalog.Database; import org.voltdb.catalog.PlanFragment; import org.voltdb.catalog.ProcParameter; import org.voltdb.catalog.Procedure; import org.voltdb.catalog.Statement; import org.voltdb.catalog.StmtParameter; import org.voltdb.catalog.Table; import org.voltdb.compiler.VoltCompiler.VoltCompilerException; import org.voltdb.expressions.ParameterValueExpression; import org.voltdb.planner.CompiledPlan; import org.voltdb.planner.QueryPlanner; import org.voltdb.planner.StatementPartitioning; import org.voltdb.planner.TrivialCostModel; import org.voltdb.plannodes.AbstractPlanNode; import org.voltdb.plannodes.AbstractScanPlanNode; import org.voltdb.plannodes.DeletePlanNode; import org.voltdb.plannodes.InsertPlanNode; import org.voltdb.plannodes.PlanNodeList; import org.voltdb.plannodes.UpdatePlanNode; import org.voltdb.types.QueryType; import org.voltdb.utils.BuildDirectoryUtils; import org.voltdb.utils.CatalogUtil; import org.voltdb.utils.CompressionService; import org.voltdb.utils.Encoder; import com.google_voltpatches.common.base.Charsets; /** * Compiles individual SQL statements and updates the given catalog. * <br/>Invokes the Optimizer to generate plans. * */ public abstract class StatementCompiler { public static final int DEFAULT_MAX_JOIN_TABLES = 5; /** * This static method conveniently does a few things for its caller: * - Formats the statement by replacing newlines with spaces * and appends a semicolon if needed * - Updates the catalog Statement with metadata about the statement * - Plans the statement and puts the serialized plan in the catalog Statement * - Updates the catalog Statment with info about the statement's parameters * Upon successful completion, catalog statement will have been updated with * plan fragments needed to execute the statement. * * @param compiler The VoltCompiler instance * @param hsql Pass through parameter to QueryPlanner * @param catalog Pass through parameter to QueryPlanner * @param db Pass through parameter to QueryPlanner * @param estimates Pass through parameter to QueryPlanner * @param catalogStmt Catalog statement to be updated with plan * @param xml XML for statement, if it has been previously parsed * (may be null) * @param stmt Text of statement to be compiled * @param joinOrder Pass through parameter to QueryPlanner * @param detMode Pass through parameter to QueryPlanner * @param partitioning Partition info for statement */ static boolean compileStatementAndUpdateCatalog(VoltCompiler compiler, HSQLInterface hsql, Database db, DatabaseEstimates estimates, Statement catalogStmt, VoltXMLElement xml, String stmt, String joinOrder, DeterminismMode detMode, StatementPartitioning partitioning) throws VoltCompiler.VoltCompilerException { // Cleanup whitespace newlines for catalog compatibility // and to make statement parsing easier. stmt = stmt.replaceAll("\n", " "); stmt = stmt.trim(); compiler.addInfo("Compiling Statement: " + stmt); // put the data in the catalog that we have if (!stmt.endsWith(";")) { stmt += ";"; } // if this key + sql is the same, then a cached stmt can be used String keyPrefix = compiler.getKeyPrefix(partitioning, detMode, joinOrder); // if the key is cache-able, look for a previous statement if (keyPrefix != null) { Statement previousStatement = compiler.getCachedStatement(keyPrefix, stmt); // check if the stmt exists and if it's the same sql text if (previousStatement != null) { catalogStmt.setAnnotation(previousStatement.getAnnotation()); catalogStmt.setAttachment(previousStatement.getAttachment()); catalogStmt.setCachekeyprefix(previousStatement.getCachekeyprefix()); catalogStmt.setCost(previousStatement.getCost()); catalogStmt.setExplainplan(previousStatement.getExplainplan()); catalogStmt.setIscontentdeterministic(previousStatement.getIscontentdeterministic()); catalogStmt.setIsorderdeterministic(previousStatement.getIsorderdeterministic()); catalogStmt.setNondeterminismdetail(previousStatement.getNondeterminismdetail()); catalogStmt.setQuerytype(previousStatement.getQuerytype()); catalogStmt.setReadonly(previousStatement.getReadonly()); catalogStmt.setReplicatedtabledml(previousStatement.getReplicatedtabledml()); catalogStmt.setSeqscancount(previousStatement.getSeqscancount()); catalogStmt.setSinglepartition(previousStatement.getSinglepartition()); catalogStmt.setSqltext(previousStatement.getSqltext()); catalogStmt.setTablesread(previousStatement.getTablesread()); catalogStmt.setTablesupdated(previousStatement.getTablesupdated()); catalogStmt.setIndexesused(previousStatement.getIndexesused()); for (StmtParameter oldSp : previousStatement.getParameters()) { StmtParameter newSp = catalogStmt.getParameters().add(oldSp.getTypeName()); newSp.setAnnotation(oldSp.getAnnotation()); newSp.setAttachment(oldSp.getAttachment()); newSp.setIndex(oldSp.getIndex()); newSp.setIsarray(oldSp.getIsarray()); newSp.setJavatype(oldSp.getJavatype()); newSp.setSqltype(oldSp.getSqltype()); } for (PlanFragment oldFrag : previousStatement.getFragments()) { PlanFragment newFrag = catalogStmt.getFragments().add(oldFrag.getTypeName()); newFrag.setAnnotation(oldFrag.getAnnotation()); newFrag.setAttachment(oldFrag.getAttachment()); newFrag.setHasdependencies(oldFrag.getHasdependencies()); newFrag.setMultipartition(oldFrag.getMultipartition()); newFrag.setNontransactional(oldFrag.getNontransactional()); newFrag.setPlanhash(oldFrag.getPlanhash()); newFrag.setPlannodetree(oldFrag.getPlannodetree()); } return true; } } // determine the type of the query QueryType qtype = QueryType.getFromSQL(stmt); catalogStmt.setReadonly(qtype.isReadOnly()); catalogStmt.setQuerytype(qtype.getValue()); // might be null if not cacheable catalogStmt.setCachekeyprefix(keyPrefix); catalogStmt.setSqltext(stmt); catalogStmt.setSinglepartition(partitioning.wasSpecifiedAsSingle()); String name = catalogStmt.getParent().getTypeName() + "-" + catalogStmt.getTypeName(); String sql = catalogStmt.getSqltext(); String stmtName = catalogStmt.getTypeName(); String procName = catalogStmt.getParent().getTypeName(); TrivialCostModel costModel = new TrivialCostModel(); CompiledPlan plan = null; QueryPlanner planner = new QueryPlanner( sql, stmtName, procName, db, partitioning, hsql, estimates, false, costModel, null, joinOrder, detMode); try { try { if (xml != null) { planner.parseFromXml(xml); } else { planner.parse(); } plan = planner.plan(); assert(plan != null); } catch (Exception e) { // These are normal expectable errors -- don't normally need a stack-trace. String msg = "Failed to plan for statement (" + catalogStmt.getTypeName() + ") \"" + catalogStmt.getSqltext() + "\"."; if (e.getMessage() != null) { msg += " Error: \"" + e.getMessage() + "\""; } throw compiler.new VoltCompilerException(msg); } // There is a hard-coded limit to the number of parameters that can be passed to the EE. if (plan.getParameters().length > CompiledPlan.MAX_PARAM_COUNT) { throw compiler.new VoltCompilerException( "The statement's parameter count " + plan.getParameters().length + " must not exceed the maximum " + CompiledPlan.MAX_PARAM_COUNT); } // Check order and content determinism before accessing the detail which // it caches. boolean orderDeterministic = plan.isOrderDeterministic(); catalogStmt.setIsorderdeterministic(orderDeterministic); boolean contentDeterministic = plan.isContentDeterministic() && (orderDeterministic || !plan.hasLimitOrOffset()); catalogStmt.setIscontentdeterministic(contentDeterministic); String nondeterminismDetail = plan.nondeterminismDetail(); catalogStmt.setNondeterminismdetail(nondeterminismDetail); catalogStmt.setSeqscancount(plan.countSeqScans()); // Input Parameters // We will need to update the system catalogs with this new information for (int i = 0; i < plan.getParameters().length; ++i) { StmtParameter catalogParam = catalogStmt.getParameters().add(String.valueOf(i)); catalogParam.setJavatype(plan.getParameters()[i].getValueType().getValue()); catalogParam.setIsarray(plan.getParameters()[i].getParamIsVector()); catalogParam.setIndex(i); } catalogStmt.setReplicatedtabledml(plan.replicatedTableDML); // output the explained plan to disk (or caller) for debugging StringBuilder planDescription = new StringBuilder(1000); // Initial capacity estimate. planDescription.append("SQL: ").append(plan.sql); // Only output the cost in debug mode. // Cost seems to only confuse people who don't understand how this number is used/generated. if (VoltCompiler.DEBUG_MODE) { planDescription.append("\nCOST: ").append(plan.cost); } planDescription.append("\nPLAN:\n"); planDescription.append(plan.explainedPlan); String planString = planDescription.toString(); // only write to disk if compiler is in standalone mode if (compiler.standaloneCompiler) { BuildDirectoryUtils.writeFile(null, name + ".txt", planString, false); } compiler.captureDiagnosticContext(planString); // build usage links for report generation and put them in the catalog CatalogUtil.updateUsageAnnotations(db, catalogStmt, plan.rootPlanGraph, plan.subPlanGraph); // set the explain plan output into the catalog (in hex) for reporting catalogStmt.setExplainplan(Encoder.hexEncode(plan.explainedPlan)); // compute a hash of the plan MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); assert(false); System.exit(-1); // should never happen with healthy jvm } // Now update our catalog information PlanFragment planFragment = catalogStmt.getFragments().add("0"); planFragment.setHasdependencies(plan.subPlanGraph != null); // mark a fragment as non-transactional if it never touches a persistent table planFragment.setNontransactional(!fragmentReferencesPersistentTable(plan.rootPlanGraph)); planFragment.setMultipartition(plan.subPlanGraph != null); byte[] planBytes = writePlanBytes(compiler, planFragment, plan.rootPlanGraph); md.update(planBytes, 0, planBytes.length); // compute the 40 bytes of hex from the 20 byte sha1 hash of the plans md.reset(); md.update(planBytes); planFragment.setPlanhash(Encoder.hexEncode(md.digest())); if (plan.subPlanGraph != null) { planFragment = catalogStmt.getFragments().add("1"); planFragment.setHasdependencies(false); planFragment.setNontransactional(false); planFragment.setMultipartition(true); byte[] subBytes = writePlanBytes(compiler, planFragment, plan.subPlanGraph); // compute the 40 bytes of hex from the 20 byte sha1 hash of the plans md.reset(); md.update(subBytes); planFragment.setPlanhash(Encoder.hexEncode(md.digest())); } // Planner should have rejected with an exception any statement with an unrecognized type. int validType = catalogStmt.getQuerytype(); assert(validType != QueryType.INVALID.getValue()); return false; } catch (StackOverflowError error) { String msg = "Failed to plan for statement (" + catalogStmt.getTypeName() + ") \"" + catalogStmt.getSqltext() + "\". Error: \"Encountered stack overflow error. " + "Try reducing the number of predicate expressions in the query.\""; throw compiler.new VoltCompilerException(msg); } } static boolean compileFromSqlTextAndUpdateCatalog(VoltCompiler compiler, HSQLInterface hsql, Database db, DatabaseEstimates estimates, Statement catalogStmt, String sqlText, String joinOrder, DeterminismMode detMode, StatementPartitioning partitioning) throws VoltCompiler.VoltCompilerException { return compileStatementAndUpdateCatalog(compiler, hsql, db, estimates, catalogStmt, null, sqlText, joinOrder, detMode, partitioning); } /** * Update the plan fragment and return the bytes of the plan */ static byte[] writePlanBytes(VoltCompiler compiler, PlanFragment fragment, AbstractPlanNode planGraph) throws VoltCompilerException { String json = null; // get the plan bytes PlanNodeList node_list = new PlanNodeList(planGraph); json = node_list.toJSONString(); compiler.captureDiagnosticJsonFragment(json); // Place serialized version of PlanNodeTree into a PlanFragment byte[] jsonBytes = json.getBytes(Charsets.UTF_8); String bin64String = CompressionService.compressAndBase64Encode(jsonBytes); fragment.setPlannodetree(bin64String); return jsonBytes; } /** * Check through a plan graph and return true if it ever touches a persistent table. */ static boolean fragmentReferencesPersistentTable(AbstractPlanNode node) { if (node == null) return false; // these nodes can read/modify persistent tables if (node instanceof AbstractScanPlanNode) return true; if (node instanceof InsertPlanNode) return true; if (node instanceof DeletePlanNode) return true; if (node instanceof UpdatePlanNode) return true; // recursively check out children for (int i = 0; i < node.getChildCount(); i++) { AbstractPlanNode child = node.getChild(i); if (fragmentReferencesPersistentTable(child)) return true; } // if nothing found, return false return false; } /** * This procedure compiles a shim org.voltdb.catalog.Procedure representing a default proc. * The shim has no plan and few details that are expensive to compute. * The returned proc instance has a full plan and can be used to create a ProcedureRunner. * Note that while there are two procedure objects here, none are rooted in a real catalog; * they are entirely parallel to regular, catalog procs. * * This code could probably go a few different places. It duplicates a bit too much of the * StatmentCompiler code for my taste, so I put it here. Next pass could reduce some of the * duplication? */ public static Procedure compileDefaultProcedure(PlannerTool plannerTool, Procedure catProc, String sqlText) { // fake db makes it easy to create procedures that aren't part of the main catalog Database fakeDb = new Catalog().getClusters().add("cluster").getDatabases().add("database"); Table table = catProc.getPartitiontable(); // determine the type of the query QueryType qtype = QueryType.getFromSQL(sqlText); StatementPartitioning partitioning = catProc.getSinglepartition() ? StatementPartitioning.forceSP() : StatementPartitioning.forceMP(); CompiledPlan plan = plannerTool.planSqlCore(sqlText, partitioning); Procedure newCatProc = fakeDb.getProcedures().add(catProc.getTypeName()); newCatProc.setClassname(catProc.getClassname()); newCatProc.setDefaultproc(true); newCatProc.setEverysite(false); newCatProc.setHasjava(false); newCatProc.setPartitioncolumn(catProc.getPartitioncolumn()); newCatProc.setPartitionparameter(catProc.getPartitionparameter()); newCatProc.setPartitiontable(catProc.getPartitiontable()); newCatProc.setReadonly(catProc.getReadonly()); newCatProc.setSinglepartition(catProc.getSinglepartition()); newCatProc.setSystemproc(false); if (catProc.getPartitionparameter() >= 0) { newCatProc.setAttachment( new ProcedurePartitionInfo( VoltType.get((byte) catProc.getPartitioncolumn().getType()), catProc.getPartitionparameter())); } CatalogMap<Statement> statements = newCatProc.getStatements(); assert(statements != null); Statement stmt = statements.add(VoltDB.ANON_STMT_NAME); stmt.setSqltext(sqlText); stmt.setReadonly(catProc.getReadonly()); stmt.setQuerytype(qtype.getValue()); stmt.setSinglepartition(catProc.getSinglepartition()); stmt.setIscontentdeterministic(true); stmt.setIsorderdeterministic(true); stmt.setNondeterminismdetail("NO CONTENT FOR DEFAULT PROCS"); stmt.setSeqscancount(plan.countSeqScans()); stmt.setReplicatedtabledml(!catProc.getReadonly() && table.getIsreplicated()); // Input Parameters // We will need to update the system catalogs with this new information for (int i = 0; i < plan.getParameters().length; ++i) { StmtParameter catalogParam = stmt.getParameters().add(String.valueOf(i)); catalogParam.setIndex(i); ParameterValueExpression pve = plan.getParameters()[i]; catalogParam.setJavatype(pve.getValueType().getValue()); catalogParam.setIsarray(pve.getParamIsVector()); } PlanFragment frag = stmt.getFragments().add("0"); // compute a hash of the plan MessageDigest md = null; try { md = MessageDigest.getInstance("SHA-1"); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); assert(false); System.exit(-1); // should never happen with healthy jvm } byte[] planBytes = writePlanBytes(frag, plan.rootPlanGraph); md.update(planBytes, 0, planBytes.length); // compute the 40 bytes of hex from the 20 byte sha1 hash of the plans md.reset(); md.update(planBytes); frag.setPlanhash(Encoder.hexEncode(md.digest())); if (plan.subPlanGraph != null) { frag.setHasdependencies(true); frag.setNontransactional(true); frag.setMultipartition(true); frag = stmt.getFragments().add("1"); frag.setHasdependencies(false); frag.setNontransactional(false); frag.setMultipartition(true); byte[] subBytes = writePlanBytes(frag, plan.subPlanGraph); // compute the 40 bytes of hex from the 20 byte sha1 hash of the plans md.reset(); md.update(subBytes); frag.setPlanhash(Encoder.hexEncode(md.digest())); } else { frag.setHasdependencies(false); frag.setNontransactional(false); frag.setMultipartition(false); } // set the procedure parameter types from the statement parameter types int paramCount = 0; for (StmtParameter stmtParam : CatalogUtil.getSortedCatalogItems(stmt.getParameters(), "index")) { // name each parameter "param1", "param2", etc... ProcParameter procParam = newCatProc.getParameters().add("param" + String.valueOf(paramCount)); procParam.setIndex(stmtParam.getIndex()); procParam.setIsarray(stmtParam.getIsarray()); procParam.setType(stmtParam.getJavatype()); paramCount++; } return newCatProc; } /** * Update the plan fragment and return the bytes of the plan */ static byte[] writePlanBytes(PlanFragment fragment, AbstractPlanNode planGraph) { // get the plan bytes PlanNodeList node_list = new PlanNodeList(planGraph); String json = node_list.toJSONString(); // Place serialized version of PlanNodeTree into a PlanFragment byte[] jsonBytes = json.getBytes(Charsets.UTF_8); String bin64String = CompressionService.compressAndBase64Encode(jsonBytes); fragment.setPlannodetree(bin64String); return jsonBytes; } }
agpl-3.0
aborg0/rapidminer-vega
src/com/rapidminer/test/ExampleGenerator.java
8689
/* * RapidMiner * * Copyright (C) 2001-2011 by Rapid-I and the contributors * * Complete list of developers available at our web site: * * http://rapid-i.com * * 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/. */ package com.rapidminer.test; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.PrintStream; import java.util.Random; import com.rapidminer.tools.Tools; /** * A helper class for testing purposes which is able to create sample example * tests for tests. * * @author Ingo Mierswa, Simon Fischer * Exp $ */ public class ExampleGenerator { private static final String[][] NOMINAL_VALUES = { { "hund", "katze", "maus", "elefant" }, { "flasche", "strase", "batzen" }, { "ming", "vase", "line" } }; public static void main(String argv[]) { try { String filestem = argv[0]; int type = Integer.parseInt(argv[1]); int numOfExamples = Integer.parseInt(argv[2]); int numOfRealAttributes = Integer.parseInt(argv[3]); int numOfNominalAttributes = Integer.parseInt(argv[4]); double error = Double.parseDouble(argv[5]); boolean labelled = (argv.length <= 6) || (!argv[6].equals("nolabel")); int numOfAttributes = numOfRealAttributes + numOfNominalAttributes; boolean nominalLabel = false; PrintStream eout; eout = new PrintStream(new FileOutputStream(new File(filestem + ".dat"))); eout.println("# Generated by com.rapidminer.test.ExampleGenerator"); eout.println("# function type: " + type); eout.println("# error: " + error); eout.println("# #examples: " + numOfExamples); Random r = new Random(0); for (int i = 0; i < numOfExamples; i++) { double[] att = new double[numOfAttributes + 1]; for (int j = 0; j < numOfRealAttributes; j++) att[j] = r.nextDouble() * 20 - 10; // att[j] = r.nextDouble()*2000-1000; for (int j = 0; j < numOfNominalAttributes; j++) { int index = j + numOfRealAttributes; att[index] = r.nextInt(NOMINAL_VALUES[index % NOMINAL_VALUES.length].length); } for (int j = 0; j < numOfRealAttributes; j++) att[j] = r.nextDouble() * 20 - 10; // att[j] = r.nextDouble()*2000-1000; for (int j = 0; j < numOfNominalAttributes; j++) { int index = j + numOfRealAttributes; att[index] = r.nextInt(NOMINAL_VALUES[index % NOMINAL_VALUES.length].length); } double f = 1 + r.nextDouble() * 2 * error - error; switch (type) { case 1: att[numOfAttributes] = (att[0] + att[1] + att[2]) * f; break; case 2: att[numOfAttributes] = (att[0] + att[1] - 2 * att[2]) > 0 ? 1 : 0; break; case 3: att[numOfAttributes] = r.nextDouble(); break; case 4: att[numOfAttributes] = (att[0] * att[1] * att[2] + att[0] * att[1] + att[1] * att[1]) * f; break; case 5: att[numOfAttributes] = ((att[numOfAttributes - 3] == 1.0) || ((att[numOfAttributes - 2] == 1.0) && (att[numOfAttributes - 1] == 2.0))) ? 0.0 : 1.0; nominalLabel = true; break; case 6: att[numOfAttributes] = att[0] + att[1]; att[2] = (Math.random() < 0.25) ? Double.NaN : att[2]; break; case 7: att[numOfAttributes] = 2 * att[0] - att[1] - att[2] > 0 ? 0.0 : 1.0; nominalLabel = true; break; case 8: att[numOfAttributes] = Math.sin(att[0] * att[1]) + Math.sin(att[0] + att[1]) > 0 ? 0.0 : 1.0; nominalLabel = true; break; case 9: att[numOfAttributes] = Math.sin(att[0] * att[1]) + Math.sin(att[0] + att[1]) + att[0] * att[1] + att[0] + att[1] > 0 ? 0.0 : 1.0; nominalLabel = true; break; case 10: att[numOfAttributes] = Math.sin(att[0] * att[1]) + Math.sin(att[0] + att[1]) * f; break; case 11: att[numOfAttributes] = 50 * Math.sin(att[0] * att[1]) + 20 * Math.sin(att[0] + att[1]) + 5 * att[0] * att[1] + att[0] + 3 * att[1] * f; break; case 12: att[numOfAttributes] = 10 * Math.sin(3 * att[0]) + 12 * Math.sin(7 * att[0]) + 11 * Math.sin(5 * att[1]) + 9 * Math.sin(10 * att[1]) + 10 * Math.sin(8 * (att[0] + att[1])); break; case 13: att[numOfAttributes] = Math.sin(10 * att[0]) + Math.sin(15 * att[1]); break; case 14: att[numOfAttributes] = Math.sin(att[0]) > 0 ? 0 : 1; nominalLabel = true; break; } // if (labelled && nominalLabel && (att[numOfAttributes] == // 1.0)) { for (int j = 0; j < numOfAttributes; j++) { if (j < numOfRealAttributes) eout.print(att[j] + "\t"); else eout.print(NOMINAL_VALUES[j % NOMINAL_VALUES.length][(int) att[j]] + "\t"); } if (labelled) { if (nominalLabel) { eout.print((att[numOfAttributes] == 0.0) ? "positive" : "negative"); } else { eout.print(att[numOfAttributes]); } } eout.println(); // } } eout.close(); PrintStream aout = new PrintStream(new FileOutputStream(new File(filestem + ".att.xml"))); aout.println("<!--"); aout.println(" Generated by com.rapidminer.test.ExampleGenerator"); aout.println(" function type: " + type); aout.println(" error: " + error); aout.println("-->" + Tools.getLineSeparator()); aout.println("<attributeset default_source=\"" + filestem + ".dat\">"); for (int i = 0; i <= numOfAttributes; i++) { aout.println((i < numOfAttributes) ? " <attribute" : " <label"); aout.println(" name = \"" + ((i < numOfAttributes) ? "att" + (i + 1) + "" : "label") + "\""); String sourcecol = (i + 1) + ""; if ((i == numOfAttributes) && !labelled) sourcecol = "none"; aout.println(" sourcecol = \"" + sourcecol + "\""); aout.println(" valuetype = \"" + (((i >= numOfRealAttributes) && ((i != numOfAttributes) || nominalLabel)) ? "nominal\"" : "real\"")); if ((i >= numOfRealAttributes) && ((i != numOfAttributes) || nominalLabel)) { aout.print(" classes = \""); if (i == numOfAttributes) aout.print("negative positive"); else { for (int c = 0; c < NOMINAL_VALUES[i % NOMINAL_VALUES.length].length; c++) { aout.print((c > 0 ? " " : "") + NOMINAL_VALUES[i % NOMINAL_VALUES.length][c]); } } aout.println("\""); } aout.println(" blocktype = \"single_value\""); // aout.println(" blocknumber = \""+(i+1)+"\""); aout.println(" unit = \"\""); aout.println(" />"); } aout.println("</attributeset>"); aout.close(); PrintStream xout = new PrintStream(new FileOutputStream(new File("xp." + filestem + ".xml"))); xout.println("<!--"); xout.println(" Generated by com.rapidminer.test.ExampleGenerator"); xout.println(" function type: " + type); xout.println(" error: " + error); xout.println("-->"); xout.println(); xout.println("<operator name=\"Globalator\" class=\"OperatorChain\">"); xout.println(" <parameter key=\"logfile\" value=\"Log_" + filestem + ".txt\"/>"); xout.println(" <parameter key=\"logverbosity\" value=\"0\"/>"); xout.println(" <parameter key=\"resultfile\" value=\"Result_" + filestem + ".txt\"/>"); xout.println(" <parameter key=\"temp_dir\" value=\"./tmp\"/>"); xout.println(); xout.println(" <operator name=\"Initiator\" class=\"ExampleSource\">"); xout.println(" <parameter key=\"attributes\" value=\"./" + filestem + ".att.xml\"/>"); xout.println(" </operator>"); xout.println(); xout.println(" <!-- insert process definition here -->"); xout.println(); xout.println("</operator>"); xout.close(); } catch (FileNotFoundException e) { e.printStackTrace(); System.err.println("Usage: ExampleGenerator filestem functiontype #examples #realattributes #nominalattributes error [nolabel]"); } } }
agpl-3.0
WebDataConsulting/billing
src/java/com/sapienter/jbilling/server/user/partner/PartnerReferralCommissionWS.java
3544
/* jBilling - The Enterprise Open Source Billing System Copyright (C) 2003-2011 Enterprise jBilling Software Ltd. and Emiliano Conde This file is part of jbilling. jbilling 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. jbilling 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 jbilling. If not, see <http://www.gnu.org/licenses/>. This source was modified by Web Data Technologies LLP (www.webdatatechnologies.in) since 15 Nov 2015. You may download the latest source from webdataconsulting.github.io. */ package com.sapienter.jbilling.server.user.partner; import com.sapienter.jbilling.common.Util; import com.sapienter.jbilling.server.security.WSSecured; import java.io.Serializable; import java.math.BigDecimal; import java.util.Date; /** * This class defines the commission percentage that one partner (referral) will give to another partner (referrer) */ public class PartnerReferralCommissionWS implements WSSecured, Serializable { private int id; private Integer referralId; private Integer referrerId; private Date startDate; private Date endDate; private String percentage; private Integer userId; public PartnerReferralCommissionWS () { } public int getId () { return id; } public void setId (int id) { this.id = id; } public Integer getReferralId () { return referralId; } public void setReferralId (Integer referralId) { this.referralId = referralId; } public Integer getReferrerId () { return referrerId; } public void setReferrerId (Integer referrerId) { this.referrerId = referrerId; } public Date getStartDate () { return startDate; } public void setStartDate (Date startDate) { this.startDate = startDate; } public Date getEndDate () { return endDate; } public void setEndDate (Date endDate) { this.endDate = endDate; } public String getPercentage() { return percentage; } public BigDecimal getPercentageAsDecimal() { return Util.string2decimal(percentage); } public void setPercentage(String percentage) { this.percentage = percentage; } public void setPercentage(BigDecimal percentage) { this.percentage = (percentage != null ? percentage.toString() : null); } /** * Unsupported, web-service security enforced using {@link #getOwningUserId()} * * @return null */ public Integer getOwningEntityId () { return null; } public Integer getOwningUserId () { return userId; } public void setOwningUserId(Integer userId){ this.userId = userId; } @Override public String toString() { return "PartnerReferralCommissionWS{" + "id=" + id + ", referralId=" + referralId + ", referrerId=" + referrerId + ", startDate=" + startDate + ", endDate=" + endDate + ", percentage=" + percentage + '}'; } }
agpl-3.0
gnosygnu/xowa_android
_400_xowa/src/main/java/gplx/xowa/bldrs/installs/Xoi_cmd_wiki_unzip.java
2369
package gplx.xowa.bldrs.installs; import gplx.*; import gplx.xowa.*; import gplx.xowa.bldrs.*; import gplx.gfui.*; import gplx.gfui.kits.core.*; import gplx.core.threads.*; class Xoi_cmd_wiki_unzip extends Gfo_thread_cmd_unzip implements Gfo_thread_cmd {//#*inherit public static final String KEY_dump = "wiki.unzip"; public Xoi_cmd_wiki_unzip(Xoi_setup_mgr install_mgr, String wiki_key, String dump_date, String dump_type) {this.install_mgr = install_mgr; this.Owner_(install_mgr); this.wiki_key = wiki_key; this.dump_date = dump_date; this.dump_type = dump_type;} private Xoi_setup_mgr install_mgr; String wiki_key, dump_date, dump_type; @Override public String Async_key() {return KEY_dump;} @Override public byte Async_init() { Xoae_app app = install_mgr.App(); Gfui_kit kit = app.Gui_mgr().Kit(); Xowe_wiki wiki = app.Wiki_mgr().Get_by_or_make(Bry_.new_u8(wiki_key)); Io_url wiki_dir = wiki.Import_cfg().Src_dir(); Io_url[] urls = Io_mgr.Instance.QueryDir_args(wiki_dir).Recur_(false).FilPath_("*.xml.bz2").ExecAsUrlAry(); if (urls.length == 0) { kit.Ask_ok(GRP_KEY, "dump.unzip_latest.file_missing", "Could not find a dump file for ~{0} in ~{1}", wiki_key, wiki_dir.Raw()); return Gfo_thread_cmd_.Init_cancel_step; } Io_url src = urls[urls.length - 1]; Io_url trg = app.Fsys_mgr().Wiki_dir().GenSubFil_nest(wiki_key, src.NameOnly()); // NOTE: NameOnly() will strip trailing .bz2; EX: a.xml.bz2 -> a.xml super.Init(app.Usr_dlg(), app.Gui_mgr().Kit(), app.Prog_mgr().App_decompress_bz2(), app.Prog_mgr().App_decompress_zip(), app.Prog_mgr().App_decompress_gz(), src, trg); this.Term_cmd_for_src_(Term_cmd_for_src_move); this.Term_cmd_for_src_url_(app.Fsys_mgr().Wiki_dir().GenSubFil_nest("#dump", "done", src.NameAndExt())); if (Io_mgr.Instance.ExistsFil(trg)) { int rslt = kit.Ask_yes_no_cancel(GRP_KEY, "target_exists", "Target file already exists: '~{0}'.\nDo you want to delete it?", trg.Raw()); switch (rslt) { case Gfui_dlg_msg_.Btn_yes: Io_mgr.Instance.DeleteFil(trg); break; case Gfui_dlg_msg_.Btn_no: return Gfo_thread_cmd_.Init_cancel_step; case Gfui_dlg_msg_.Btn_cancel: return Gfo_thread_cmd_.Init_cancel_all; default: throw Err_.new_unhandled(rslt); } } return Gfo_thread_cmd_.Init_ok; } static final String GRP_KEY = "xowa.thread.dump.unzip"; }
agpl-3.0
AveryRegier/club-tracker
club-web/src/main/java/com/github/averyregier/club/view/FastSetup.java
4845
package com.github.averyregier.club.view; import com.github.averyregier.club.application.ClubApplication; import com.github.averyregier.club.broker.ProviderBroker; import com.github.averyregier.club.domain.User; import com.github.averyregier.club.domain.club.*; import com.github.averyregier.club.domain.club.adapter.SettingsAdapter; import com.github.averyregier.club.domain.login.Provider; import org.brickred.socialauth.Profile; import spark.Request; import spark.Response; import java.util.EnumSet; import java.util.Map; import java.util.UUID; import static spark.Spark.before; import static spark.Spark.halt; /** * Created by avery on 1/10/15. */ public class FastSetup { public void init(ClubApplication app) { before("/test-setup", (request, response) -> { User user; if (new ProviderBroker(app.getConnector()).find().isEmpty()) { new ProviderBroker(app.getConnector()).persist(new Provider("example", "Example", "", "", "", "")); user = setupJohnDoe(app); synchronized (this) { String demoId = new UUID(1, 1).toString(); if (app.getProgram(demoId) == null) { Program program = app.setupProgramWithId("ABC", "AWANA", "en_US", demoId); program.getCurriculum().getSeries().stream() .map(program::addClub) .filter(c -> c.getShortCode().equals("TnT")) .forEach(c -> { c.replacePolicies(EnumSet.of(Policy.noSectionAwards), new SettingsAdapter(c)); }); program.assign(user, ClubLeader.LeadershipRole.COMMANDER); program.getClubs().stream().skip(3).findFirst().ifPresent(c -> c.recruit(user)); registerDoeFamily(user, program); Family family = registerSmithFamily(app, program); signSomeSections(user, family); } } } else { user = setupJohnDoe(app); } goToMy(request, response, user); halt(); }); } private void signSomeSections(User user, Family family) { family.getClubbers().stream().flatMap(c -> c .getNextSections(10).stream()) .forEach(r -> r.sign(user.asListener().get(), "")); } private Family registerSmithFamily(ClubApplication app, Program program) { Profile profile = new Profile(); profile.setFirstName("Mary"); profile.setLastName("Smith"); profile.setGender("female"); profile.setEmail("mary.smith@example.com"); profile.setValidatedId("Example-ID-For-Mary-Smith"); profile.setProviderId("example"); User user = Login.setupUser(app, profile, null); RegistrationInformation form = program.createRegistrationForm(user); Map<String, String> fields = form.getFields(); fields.put("child1.childName.given", "Joe"); fields.put("child1.childName.surname", "Smith"); fields.put("child1.gender", "MALE"); fields.put("child1.ageGroup", "THIRD_GRADE"); fields.put("child2.childName.given", "Jimmy"); fields.put("child2.childName.surname", "Smith"); fields.put("child2.gender", "MALE"); fields.put("child2.ageGroup", "FIRST_GRADE"); return program.updateRegistrationForm(fields).register(user); } private void registerDoeFamily(User user, Program program) { RegistrationInformation form = program.createRegistrationForm(user); Map<String, String> fields = form.getFields(); fields.put("child1.childName.given", "Betty"); fields.put("child1.childName.surname", "Doe"); fields.put("child1.gender", "FEMALE"); fields.put("child1.ageGroup", "FOURTH_GRADE"); Family family = program.updateRegistrationForm(fields).register(user); } private void goToMy(Request request, Response response, User user) { String context = request.contextPath(); context = context == null ? "" : context; String location = context + "/protected/my"; request.session().attribute("location", location); Login.resetCookies(request, response, user); } private User setupJohnDoe(ClubApplication app) { Profile profile = new Profile(); profile.setFirstName("John"); profile.setLastName("Doe"); profile.setGender("male"); profile.setEmail("john.doe@example.com"); profile.setValidatedId("Example-ID-For-John-Doe"); profile.setProviderId("example"); return Login.setupUser(app, profile, null); } }
agpl-3.0
saemx/ged-sas
_alfresco/source/java/eu/akka/saem/alfresco/connector/asalae/ws/WebServiceBindingStub.java
27792
package eu.akka.saem.alfresco.connector.asalae.ws; /** * * @Class : WebServiceBindingStub.java * @Package : eu.akka.saem.alfresco.connector.asalae.ws * @Date : $Date: 25 févr. 2014 $: * @author : $Author: THOMAS.POGNANT $ * @version : $Revision: $: * @Id : $Id: WebServiceBindingStub.java $ * */ public class WebServiceBindingStub extends org.apache.axis.client.Stub implements WebServicePortType { private java.util.Vector cachedSerClasses = new java.util.Vector(); private java.util.Vector cachedSerQNames = new java.util.Vector(); private java.util.Vector cachedSerFactories = new java.util.Vector(); private java.util.Vector cachedDeserFactories = new java.util.Vector(); static org.apache.axis.description.OperationDesc[] _operations; static { _operations = new org.apache.axis.description.OperationDesc[9]; _initOperationDesc1(); } private static void _initOperationDesc1() { org.apache.axis.description.OperationDesc oper; org.apache.axis.description.ParameterDesc param; oper = new org.apache.axis.description.OperationDesc(); oper.setName("wsDepot"); param = new org.apache.axis.description.ParameterDesc(new javax.xml.namespace.QName("", "nomBordereau"), org.apache.axis.description.ParameterDesc.IN, new javax.xml.namespace.QName( "http://www.w3.org/2001/XMLSchema", "string"), String.class, false, false); oper.addParameter(param); param = new org.apache.axis.description.ParameterDesc(new javax.xml.namespace.QName("", "bordereau"), org.apache.axis.description.ParameterDesc.IN, new javax.xml.namespace.QName( "http://www.w3.org/2001/XMLSchema", "base64Binary"), byte[].class, false, false); oper.addParameter(param); param = new org.apache.axis.description.ParameterDesc( new javax.xml.namespace.QName("", "nomDocument"), org.apache.axis.description.ParameterDesc.IN, new javax.xml.namespace.QName( "http://www.w3.org/2001/XMLSchema", "string"), String.class, false, false); oper.addParameter(param); param = new org.apache.axis.description.ParameterDesc(new javax.xml.namespace.QName("", "document"), org.apache.axis.description.ParameterDesc.IN, new javax.xml.namespace.QName( "http://www.w3.org/2001/XMLSchema", "base64Binary"), byte[].class, false, false); oper.addParameter(param); param = new org.apache.axis.description.ParameterDesc(new javax.xml.namespace.QName("", "typeDocument"), org.apache.axis.description.ParameterDesc.IN, new javax.xml.namespace.QName( "http://www.w3.org/2001/XMLSchema", "string"), String.class, false, false); oper.addParameter(param); param = new org.apache.axis.description.ParameterDesc(new javax.xml.namespace.QName("", "login"), org.apache.axis.description.ParameterDesc.IN, new javax.xml.namespace.QName( "http://www.w3.org/2001/XMLSchema", "string"), String.class, false, false); oper.addParameter(param); param = new org.apache.axis.description.ParameterDesc(new javax.xml.namespace.QName("", "password"), org.apache.axis.description.ParameterDesc.IN, new javax.xml.namespace.QName( "http://www.w3.org/2001/XMLSchema", "string"), String.class, false, false); oper.addParameter(param); oper.setReturnType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string")); oper.setReturnClass(String.class); oper.setReturnQName(new javax.xml.namespace.QName("", "wsDepotReturn")); oper.setStyle(org.apache.axis.constants.Style.RPC); oper.setUse(org.apache.axis.constants.Use.ENCODED); _operations[0] = oper; oper = new org.apache.axis.description.OperationDesc(); oper.setName("wsGSeda"); param = new org.apache.axis.description.ParameterDesc(new javax.xml.namespace.QName("", "params"), org.apache.axis.description.ParameterDesc.IN, new javax.xml.namespace.QName( "http://www.w3.org/2001/XMLSchema", "anyType"), Object.class, false, false); oper.addParameter(param); param = new org.apache.axis.description.ParameterDesc(new javax.xml.namespace.QName("", "login"), org.apache.axis.description.ParameterDesc.IN, new javax.xml.namespace.QName( "http://www.w3.org/2001/XMLSchema", "string"), String.class, false, false); oper.addParameter(param); param = new org.apache.axis.description.ParameterDesc(new javax.xml.namespace.QName("", "password"), org.apache.axis.description.ParameterDesc.IN, new javax.xml.namespace.QName( "http://www.w3.org/2001/XMLSchema", "string"), String.class, false, false); oper.addParameter(param); oper.setReturnType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string")); oper.setReturnClass(String.class); oper.setReturnQName(new javax.xml.namespace.QName("", "wsGSedaReturn")); oper.setStyle(org.apache.axis.constants.Style.RPC); oper.setUse(org.apache.axis.constants.Use.ENCODED); _operations[1] = oper; oper = new org.apache.axis.description.OperationDesc(); oper.setName("wsGetVersion"); param = new org.apache.axis.description.ParameterDesc(new javax.xml.namespace.QName("", "login"), org.apache.axis.description.ParameterDesc.IN, new javax.xml.namespace.QName( "http://www.w3.org/2001/XMLSchema", "string"), String.class, false, false); oper.addParameter(param); param = new org.apache.axis.description.ParameterDesc(new javax.xml.namespace.QName("", "password"), org.apache.axis.description.ParameterDesc.IN, new javax.xml.namespace.QName( "http://www.w3.org/2001/XMLSchema", "string"), String.class, false, false); oper.addParameter(param); oper.setReturnType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string")); oper.setReturnClass(String.class); oper.setReturnQName(new javax.xml.namespace.QName("", "wsGetVersionReturn")); oper.setStyle(org.apache.axis.constants.Style.RPC); oper.setUse(org.apache.axis.constants.Use.ENCODED); _operations[2] = oper; oper = new org.apache.axis.description.OperationDesc(); oper.setName("wsGetMessage"); param = new org.apache.axis.description.ParameterDesc( new javax.xml.namespace.QName("", "typeEchange"), org.apache.axis.description.ParameterDesc.IN, new javax.xml.namespace.QName( "http://www.w3.org/2001/XMLSchema", "string"), String.class, false, false); oper.addParameter(param); param = new org.apache.axis.description.ParameterDesc( new javax.xml.namespace.QName("", "typeMessage"), org.apache.axis.description.ParameterDesc.IN, new javax.xml.namespace.QName( "http://www.w3.org/2001/XMLSchema", "string"), String.class, false, false); oper.addParameter(param); param = new org.apache.axis.description.ParameterDesc(new javax.xml.namespace.QName("", "identifiantMessage"), org.apache.axis.description.ParameterDesc.IN, new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"), String.class, false, false); oper.addParameter(param); param = new org.apache.axis.description.ParameterDesc(new javax.xml.namespace.QName("", "login"), org.apache.axis.description.ParameterDesc.IN, new javax.xml.namespace.QName( "http://www.w3.org/2001/XMLSchema", "string"), String.class, false, false); oper.addParameter(param); param = new org.apache.axis.description.ParameterDesc(new javax.xml.namespace.QName("", "password"), org.apache.axis.description.ParameterDesc.IN, new javax.xml.namespace.QName( "http://www.w3.org/2001/XMLSchema", "string"), String.class, false, false); oper.addParameter(param); oper.setReturnType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string")); oper.setReturnClass(String.class); oper.setReturnQName(new javax.xml.namespace.QName("", "wsGetMessageReturn")); oper.setStyle(org.apache.axis.constants.Style.RPC); oper.setUse(org.apache.axis.constants.Use.ENCODED); _operations[3] = oper; oper = new org.apache.axis.description.OperationDesc(); oper.setName("wsGetProfil"); param = new org.apache.axis.description.ParameterDesc(new javax.xml.namespace.QName("", "login"), org.apache.axis.description.ParameterDesc.IN, new javax.xml.namespace.QName( "http://www.w3.org/2001/XMLSchema", "string"), String.class, false, false); oper.addParameter(param); param = new org.apache.axis.description.ParameterDesc(new javax.xml.namespace.QName("", "password"), org.apache.axis.description.ParameterDesc.IN, new javax.xml.namespace.QName( "http://www.w3.org/2001/XMLSchema", "string"), String.class, false, false); oper.addParameter(param); oper.setReturnType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string")); oper.setReturnClass(String.class); oper.setReturnQName(new javax.xml.namespace.QName("", "wsGetProfilReturn")); oper.setStyle(org.apache.axis.constants.Style.RPC); oper.setUse(org.apache.axis.constants.Use.ENCODED); _operations[4] = oper; /** SAEM-80 : Webservice pour la récupération des DUA expirées **/ oper = new org.apache.axis.description.OperationDesc(); oper.setName("wsGetDuaExpirees"); param = new org.apache.axis.description.ParameterDesc(new javax.xml.namespace.QName("", "login"), org.apache.axis.description.ParameterDesc.IN, new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"), String.class, false, false); oper.addParameter(param); param = new org.apache.axis.description.ParameterDesc(new javax.xml.namespace.QName("", "password"), org.apache.axis.description.ParameterDesc.IN, new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"), String.class, false, false); oper.addParameter(param); oper.setReturnType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "anyType")); oper.setReturnClass(Object.class); oper.setReturnQName(new javax.xml.namespace.QName("", "wsGetDuaExpireesReturn")); oper.setStyle(org.apache.axis.constants.Style.RPC); oper.setUse(org.apache.axis.constants.Use.ENCODED); _operations[5] = oper; /******************************************************************/ /** SAEM-80 : Webservice de complétion du bordereau **/ oper = new org.apache.axis.description.OperationDesc(); oper.setName("wsCompleterBordereau"); param = new org.apache.axis.description.ParameterDesc( new javax.xml.namespace.QName("", "bordereau"), org.apache.axis.description.ParameterDesc.IN, new javax.xml.namespace.QName( "http://www.w3.org/2001/XMLSchema", "base64Binary"), byte[].class, false, false); oper.addParameter(param); param = new org.apache.axis.description.ParameterDesc( new javax.xml.namespace.QName("", "login"), org.apache.axis.description.ParameterDesc.IN, new javax.xml.namespace.QName( "http://www.w3.org/2001/XMLSchema", "string"), String.class, false, false); oper.addParameter(param); param = new org.apache.axis.description.ParameterDesc( new javax.xml.namespace.QName("", "password"), org.apache.axis.description.ParameterDesc.IN, new javax.xml.namespace.QName( "http://www.w3.org/2001/XMLSchema", "string"), String.class, false, false); oper.addParameter(param); oper.setReturnType(new javax.xml.namespace.QName( "http://www.w3.org/2001/XMLSchema", "base64Binary")); oper.setReturnClass(byte[].class); oper.setReturnQName(new javax.xml.namespace.QName("", "wsCompleterBordereauReturn")); oper.setStyle(org.apache.axis.constants.Style.RPC); oper.setUse(org.apache.axis.constants.Use.ENCODED); _operations[6] = oper; /*****************************************************/ oper = new org.apache.axis.description.OperationDesc(); oper.setName("wsElimination"); param = new org.apache.axis.description.ParameterDesc(new javax.xml.namespace.QName("", "nomBordereau"), org.apache.axis.description.ParameterDesc.IN, new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"), String.class, false, false); oper.addParameter(param); param = new org.apache.axis.description.ParameterDesc(new javax.xml.namespace.QName("", "bordereau"), org.apache.axis.description.ParameterDesc.IN, new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "base64Binary"), byte[].class, false, false); oper.addParameter(param); param = new org.apache.axis.description.ParameterDesc(new javax.xml.namespace.QName("", "login"), org.apache.axis.description.ParameterDesc.IN, new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"), String.class, false, false); oper.addParameter(param); param = new org.apache.axis.description.ParameterDesc(new javax.xml.namespace.QName("", "password"), org.apache.axis.description.ParameterDesc.IN, new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string"), String.class, false, false); oper.addParameter(param); oper.setReturnType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string")); oper.setReturnClass(String.class); oper.setReturnQName(new javax.xml.namespace.QName("", "wsEliminationReturn")); oper.setStyle(org.apache.axis.constants.Style.RPC); oper.setUse(org.apache.axis.constants.Use.ENCODED); _operations[7] = oper; oper = new org.apache.axis.description.OperationDesc(); oper.setName("wsRestitution"); param = new org.apache.axis.description.ParameterDesc(new javax.xml.namespace.QName("", "nomBordereau"), org.apache.axis.description.ParameterDesc.IN, new javax.xml.namespace.QName( "http://www.w3.org/2001/XMLSchema", "string"), String.class, false, false); oper.addParameter(param); param = new org.apache.axis.description.ParameterDesc(new javax.xml.namespace.QName("", "bordereau"), org.apache.axis.description.ParameterDesc.IN, new javax.xml.namespace.QName( "http://www.w3.org/2001/XMLSchema", "base64Binary"), byte[].class, false, false); oper.addParameter(param); param = new org.apache.axis.description.ParameterDesc( new javax.xml.namespace.QName("", "nomDocument"), org.apache.axis.description.ParameterDesc.IN, new javax.xml.namespace.QName( "http://www.w3.org/2001/XMLSchema", "string"), String.class, false, false); oper.addParameter(param); param = new org.apache.axis.description.ParameterDesc(new javax.xml.namespace.QName("", "document"), org.apache.axis.description.ParameterDesc.IN, new javax.xml.namespace.QName( "http://www.w3.org/2001/XMLSchema", "base64Binary"), byte[].class, false, false); oper.addParameter(param); param = new org.apache.axis.description.ParameterDesc(new javax.xml.namespace.QName("", "typeDocument"), org.apache.axis.description.ParameterDesc.IN, new javax.xml.namespace.QName( "http://www.w3.org/2001/XMLSchema", "string"), String.class, false, false); oper.addParameter(param); param = new org.apache.axis.description.ParameterDesc(new javax.xml.namespace.QName("", "login"), org.apache.axis.description.ParameterDesc.IN, new javax.xml.namespace.QName( "http://www.w3.org/2001/XMLSchema", "string"), String.class, false, false); oper.addParameter(param); param = new org.apache.axis.description.ParameterDesc(new javax.xml.namespace.QName("", "password"), org.apache.axis.description.ParameterDesc.IN, new javax.xml.namespace.QName( "http://www.w3.org/2001/XMLSchema", "string"), String.class, false, false); oper.addParameter(param); oper.setReturnType(new javax.xml.namespace.QName("http://www.w3.org/2001/XMLSchema", "string")); oper.setReturnClass(String.class); oper.setReturnQName(new javax.xml.namespace.QName("", "wsRestitutionReturn")); oper.setStyle(org.apache.axis.constants.Style.RPC); oper.setUse(org.apache.axis.constants.Use.ENCODED); _operations[8] = oper; } public WebServiceBindingStub() throws org.apache.axis.AxisFault { this(null); } public WebServiceBindingStub(java.net.URL endpointURL, javax.xml.rpc.Service service) throws org.apache.axis.AxisFault { this(service); super.cachedEndpoint = endpointURL; } public WebServiceBindingStub(javax.xml.rpc.Service service) throws org.apache.axis.AxisFault { if (service == null) { super.service = new org.apache.axis.client.Service(); } else { super.service = service; } ((org.apache.axis.client.Service) super.service).setTypeMappingVersion("1.2"); } protected org.apache.axis.client.Call createCall() throws java.rmi.RemoteException { try { org.apache.axis.client.Call _call = super._createCall(); if (super.maintainSessionSet) { _call.setMaintainSession(super.maintainSession); } if (super.cachedUsername != null) { _call.setUsername(super.cachedUsername); } if (super.cachedPassword != null) { _call.setPassword(super.cachedPassword); } if (super.cachedEndpoint != null) { _call.setTargetEndpointAddress(super.cachedEndpoint); } if (super.cachedTimeout != null) { _call.setTimeout(super.cachedTimeout); } if (super.cachedPortName != null) { _call.setPortName(super.cachedPortName); } java.util.Enumeration keys = super.cachedProperties.keys(); while (keys.hasMoreElements()) { String key = (String) keys.nextElement(); _call.setProperty(key, super.cachedProperties.get(key)); } return _call; } catch (Throwable _t) { throw new org.apache.axis.AxisFault("Failure trying to get the Call object", _t); } } public String wsDepot(String nomBordereau, byte[] bordereau, String nomDocument, byte[] document, String typeDocument, String login, String password) throws java.rmi.RemoteException { if (super.cachedEndpoint == null) { throw new org.apache.axis.NoEndPointException(); } org.apache.axis.client.Call _call = createCall(); _call.setOperation(_operations[0]); _call.setUseSOAPAction(true); _call.setSOAPActionURI("urn:WebServiceAction"); _call.setSOAPVersion(org.apache.axis.soap.SOAPConstants.SOAP11_CONSTANTS); _call.setOperationName(new javax.xml.namespace.QName("urn:server", "wsDepot")); setRequestHeaders(_call); setAttachments(_call); try { Object _resp = _call.invoke(new Object[] { nomBordereau, bordereau, nomDocument, document, typeDocument, login, password }); if (_resp instanceof java.rmi.RemoteException) { throw (java.rmi.RemoteException) _resp; } else { extractAttachments(_call); try { return (String) _resp; } catch (Exception _exception) { return (String) org.apache.axis.utils.JavaUtils.convert(_resp, String.class); } } } catch (org.apache.axis.AxisFault axisFaultException) { throw axisFaultException; } } public String wsRestitution(String nomBordereau, byte[] bordereau, String nomDocument, byte[] document, String typeDocument, String login, String password) throws java.rmi.RemoteException { if (super.cachedEndpoint == null) { throw new org.apache.axis.NoEndPointException(); } org.apache.axis.client.Call _call = createCall(); _call.setOperation(_operations[8]); _call.setUseSOAPAction(true); _call.setSOAPActionURI("urn:WebServiceAction"); _call.setSOAPVersion(org.apache.axis.soap.SOAPConstants.SOAP11_CONSTANTS); _call.setOperationName(new javax.xml.namespace.QName("urn:server", "wsRestitution")); setRequestHeaders(_call); setAttachments(_call); try { Object _resp = _call.invoke(new Object[] { nomBordereau, bordereau, nomDocument, document, typeDocument, login, password }); if (_resp instanceof java.rmi.RemoteException) { throw (java.rmi.RemoteException) _resp; } else { extractAttachments(_call); try { return (String) _resp; } catch (Exception _exception) { return (String) org.apache.axis.utils.JavaUtils.convert(_resp, String.class); } } } catch (org.apache.axis.AxisFault axisFaultException) { throw axisFaultException; } } public String wsElimination(String nomBordereau, byte[] bordereau, String login, String password) throws java.rmi.RemoteException { if (super.cachedEndpoint == null) { throw new org.apache.axis.NoEndPointException(); } org.apache.axis.client.Call _call = createCall(); _call.setOperation(_operations[7]); _call.setUseSOAPAction(true); _call.setSOAPActionURI("urn:WebServiceAction"); _call.setSOAPVersion(org.apache.axis.soap.SOAPConstants.SOAP11_CONSTANTS); _call.setOperationName(new javax.xml.namespace.QName("urn:server", "wsElimination")); setRequestHeaders(_call); setAttachments(_call); try { Object _resp = _call.invoke(new Object[] {nomBordereau, bordereau, login, password}); if (_resp instanceof java.rmi.RemoteException) { throw (java.rmi.RemoteException)_resp; } else { extractAttachments(_call); try { return (String) _resp; } catch (Exception _exception) { return (String) org.apache.axis.utils.JavaUtils.convert(_resp, String.class); } } } catch (org.apache.axis.AxisFault axisFaultException) { throw axisFaultException; } } public String wsGSeda(Object nomBordereau, String login, String password) throws java.rmi.RemoteException { if (super.cachedEndpoint == null) { throw new org.apache.axis.NoEndPointException(); } org.apache.axis.client.Call _call = createCall(); _call.setOperation(_operations[1]); _call.setUseSOAPAction(true); _call.setSOAPActionURI("urn:WebServiceAction"); _call.setSOAPVersion(org.apache.axis.soap.SOAPConstants.SOAP11_CONSTANTS); _call.setOperationName(new javax.xml.namespace.QName("urn:server", "wsGSeda")); setRequestHeaders(_call); setAttachments(_call); try { Object _resp = _call.invoke(new Object[] { nomBordereau, login, password }); if (_resp instanceof java.rmi.RemoteException) { throw (java.rmi.RemoteException) _resp; } else { extractAttachments(_call); try { return (String) _resp; } catch (Exception _exception) { return (String) org.apache.axis.utils.JavaUtils.convert(_resp, String.class); } } } catch (org.apache.axis.AxisFault axisFaultException) { throw axisFaultException; } } public String wsGetProfil(String login, String password) throws java.rmi.RemoteException { if (super.cachedEndpoint == null) { throw new org.apache.axis.NoEndPointException(); } org.apache.axis.client.Call _call = createCall(); _call.setOperation(_operations[4]); _call.setUseSOAPAction(true); _call.setSOAPActionURI("urn:WebServiceAction"); _call.setSOAPVersion(org.apache.axis.soap.SOAPConstants.SOAP11_CONSTANTS); _call.setOperationName(new javax.xml.namespace.QName("urn:server", "wsGetProfil")); setRequestHeaders(_call); setAttachments(_call); try { Object _resp = _call.invoke(new Object[] { login, password }); if (_resp instanceof java.rmi.RemoteException) { throw (java.rmi.RemoteException) _resp; } else { extractAttachments(_call); try { return (String) _resp; } catch (Exception _exception) { return (String) org.apache.axis.utils.JavaUtils.convert(_resp, String.class); } } } catch (org.apache.axis.AxisFault axisFaultException) { throw axisFaultException; } } public String wsGetVersion(String login, String password) throws java.rmi.RemoteException { if (super.cachedEndpoint == null) { throw new org.apache.axis.NoEndPointException(); } org.apache.axis.client.Call _call = createCall(); _call.setOperation(_operations[2]); _call.setUseSOAPAction(true); _call.setSOAPActionURI("urn:WebServiceAction"); _call.setSOAPVersion(org.apache.axis.soap.SOAPConstants.SOAP11_CONSTANTS); _call.setOperationName(new javax.xml.namespace.QName("urn:server", "wsGetVersion")); setRequestHeaders(_call); setAttachments(_call); try { Object _resp = _call.invoke(new Object[] { login, password }); if (_resp instanceof java.rmi.RemoteException) { throw (java.rmi.RemoteException) _resp; } else { extractAttachments(_call); try { return (String) _resp; } catch (Exception _exception) { return (String) org.apache.axis.utils.JavaUtils.convert(_resp, String.class); } } } catch (org.apache.axis.AxisFault axisFaultException) { throw axisFaultException; } } public String wsGetMessage(String typeEchange, String typeMessage, String identifiantMessage, String login, String password) throws java.rmi.RemoteException { if (super.cachedEndpoint == null) { throw new org.apache.axis.NoEndPointException(); } org.apache.axis.client.Call _call = createCall(); _call.setOperation(_operations[3]); _call.setUseSOAPAction(true); _call.setSOAPActionURI("urn:WebServiceAction"); _call.setSOAPVersion(org.apache.axis.soap.SOAPConstants.SOAP11_CONSTANTS); _call.setOperationName(new javax.xml.namespace.QName("urn:server", "wsGetMessage")); setRequestHeaders(_call); setAttachments(_call); try { Object _resp = _call.invoke(new Object[] { typeEchange, typeMessage, identifiantMessage, login, password }); if (_resp instanceof java.rmi.RemoteException) { throw (java.rmi.RemoteException) _resp; } else { extractAttachments(_call); try { return (String) _resp; } catch (Exception _exception) { return (String) org.apache.axis.utils.JavaUtils.convert(_resp, String.class); } } } catch (org.apache.axis.AxisFault axisFaultException) { throw axisFaultException; } } /** * SAEM-80 Webservice pour la récupération des DUA expirées * @author romain.chiquois */ public Object wsGetDuaExpirees(String login, String password) throws java.rmi.RemoteException { if (super.cachedEndpoint == null) { throw new org.apache.axis.NoEndPointException(); } org.apache.axis.client.Call _call = createCall(); _call.setOperation(_operations[5]); _call.setUseSOAPAction(true); _call.setSOAPActionURI("urn:WebServiceAction"); _call.setSOAPVersion(org.apache.axis.soap.SOAPConstants.SOAP11_CONSTANTS); _call.setOperationName(new javax.xml.namespace.QName("urn:server", "wsGetDuaExpirees")); setRequestHeaders(_call); setAttachments(_call); try { Object _resp = _call.invoke(new Object[] {login, password}); if (_resp instanceof java.rmi.RemoteException) { throw (java.rmi.RemoteException)_resp; } else { extractAttachments(_call); return _resp; } } catch (org.apache.axis.AxisFault axisFaultException) { throw axisFaultException; } } /** * SAEM-80 Webservice de complétion du bordereau * @author romain.chiquois */ public byte[] wsCompleterBordereau(Object bordereau, String login, String password) { try{ if (super.cachedEndpoint == null) { throw new org.apache.axis.NoEndPointException(); } org.apache.axis.client.Call _call = createCall(); _call.setOperation(_operations[6]); _call.setUseSOAPAction(true); _call.setSOAPActionURI("urn:WebServiceAction"); _call.setSOAPVersion(org.apache.axis.soap.SOAPConstants.SOAP11_CONSTANTS); _call.setOperationName(new javax.xml.namespace.QName("urn:server", "wsCompleterBordereau")); setRequestHeaders(_call); setAttachments(_call); try { Object _resp = _call.invoke(new Object[] { bordereau, login, password }); if (_resp instanceof java.rmi.RemoteException) { throw (java.rmi.RemoteException) _resp; } else { extractAttachments(_call); try { return (byte[]) _resp; } catch (Exception _exception) { return (byte[]) org.apache.axis.utils.JavaUtils.convert( _resp, byte[].class); } } } catch (org.apache.axis.AxisFault axisFaultException) { throw axisFaultException; } } catch(Exception ex){ ex.printStackTrace(); } return null; } }
agpl-3.0
automenta/narchy
util/src/main/java/jcog/learn/decision/data/SimpleValue.java
1402
package jcog.learn.decision.data; import com.google.common.base.Preconditions; import com.google.common.collect.Maps; import org.jetbrains.annotations.Nullable; import java.util.Map; import java.util.function.Function; /** * * @author Ignas */ public final class SimpleValue<L> implements Function<String,L> { private final Map<String, L> values = Maps.newHashMap(); private SimpleValue(String[] header, L... dataValues) { super(); for (int i = 0; i < header.length; i++) { this.values.put(header[i], dataValues[i]); } } /** * Create data sample without labels which is used on trained tree. */ public static SimpleValue classification(String[] header, Object... values) { Preconditions.checkArgument(header.length == values.length); return new SimpleValue(header, values); } /** * @param header * @param values * @return */ public static SimpleValue data(String[] header, Object... values) { Preconditions.checkArgument(header.length == values.length); return new SimpleValue(header, values); } @Nullable @Override public L apply(String column) { return values.get(column); } /** * {@inheritDoc} */ @Override public String toString() { return "SimpleDataSample [values=" + values + ']'; } }
agpl-3.0
AAccount/dt_call_aclient
aclient/src/main/java/dt/call/aclient/Voip/SoundEffects.java
4783
package dt.call.aclient.Voip; /** * Created by Daniel on 12/22/19. * */ import android.content.Context; import android.media.AudioFormat; import android.media.AudioManager; import android.media.AudioTrack; import android.media.Ringtone; import android.media.RingtoneManager; import android.net.Uri; import android.os.Vibrator; import java.io.InputStream; import java.util.Timer; import java.util.TimerTask; import dt.call.aclient.Const; import dt.call.aclient.R; import dt.call.aclient.Utils; import dt.call.aclient.Vars; public class SoundEffects { private static final String tag = "Voip.SoundEffects"; private static final int DIAL_TONE_SIZE = 32000; private static final int END_TONE_SIZE = 10858; private static final int WAV_FILE_HEADER = 44; //.wav files actually have a 44 byte header private static final int S16 = AudioFormat.ENCODING_PCM_16BIT; private static final int STREAMCALL = AudioManager.STREAM_VOICE_CALL; private AudioManager audioManager; private AudioTrack dialTone = null; private Ringtone ringtone = null; private Vibrator vibrator = null; private static SoundEffects instance = null; public static SoundEffects getInstance() { if(instance == null) { instance = new SoundEffects(); } return instance; } private SoundEffects() { audioManager = (AudioManager) Vars.applicationContext.getSystemService(Context.AUDIO_SERVICE); } public void playDialtone() { audioManager.setMode(AudioManager.MODE_IN_COMMUNICATION); audioManager.setSpeakerphoneOn(false); byte[] dialToneDump = new byte[DIAL_TONE_SIZE]; //right click the file and get the exact size try { final InputStream dialToneStream = Vars.applicationContext.getResources().openRawResource(R.raw.dialtone8000); final int amount = dialToneStream.read(dialToneDump); final int actualSize = amount-WAV_FILE_HEADER; dialToneStream.close(); //only create the dial tone audio track if it's needed. otherwise it leaks resources if you create but never use it dialTone = new AudioTrack(STREAMCALL, 8000, AudioFormat.CHANNEL_OUT_MONO, S16, DIAL_TONE_SIZE, AudioTrack.MODE_STATIC); dialTone.write(dialToneDump, WAV_FILE_HEADER, actualSize); dialTone.setLoopPoints(0, actualSize/2, -1); dialTone.play(); } catch(Exception e) { Utils.dumpException(tag, e); } } public void stopDialtone() { if(dialTone != null) { dialTone.pause(); dialTone.flush(); dialTone.stop(); dialTone.release(); dialTone = null; } } public void playRingtone() { Utils.logcat(Const.LOGD, tag, "playing ringtone"); switch(audioManager.getRingerMode()) { case AudioManager.RINGER_MODE_NORMAL: Uri ringtoneUri = RingtoneManager.getDefaultUri(RingtoneManager.TYPE_RINGTONE); ringtone = RingtoneManager.getRingtone(Vars.applicationContext, ringtoneUri); ringtone.play(); break; case AudioManager.RINGER_MODE_VIBRATE: vibrator = (Vibrator)Vars.applicationContext.getSystemService(Context.VIBRATOR_SERVICE); if(vibrator == null) { break; } final long[] vibratePattern = new long[] {0, 400, 200}; vibrator.vibrate(vibratePattern, 0); break; //no need for the dead silent case. if it is dead silent just light up the screen with no nothing } //safety auto shutoff since it is being called from anywhere final TimerTask task = new TimerTask() { @Override public void run() { stopRingtone(); } }; final Timer timer = new Timer(); timer.schedule(task, Const.CALL_TIMEOUT*1000L); } public void stopRingtone() { Utils.logcat(Const.LOGD, tag, "stopping ringtone"); if(ringtone != null && ringtone.isPlaying()) { ringtone.stop(); ringtone = null; } if(vibrator != null) { vibrator.cancel(); vibrator = null; } } public void playEndTone() { try { final byte[] endToneDump = new byte[END_TONE_SIZE]; //right click the file and get the exact size final InputStream endToneStream = Vars.applicationContext.getResources().openRawResource(R.raw.end8000); final int amount = endToneStream.read(endToneDump); final int actualSize = amount - WAV_FILE_HEADER; endToneStream.close(); final AudioTrack endTonePlayer = new AudioTrack(STREAMCALL, 8000, AudioFormat.CHANNEL_OUT_MONO, S16, actualSize, AudioTrack.MODE_STATIC); endTonePlayer.write(endToneDump, WAV_FILE_HEADER, actualSize); endTonePlayer.play(); int playbackPos = endTonePlayer.getPlaybackHeadPosition(); while (playbackPos < actualSize / 2) { playbackPos = endTonePlayer.getPlaybackHeadPosition(); } endTonePlayer.pause(); endTonePlayer.flush(); endTonePlayer.stop(); endTonePlayer.release(); } catch (Exception e) { //nothing useful you can do if the notification end tone fails to play } } }
agpl-3.0
aborg0/rapidminer-vega
src/com/rapidminer/operator/preprocessing/sampling/PartitionOperator.java
7123
/* * RapidMiner * * Copyright (C) 2001-2011 by Rapid-I and the contributors * * Complete list of developers available at our web site: * * http://rapid-i.com * * 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/. */ package com.rapidminer.operator.preprocessing.sampling; import java.util.List; import com.rapidminer.example.ExampleSet; import com.rapidminer.example.set.SplittedExampleSet; import com.rapidminer.operator.Operator; import com.rapidminer.operator.OperatorDescription; import com.rapidminer.operator.OperatorException; import com.rapidminer.operator.SimpleProcessSetupError; import com.rapidminer.operator.ProcessSetupError.Severity; import com.rapidminer.operator.UserError; import com.rapidminer.operator.annotation.ResourceConsumptionEstimator; import com.rapidminer.operator.ports.InputPort; import com.rapidminer.operator.ports.OutputPort; import com.rapidminer.operator.ports.OutputPortExtender; import com.rapidminer.operator.ports.metadata.AttributeMetaData; import com.rapidminer.operator.ports.metadata.ExampleSetMetaData; import com.rapidminer.operator.ports.metadata.MetaData; import com.rapidminer.operator.ports.metadata.OneToManyPassThroughRule; import com.rapidminer.parameter.ParameterType; import com.rapidminer.parameter.ParameterTypeCategory; import com.rapidminer.parameter.ParameterTypeDouble; import com.rapidminer.parameter.ParameterTypeEnumeration; import com.rapidminer.parameter.UndefinedParameterError; import com.rapidminer.tools.OperatorResourceConsumptionHandler; import com.rapidminer.tools.RandomGenerator; /** * Divides a data set into the defined partitions and deliver the subsets. * * @author Tobias Malbrecht */ public class PartitionOperator extends Operator { public static final String PARAMETER_PARTITIONS = "partitions"; public static final String PARAMETER_RATIO = "ratio"; public static final String PARAMETER_SAMPLING_TYPE = "sampling_type"; private InputPort exampleSetInput = getInputPorts().createPort("example set", ExampleSet.class); private OutputPortExtender outExtender = new OutputPortExtender("partition", getOutputPorts()); public PartitionOperator(OperatorDescription description) { super(description); outExtender.start(); getTransformer().addRule(new OneToManyPassThroughRule(exampleSetInput, outExtender.getManagedPorts()) { @Override public void transformMD() { super.transformMD(); // check sanity of parameters try { String[] ratioList = ParameterTypeEnumeration.transformString2Enumeration(getParameterAsString(PARAMETER_PARTITIONS)); double[] ratios = new double[ratioList.length]; int i = 0; double sum = 0; for (String entry : ratioList) { ratios[i] = Double.valueOf(entry); sum += ratios[i]; i++; } if (sum != 1d) { addError(new SimpleProcessSetupError(Severity.WARNING, getPortOwner(), "parameter_enumeration_forbidden_sum", PARAMETER_PARTITIONS, "1")); } } catch (UndefinedParameterError e) { } catch (NumberFormatException e) {} } @Override public MetaData modifyMetaData(MetaData unmodifiedMetaData, int outputIndex) { if (unmodifiedMetaData instanceof ExampleSetMetaData) { try { unmodifiedMetaData = modifiyMetaData((ExampleSetMetaData) unmodifiedMetaData, outputIndex); } catch (UndefinedParameterError e) {} } return unmodifiedMetaData; } }); } protected ExampleSetMetaData modifiyMetaData(ExampleSetMetaData metaData, int outputIndex) throws UndefinedParameterError { if (metaData.getNumberOfExamples().isKnown()) { String[] ratioList = ParameterTypeEnumeration.transformString2Enumeration(getParameterAsString(PARAMETER_PARTITIONS)); double[] ratios = new double[ratioList.length]; if (outputIndex < ratios.length) { int i = 0; double sum = 0; for (String entry : ratioList) { ratios[i] = Double.valueOf(entry); sum += ratios[i]; i++; } metaData.setNumberOfExamples((int)(ratios[outputIndex] / sum * metaData.getNumberOfExamples().getValue())); for (AttributeMetaData amd: metaData.getAllAttributes()) { amd.getNumberOfMissingValues().reduceByUnknownAmount(); } } else return null; } return metaData; } @Override public void doWork() throws OperatorException { String[] ratioList = ParameterTypeEnumeration.transformString2Enumeration(getParameterAsString(PARAMETER_PARTITIONS)); if (ratioList.length == 0) { throw new UserError(this, 217, PARAMETER_PARTITIONS, getName(), ""); } double[] ratios = new double[ratioList.length]; int i = 0; double sum = 0; for (String entry : ratioList) { try { ratios[i] = Double.valueOf(entry); } catch(NumberFormatException e) { throw new UserError(this, 211, PARAMETER_PARTITIONS, entry); } sum += ratios[i]; i++; } for (int j = 0; j < ratios.length; j++) { ratios[j] /= sum; } ExampleSet originalSet = exampleSetInput.getData(); SplittedExampleSet e = new SplittedExampleSet(originalSet, ratios, getParameterAsInt(PARAMETER_SAMPLING_TYPE), getParameterAsBoolean(RandomGenerator.PARAMETER_USE_LOCAL_RANDOM_SEED), getParameterAsInt(RandomGenerator.PARAMETER_LOCAL_RANDOM_SEED)); List<OutputPort> outputs = outExtender.getManagedPorts(); for (int j = 0; j < ratioList.length; j++) { SplittedExampleSet b = (SplittedExampleSet) e.clone(); b.selectSingleSubset(j); if (outputs.size() > j) { outputs.get(j).deliver(b); } } } @Override public List<ParameterType> getParameterTypes() { List<ParameterType> types = super.getParameterTypes(); types.add(new ParameterTypeEnumeration(PARAMETER_PARTITIONS, "The partitions that should be created.", new ParameterTypeDouble(PARAMETER_RATIO, "The relative size of this partition.", 0, 1), false)); types.add(new ParameterTypeCategory(PARAMETER_SAMPLING_TYPE, "Defines the sampling type of this operator.", SplittedExampleSet.SAMPLING_NAMES, SplittedExampleSet.SHUFFLED_SAMPLING, false)); types.addAll(RandomGenerator.getRandomGeneratorParameters(this)); return types; } @Override public ResourceConsumptionEstimator getResourceConsumptionEstimator() { return OperatorResourceConsumptionHandler.getResourceConsumptionEstimator(getInputPorts().getPortByIndex(0), PartitionOperator.class, null); } }
agpl-3.0
objectuser/pneumatic
pneumatic-yaml-dsl/src/test/java/com/surgingsystems/etl/yamldsl/RestfulLookupFilterTest.java
1846
package com.surgingsystems.etl.yamldsl; import org.junit.Assert; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationContext; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.annotation.DirtiesContext.ClassMode; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import com.surgingsystems.etl.filter.RestfulLookupFilter; @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration({ "classpath:etl-context.xml" }) @DirtiesContext(classMode = ClassMode.AFTER_EACH_TEST_METHOD) public class RestfulLookupFilterTest { @Autowired private ApplicationContext applicationContext; @Autowired private YamlParser yamlParser; @Test public void parse() { yamlParser.parse("restful-lookup-test.yml"); RestfulLookupFilter restfulLookup = applicationContext.getBean("restfulLookup", RestfulLookupFilter.class); Assert.assertNotNull("Found the bean", restfulLookup); restfulLookup.validate(); Assert.assertNotNull("Name is set", restfulLookup.getName()); Assert.assertEquals("Name is right", "Test Restful Lookup", restfulLookup.getName()); Assert.assertNotNull("Request url is set", restfulLookup.getRequestUrl()); Assert.assertNotNull("Input is set", restfulLookup.getInput()); Assert.assertNotNull("Input schema is set", restfulLookup.getInputSchema()); Assert.assertNotNull("Output is set", restfulLookup.getOutput()); Assert.assertNotNull("Output schema is set", restfulLookup.getOutputSchema()); Assert.assertNotNull("Response schema is set", restfulLookup.getResponseSchema()); } }
agpl-3.0
haiqu/bitsquare
gui/src/test/java/io/bitsquare/gui/main/market/trades/TradesChartsViewModelTest.java
2732
package io.bitsquare.gui.main.market.trades; import io.bitsquare.gui.main.market.trades.charts.CandleData; import io.bitsquare.trade.offer.Offer; import io.bitsquare.trade.statistics.TradeStatistics; import org.bitcoinj.core.Coin; import org.bitcoinj.utils.Fiat; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Date; import java.util.HashSet; import java.util.Set; import static org.junit.Assert.assertEquals; public class TradesChartsViewModelTest { private static final Logger log = LoggerFactory.getLogger(TradesChartsViewModelTest.class); @Test public void testGetCandleData() { TradesChartsViewModel model = new TradesChartsViewModel(); long low = Fiat.parseFiat("EUR", "500").value; long open = Fiat.parseFiat("EUR", "520").value; long close = Fiat.parseFiat("EUR", "580").value; long high = Fiat.parseFiat("EUR", "600").value; long average = Fiat.parseFiat("EUR", "550").value; long amount = Coin.parseCoin("4").value; long volume = Fiat.parseFiat("EUR", "2200").value; boolean isBullish = true; Set<TradeStatistics> set = new HashSet<>(); final Date now = new Date(); Offer offer = new Offer(null, null, null, null, 0, 0, false, 0, 0, "EUR", null, null, null, null, null, null, null, null); set.add(new TradeStatistics(offer, Fiat.parseFiat("EUR", "520"), Coin.parseCoin("1"), new Date(now.getTime()), null, null)); set.add(new TradeStatistics(offer, Fiat.parseFiat("EUR", "500"), Coin.parseCoin("1"), new Date(now.getTime() + 100), null, null)); set.add(new TradeStatistics(offer, Fiat.parseFiat("EUR", "600"), Coin.parseCoin("1"), new Date(now.getTime() + 200), null, null)); set.add(new TradeStatistics(offer, Fiat.parseFiat("EUR", "580"), Coin.parseCoin("1"), new Date(now.getTime() + 300), null, null)); CandleData candleData = model.getCandleData(model.getTickFromTime(now.getTime(), TradesChartsViewModel.TickUnit.DAY), set); assertEquals(open, candleData.open); assertEquals(close, candleData.close); assertEquals(high, candleData.high); assertEquals(low, candleData.low); assertEquals(average, candleData.average); assertEquals(amount, candleData.accumulatedAmount); assertEquals(volume, candleData.accumulatedVolume); assertEquals(isBullish, candleData.isBullish); } }
agpl-3.0
splicemachine/spliceengine
db-engine/src/main/java/com/splicemachine/db/impl/sql/compile/RemapCRsForJoinVisitor.java
3847
/* * This file is part of Splice Machine. * Splice Machine 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, or (at your option) any later version. * Splice Machine 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 Splice Machine. * If not, see <http://www.gnu.org/licenses/>. * * Some parts of this source code are based on Apache Derby, and the following notices apply to * Apache Derby: * * Apache Derby is a subproject of the Apache DB project, and is licensed under * the Apache License, Version 2.0 (the "License"); you may not use these files * 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. * * Splice Machine, Inc. has modified the Apache Derby code in this file. * * All such Splice Machine modifications are Copyright 2012 - 2021 Splice Machine, Inc., * and are licensed to you under the GNU Affero General Public License. */ package com.splicemachine.db.impl.sql.compile; import com.splicemachine.db.iapi.sql.compile.Visitable; import com.splicemachine.db.iapi.sql.compile.Visitor; import com.splicemachine.db.iapi.error.StandardException; import static com.splicemachine.db.impl.sql.compile.ColumnReference.isBaseRowIdOrRowId; /** * Remap ROWID or BASEROWID ColumnReference nodes in ResultColumnLists * if they refer to a JoinNode, so they refer to the original source column. * */ public class RemapCRsForJoinVisitor implements Visitor { public RemapCRsForJoinVisitor() { } public Visitable visit(Visitable node, QueryTreeNode parent) throws StandardException { if (node instanceof ColumnReference) { ColumnReference cr = (ColumnReference)node; if (!isBaseRowIdOrRowId(cr.getColumnName())) return node; ResultColumn resultColumn = cr.getSource(); if (resultColumn != null) { if (resultColumn.getExpression() instanceof VirtualColumnNode) { VirtualColumnNode vcn = (VirtualColumnNode) resultColumn.getExpression(); if (vcn.getSourceResultSet() instanceof JoinNode) { // Remap twice to get to the left or right source of // the join. cr.remapColumnReferences(); cr.remapColumnReferences(); } } } } return node; } /** * No need to go below a SubqueryNode. * * @return Whether or not to go below the node. */ public boolean skipChildren(Visitable node) { return ((node instanceof ColumnReference) || (node instanceof SubqueryNode)); } public boolean visitChildrenFirst(Visitable node) { return false; } public boolean stopTraversal() { return false; } //////////////////////////////////////////////// // // CLASS INTERFACE // //////////////////////////////////////////////// }
agpl-3.0
RestComm/jss7
tcap-ansi/tcap-ansi-impl/src/test/java/org/restcomm/protocols/ss7/tcapAnsi/asn/DialogPortionTest.java
6033
/* * TeleStax, Open Source Cloud Communications Copyright 2012. * and individual contributors * by the @authors tag. See the copyright.txt in the distribution for a * full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.restcomm.protocols.ss7.tcapAnsi.asn; import static org.testng.Assert.*; import java.util.Arrays; import org.mobicents.protocols.asn.AsnInputStream; import org.mobicents.protocols.asn.AsnOutputStream; import org.mobicents.protocols.asn.Tag; import org.restcomm.protocols.ss7.tcapAnsi.api.asn.ApplicationContext; import org.restcomm.protocols.ss7.tcapAnsi.api.asn.Confidentiality; import org.restcomm.protocols.ss7.tcapAnsi.api.asn.DialogPortion; import org.restcomm.protocols.ss7.tcapAnsi.api.asn.ProtocolVersion; import org.restcomm.protocols.ss7.tcapAnsi.api.asn.SecurityContext; import org.restcomm.protocols.ss7.tcapAnsi.api.asn.UserInformation; import org.restcomm.protocols.ss7.tcapAnsi.api.asn.UserInformationElement; import org.restcomm.protocols.ss7.tcapAnsi.asn.ConfidentialityImpl; import org.restcomm.protocols.ss7.tcapAnsi.asn.SecurityContextImpl; import org.restcomm.protocols.ss7.tcapAnsi.asn.TcapFactory; import org.restcomm.protocols.ss7.tcapAnsi.asn.UserInformationElementImpl; import org.testng.annotations.Test; /** * * @author sergey vetyutnev * */ @Test(groups = { "asn" }) public class DialogPortionTest { private byte[] data1 = new byte[] { -7, 33, -38, 1, 3, -3, 20, 40, 18, 6, 7, 4, 0, 0, 1, 1, 1, 1, -96, 7, 1, 2, 3, 4, 5, 6, 7, -128, 1, 10, -94, 3, -128, 1, 20 }; private byte[] data2 = new byte[] { -7, 11, -37, 1, 30, -127, 1, 42, -94, 3, -127, 1, 44 }; private byte[] dataValue = new byte[] { 1, 2, 3, 4, 5, 6, 7 }; @Test(groups = { "functional.decode" }) public void testDecode() throws Exception { // 1 AsnInputStream ais = new AsnInputStream(this.data1); int tag = ais.readTag(); assertEquals(tag, DialogPortion._TAG_DIALOG_PORTION); assertEquals(ais.getTagClass(), Tag.CLASS_PRIVATE); DialogPortion dp = TcapFactory.createDialogPortion(); dp.decode(ais); assertNull(dp.getApplicationContext()); assertTrue(dp.getProtocolVersion().isT1_114_2000Supported()); UserInformation ui = dp.getUserInformation(); assertTrue(Arrays.equals(new long[] { 0, 4, 0, 0, 1, 1, 1, 1 }, ui.getUserInformationElements()[0].getOidValue())); assertEquals(dataValue, ui.getUserInformationElements()[0].getEncodeType()); SecurityContext sc = dp.getSecurityContext(); assertEquals((long) sc.getIntegerSecurityId(), 10); Confidentiality con = dp.getConfidentiality(); assertEquals((long) con.getIntegerConfidentialityId(), 20); // 2 ais = new AsnInputStream(this.data2); tag = ais.readTag(); assertEquals(tag, DialogPortion._TAG_DIALOG_PORTION); assertEquals(ais.getTagClass(), Tag.CLASS_PRIVATE); dp = TcapFactory.createDialogPortion(); dp.decode(ais); assertNull(dp.getProtocolVersion()); assertEquals(dp.getApplicationContext().getInteger(), 30); assertNull(dp.getUserInformation()); sc = dp.getSecurityContext(); assertTrue(Arrays.equals(sc.getObjectSecurityId(), new long[] { 1, 2 })); con = dp.getConfidentiality(); assertTrue(Arrays.equals(con.getObjectConfidentialityId(), new long[] { 1, 4 })); } @Test(groups = { "functional.encode" }) public void testEncode() throws Exception { // 1 DialogPortion dp = TcapFactory.createDialogPortion(); ProtocolVersion pv = TcapFactory.createProtocolVersionFull(); dp.setProtocolVersion(pv); UserInformation ui = TcapFactory.createUserInformation(); UserInformationElement[] uie = new UserInformationElement[1]; uie[0] = new UserInformationElementImpl(); uie[0].setOid(true); uie[0].setOidValue(new long[] { 0, 4, 0, 0, 1, 1, 1, 1 }); uie[0].setAsn(true); uie[0].setEncodeType(dataValue); ui.setUserInformationElements(uie); dp.setUserInformation(ui); SecurityContext sc = new SecurityContextImpl(); sc.setIntegerSecurityId(10L); dp.setSecurityContext(sc); Confidentiality con = new ConfidentialityImpl(); con.setIntegerConfidentialityId(20L); dp.setConfidentiality(con); AsnOutputStream aos = new AsnOutputStream(); dp.encode(aos); byte[] encodedData = aos.toByteArray(); byte[] expectedData = data1; assertEquals(encodedData, expectedData); // 2 dp = TcapFactory.createDialogPortion(); ApplicationContext ac = TcapFactory.createApplicationContext(30); dp.setApplicationContext(ac); sc = new SecurityContextImpl(); sc.setObjectSecurityId(new long[] { 1, 2 }); dp.setSecurityContext(sc); con = new ConfidentialityImpl(); con.setObjectConfidentialityId(new long[] { 1, 4 }); dp.setConfidentiality(con); aos = new AsnOutputStream(); dp.encode(aos); encodedData = aos.toByteArray(); expectedData = data2; assertEquals(encodedData, expectedData); } }
agpl-3.0
o2oa/o2oa
o2server/x_processplatform_assemble_bam/src/main/java/com/x/processplatform/assemble/bam/jaxrs/state/TimerOrganization.java
9789
package com.x.processplatform.assemble.bam.jaxrs.state; import java.util.ArrayList; import java.util.Comparator; import java.util.Date; import java.util.List; import java.util.stream.Collectors; import javax.persistence.EntityManager; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.CriteriaQuery; import javax.persistence.criteria.Predicate; import javax.persistence.criteria.Root; import com.x.processplatform.assemble.bam.Business; import com.x.processplatform.assemble.bam.ThisApplication; import com.x.processplatform.assemble.bam.stub.PersonStub; import com.x.processplatform.assemble.bam.stub.UnitStub; import com.x.processplatform.core.entity.content.Task; import com.x.processplatform.core.entity.content.TaskCompleted; import com.x.processplatform.core.entity.content.TaskCompleted_; import com.x.processplatform.core.entity.content.Task_; public class TimerOrganization extends ActionBase { public void execute(Business business) throws Exception { ActionOrganization.Wo wo = new ActionOrganization.Wo(); Date start = this.getStart(); Date current = new Date(); wo.setUnit(this.unit(business, start, current)); wo.setPerson(this.person(business, start, current)); ThisApplication.state.setOrganization(wo); } private List<ActionOrganization.WoUnit> unit(Business business, Date start, Date current) throws Exception { List<ActionOrganization.WoUnit> list = new ArrayList<>(); for (UnitStub stub : ThisApplication.state.getUnitStubs()) { List<String> us = new ArrayList<>(); us.add(stub.getValue()); us.addAll(business.organization().unit().listWithUnitSubNested(stub.getValue())); Long count = this.countWithUnit(business, start, us); Long expiredCount = this.countExpiredWithUnit(business, start, current, us); Long duration = this.durationWithUnit(business, start, current, us); Long completedCount = this.countCompletedWithUnit(business, start, us); Long completedExpiredCount = this.countExpiredCompletedWithUnit(business, start, us); ActionOrganization.WoUnit wo = new ActionOrganization.WoUnit(); wo.setName(stub.getName()); wo.setValue(stub.getValue()); wo.setCount(count); wo.setExpiredCount(expiredCount); wo.setDuration(duration); wo.setCompletedCount(completedCount); wo.setCompletedExpiredCount(completedExpiredCount); list.add(wo); } return list; } private Long countWithUnit(Business business, Date start, List<String> units) throws Exception { EntityManager em = business.entityManagerContainer().get(Task.class); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Long> cq = cb.createQuery(Long.class); Root<Task> root = cq.from(Task.class); Predicate p = cb.greaterThan(root.get(Task_.startTime), start); p = cb.and(p, root.get(Task_.unit).in(units)); cq.select(cb.count(root)).where(p); return em.createQuery(cq).getSingleResult(); } private Long countExpiredWithUnit(Business business, Date start, Date current, List<String> units) throws Exception { EntityManager em = business.entityManagerContainer().get(Task.class); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Long> cq = cb.createQuery(Long.class); Root<Task> root = cq.from(Task.class); Predicate p = cb.greaterThan(root.get(Task_.startTime), start); p = cb.and(p, cb.lessThan(root.get(Task_.expireTime), current)); p = cb.and(p, root.get(Task_.unit).in(units)); cq.select(cb.count(root)).where(p); return em.createQuery(cq).getSingleResult(); } private Long durationWithUnit(Business business, Date start, Date current, List<String> units) throws Exception { EntityManager em = business.entityManagerContainer().get(Task.class); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Date> cq = cb.createQuery(Date.class); Root<Task> root = cq.from(Task.class); Predicate p = cb.greaterThan(root.get(Task_.startTime), start); p = cb.and(p, root.get(Task_.unit).in(units)); cq.select(root.get(Task_.startTime)).where(p); List<Date> os = em.createQuery(cq).getResultList(); long duration = 0; for (Date o : os) { duration += current.getTime() - o.getTime(); } /** 转化为分钟 */ duration = duration / (1000L * 60L); return duration; } private Long countCompletedWithUnit(Business business, Date start, List<String> units) throws Exception { EntityManager em = business.entityManagerContainer().get(TaskCompleted.class); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Long> cq = cb.createQuery(Long.class); Root<TaskCompleted> root = cq.from(TaskCompleted.class); Predicate p = cb.greaterThan(root.get(TaskCompleted_.completedTime), start); p = cb.and(p, root.get(TaskCompleted_.unit).in(units)); cq.select(cb.count(root)).where(p); return em.createQuery(cq).getSingleResult(); } private Long countExpiredCompletedWithUnit(Business business, Date start, List<String> units) throws Exception { EntityManager em = business.entityManagerContainer().get(TaskCompleted.class); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Long> cq = cb.createQuery(Long.class); Root<TaskCompleted> root = cq.from(TaskCompleted.class); Predicate p = cb.greaterThan(root.get(TaskCompleted_.completedTime), start); p = cb.and(p, root.get(TaskCompleted_.unit).in(units)); p = cb.and(p, cb.equal(root.get(TaskCompleted_.expired), true)); cq.select(cb.count(root)).where(p); return em.createQuery(cq).getSingleResult(); } private List<ActionOrganization.WoPerson> person(Business business, Date start, Date current) throws Exception { List<ActionOrganization.WoPerson> list = new ArrayList<>(); for (PersonStub stub : ThisApplication.state.getPersonStubs()) { Long count = this.countWithPerson(business, start, stub.getValue()); Long expiredCount = this.countExpiredWithPerson(business, start, current, stub.getValue()); Long duration = this.durationWithPerson(business, start, current, stub.getValue()); Long completedCount = this.countCompletedWithPerson(business, start, stub.getValue()); Long completedExpiredCount = this.countExpiredCompletedWithPerson(business, start, stub.getValue()); ActionOrganization.WoPerson wo = new ActionOrganization.WoPerson(); wo.setName(stub.getName()); wo.setValue(stub.getValue()); wo.setCount(count); wo.setExpiredCount(expiredCount); wo.setDuration(duration); wo.setCompletedCount(completedCount); wo.setCompletedExpiredCount(completedExpiredCount); list.add(wo); } list = list.stream().sorted( Comparator.comparing(ActionOrganization.WoPerson::getCount, Comparator.nullsLast(Long::compareTo))) .collect(Collectors.toList()); return list; } private Long countWithPerson(Business business, Date start, String person) throws Exception { EntityManager em = business.entityManagerContainer().get(Task.class); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Long> cq = cb.createQuery(Long.class); Root<Task> root = cq.from(Task.class); Predicate p = cb.greaterThan(root.get(Task_.startTime), start); p = cb.and(p, cb.equal(root.get(Task_.person), person)); cq.select(cb.count(root)).where(p); return em.createQuery(cq).getSingleResult(); } private Long countExpiredWithPerson(Business business, Date start, Date current, String person) throws Exception { EntityManager em = business.entityManagerContainer().get(Task.class); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Long> cq = cb.createQuery(Long.class); Root<Task> root = cq.from(Task.class); Predicate p = cb.greaterThan(root.get(Task_.startTime), start); p = cb.and(p, cb.equal(root.get(Task_.person), person)); p = cb.and(p, cb.lessThan(root.get(Task_.expireTime), current)); cq.select(cb.count(root)).where(p); return em.createQuery(cq).getSingleResult(); } private Long durationWithPerson(Business business, Date start, Date current, String person) throws Exception { EntityManager em = business.entityManagerContainer().get(Task.class); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Date> cq = cb.createQuery(Date.class); Root<Task> root = cq.from(Task.class); Predicate p = cb.greaterThan(root.get(Task_.startTime), start); p = cb.and(p, cb.equal(root.get(Task_.person), person)); cq.select(root.get(Task_.startTime)).where(p); List<Date> os = em.createQuery(cq).getResultList(); long duration = 0; for (Date o : os) { duration += current.getTime() - o.getTime(); } duration = duration / (1000L * 60L); return duration; } private Long countCompletedWithPerson(Business business, Date start, String person) throws Exception { EntityManager em = business.entityManagerContainer().get(TaskCompleted.class); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Long> cq = cb.createQuery(Long.class); Root<TaskCompleted> root = cq.from(TaskCompleted.class); Predicate p = cb.greaterThan(root.get(TaskCompleted_.completedTime), start); p = cb.and(p, cb.equal(root.get(TaskCompleted_.person), person)); cq.select(cb.count(root)).where(p); return em.createQuery(cq).getSingleResult(); } private Long countExpiredCompletedWithPerson(Business business, Date start, String person) throws Exception { EntityManager em = business.entityManagerContainer().get(TaskCompleted.class); CriteriaBuilder cb = em.getCriteriaBuilder(); CriteriaQuery<Long> cq = cb.createQuery(Long.class); Root<TaskCompleted> root = cq.from(TaskCompleted.class); Predicate p = cb.greaterThan(root.get(TaskCompleted_.completedTime), start); p = cb.and(p, cb.equal(root.get(TaskCompleted_.person), person)); p = cb.and(p, cb.equal(root.get(TaskCompleted_.expired), true)); cq.select(cb.count(root)).where(p); return em.createQuery(cq).getSingleResult(); } }
agpl-3.0
b1acKr0se/bridddle-for-dribbble
app/src/main/java/io/b1ackr0se/bridddle/ui/common/ShotViewHolder.java
609
package io.b1ackr0se.bridddle.ui.common; import android.support.v7.widget.RecyclerView; import android.view.View; import android.widget.TextView; import butterknife.BindView; import butterknife.ButterKnife; import io.b1ackr0se.bridddle.R; import io.b1ackr0se.bridddle.ui.widget.AspectRatioImageView; public class ShotViewHolder extends RecyclerView.ViewHolder { @BindView(R.id.shot_image) AspectRatioImageView shotImageView; @BindView(R.id.gif_indicator) TextView gifIndicator; public ShotViewHolder(View itemView) { super(itemView); ButterKnife.bind(this, itemView); } }
agpl-3.0
automenta/java_dann
src/syncleus/dann/evolve/score/parallel/ParallelScore.java
4916
/* * Encog(tm) Core v3.2 - Java Version * http://www.heatonresearch.com/encog/ * https://github.com/encog/encog-java-core * Copyright 2008-2013 Heaton Research, 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. * * For more information on Heaton Research copyrights, licenses * and trademarks visit: * http://www.heatonresearch.com/copyright */ package syncleus.dann.evolve.score.parallel; import java.util.List; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import org.encog.util.concurrency.MultiThreadable; import syncleus.dann.evolve.GeneticError; import syncleus.dann.evolve.codec.GeneticCODEC; import syncleus.dann.evolve.genome.Genome; import syncleus.dann.evolve.population.Population; import syncleus.dann.evolve.score.AdjustScore; import syncleus.dann.evolve.species.Species; import syncleus.dann.learn.ScoreLearning; /** * This class is used to calculate the scores for an entire population. This is * typically done when a new population must be scored for the first time. */ public class ParallelScore implements MultiThreadable { /** * The population to score. */ private final Population population; /** * The CODEC used to create genomes. */ private final GeneticCODEC codec; /** * The scoring function. */ private final ScoreLearning scoreFunction; /** * The score adjuster. */ private final List<AdjustScore> adjusters; /** * The number of requested threads. */ private int threads; /** * The actual number of threads. */ private int actualThreads; /** * Construct the parallel score calculation object. * * @param thePopulation The population to score. * @param theCODEC The CODEC to use. * @param theAdjusters The score adjusters to use. * @param theScoreFunction The score function. * @param theThreadCount The requested thread count. */ public ParallelScore(final Population thePopulation, final GeneticCODEC theCODEC, final List<AdjustScore> theAdjusters, final ScoreLearning theScoreFunction, final int theThreadCount) { this.codec = theCODEC; this.population = thePopulation; this.scoreFunction = theScoreFunction; this.adjusters = theAdjusters; this.actualThreads = 0; } /** * @return the population */ public Population getPopulation() { return population; } /** * @return the scoreFunction */ public ScoreLearning getScoreFunction() { return scoreFunction; } /** * @return the codec */ public GeneticCODEC getCodec() { return codec; } /** * Calculate the scores. */ public void process() { // determine thread usage if (this.scoreFunction.requireSingleThreaded()) { this.actualThreads = 1; } else if (threads == 0) { this.actualThreads = Runtime.getRuntime().availableProcessors(); } else { this.actualThreads = threads; } // start up ExecutorService taskExecutor = null; if (this.threads == 1) { taskExecutor = Executors.newSingleThreadScheduledExecutor(); } else { taskExecutor = Executors.newFixedThreadPool(this.actualThreads); } for (final Species species : this.population.getSpecies()) { for (final Genome genome : species.getMembers()) { taskExecutor.execute(new ParallelScoreTask(genome, this)); } } taskExecutor.shutdown(); try { taskExecutor.awaitTermination(Long.MAX_VALUE, TimeUnit.MINUTES); } catch (final InterruptedException e) { throw new GeneticError(e); } } /** * @return The score adjusters. */ public List<AdjustScore> getAdjusters() { return this.adjusters; } /** * @return The desired number of threads. */ @Override public int getThreadCount() { return this.threads; } /** * @param numThreads The desired thread count. */ @Override public void setThreadCount(final int numThreads) { this.threads = numThreads; } }
agpl-3.0
CecileBONIN/Silverpeas-Core
lib-core/src/test/java/org/silverpeas/process/io/file/AbstractHandledFileTest.java
7895
/* * Copyright (C) 2000 - 2013 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 recieved a copy of the text describing * the FLOSS exception, and it is also available here: * "http://www.silverpeas.org/docs/core/legal/floss_exception.html" * * 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 org.silverpeas.process.io.file; import java.io.File; import org.apache.commons.io.FileUtils; import org.junit.After; import org.junit.Before; import org.silverpeas.process.session.ProcessSession; import static com.stratelia.webactiv.util.GeneralPropertiesManager.getString; import static org.apache.commons.io.FileUtils.*; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; /** * @author Yohann Chastagnier */ public abstract class AbstractHandledFileTest { protected static final FileBasePath BASE_PATH_TEST = FileBasePath.UPLOAD_PATH; protected static final ProcessSession currentSession = createSessionTest(); protected static final String componentInstanceId = "componentInstanceId"; protected static final File sessionRootPath = new File(getString("tempPath")); protected static final File realRootPath = new File(BASE_PATH_TEST.getPath()); protected static final File otherFile = new File( new File(BASE_PATH_TEST.getPath()).getParentFile(), "other"); protected static final File sessionHandledPath = FileUtils.getFile(sessionRootPath, currentSession.getId(), BASE_PATH_TEST.getHandledNodeName()); protected static final File realComponentPath = FileUtils.getFile(realRootPath, componentInstanceId); protected static final File sessionComponentPath = FileUtils.getFile(sessionRootPath, currentSession.getId(), BASE_PATH_TEST.getHandledNodeName(), componentInstanceId); protected FileHandler fileHandler; @Before public void beforeTest() throws Exception { cleanTest(); fileHandler = new FileHandler(currentSession); realComponentPath.mkdirs(); sessionComponentPath.mkdirs(); touch(otherFile); } @After public void afterTest() throws Exception { cleanTest(); } /** * Cleaning files handled by a test */ private void cleanTest() { deleteQuietly(sessionRootPath); deleteQuietly(realRootPath); deleteQuietly(otherFile); } /** * --> SESSION * /sessionPath/handledPath/root_file_2 * /sessionPath/handledPath/root_file_3 * /sessionPath/handledPath/componentInstanceId/file_1 * /sessionPath/handledPath/componentInstanceId/a/b/file_ab_1 * /sessionPath/handledPath/componentInstanceId/a/b/file_ab_2.xml * /sessionPath/handledPath/componentInstanceId/a/b/c/file_abc_3 * /sessionPath/handledPath/componentInstanceId/b/file_b_2 * --> REAL * /root_file_1 * /root_file_2 * /componentInstanceId/file_1 * /componentInstanceId/file_2 * /componentInstanceId/a/file_a_1 * /componentInstanceId/a/file_a_2 - * /componentInstanceId/a/file_a_3.xml * /componentInstanceId/a/b/file_ab_1 - * /componentInstanceId/a/b/file_ab_2.xml - * /componentInstanceId/a/b/c/file_abc_1 - * /componentInstanceId/a/b/c/file_abc_2 - * /componentInstanceId/b/file_b_1 * /componentInstanceId/b/c/file_bc_1.test * /componentInstanceId/b/c/d/file_bcd_1 - * --> DELETED * /componentInstanceId/a/file_a_2 * /componentInstanceId/a/b/ * /componentInstanceId/b/c/d/ */ protected void buildCommonPathStructure() throws Exception { // --> SESSION createSessionFile(FileUtils.getFile(sessionHandledPath, "root_file_2")); createSessionFile(FileUtils.getFile(sessionHandledPath, "root_file_3")); createSessionFile(FileUtils.getFile(sessionComponentPath, "file_1")); createSessionFile(FileUtils.getFile(sessionComponentPath, "a/b/file_ab_1")); createSessionFile(FileUtils.getFile(sessionComponentPath, "a/b/file_ab_2.xml")); createSessionFile(FileUtils.getFile(sessionComponentPath, "a/b/c/file_abc_3")); createSessionFile(FileUtils.getFile(sessionComponentPath, "b/file_b_2")); // --> REAL createFile(FileUtils.getFile(realRootPath, "root_file_1")); createFile(FileUtils.getFile(realRootPath, "root_file_2")); createFile(FileUtils.getFile(realComponentPath, "file_1")); createFile(FileUtils.getFile(realComponentPath, "file_2")); createFile(FileUtils.getFile(realComponentPath, "a/file_a_1")); createFile(FileUtils.getFile(realComponentPath, "a/file_a_2")); createFile(FileUtils.getFile(realComponentPath, "a/file_a_3.xml")); createFile(FileUtils.getFile(realComponentPath, "a/b/file_ab_1")); createFile(FileUtils.getFile(realComponentPath, "a/b/file_ab_2.xml")); createFile(FileUtils.getFile(realComponentPath, "a/b/c/file_abc_1")); createFile(FileUtils.getFile(realComponentPath, "a/b/c/file_abc_2")); createFile(FileUtils.getFile(realComponentPath, "b/file_b_1")); createFile(FileUtils.getFile(realComponentPath, "b/c/file_bc_1.test")); createFile(FileUtils.getFile(realComponentPath, "b/c/d/file_bcd_1")); assertSizes(124, 136); fileHandler.markToDelete(BASE_PATH_TEST, FileUtils.getFile(realComponentPath, "a", "file_a_2")); fileHandler.markToDelete(BASE_PATH_TEST, FileUtils.getFile(realComponentPath, "a/b")); fileHandler.markToDelete(BASE_PATH_TEST, FileUtils.getFile(realComponentPath, "b/c/d")); assertSizes(64, 136); assertThat( FileUtils.getFile(sessionRootPath, currentSession.getId(), "@#@work@#@", "temporaryFile") .exists(), is(false)); writeStringToFile(fileHandler.getSessionTemporaryFile("temporaryFile"), "this is a session temporary file !"); assertThat( FileUtils.getFile(sessionRootPath, currentSession.getId(), "@#@work@#@", "temporaryFile") .exists(), is(true)); assertSizes(64, 136); } private void createSessionFile(final File file) throws Exception { writeStringToFile(file, file.getName() + "_session"); } private void createFile(final File file) throws Exception { writeStringToFile(file, file.getName()); } /** * Centralizes common code * @param sessionSize * @param realSize */ protected void assertSizes(final long sessionSize, final long realSize) { assertThat(fileHandler.sizeOfSessionWorkingPath(), is(sessionSize)); assertThat(sizeOf(realRootPath), is(realSize)); } /** * Centralizes asserts * @param test * @param expected */ protected void assertFileNames(final File test, final File expected) { assertThat(test, is(expected)); } protected static ProcessSession createSessionTest() { return new ProcessSession() { @Override public void setAttribute(final String name, final Object value) { } @Override public String getId() { return "sessionPathId"; } @Override public Object getAttribute(final String name) { return null; } @Override public <C> C getAttribute(final String name, final Class<C> expectedReturnedClass) { return null; } }; } }
agpl-3.0
fharias/purplecore
jpos/src/main/java/org/jpos/q2/iso/MUXPool.java
4611
/* * jPOS Project [http://jpos.org] * Copyright (C) 2000-2013 Alejandro P. Revilla * * 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/>. */ package org.jpos.q2.iso; import org.jdom.Element; import org.jpos.core.ConfigurationException; import org.jpos.iso.*; import org.jpos.q2.QBeanSupport; import org.jpos.util.NameRegistrar; import java.util.StringTokenizer; /** * @author apr */ public class MUXPool extends QBeanSupport implements MUX { int strategy = 0; String[] muxName; MUX[] mux; int msgno = 0; public static final int ROUND_ROBIN = 1; public static final int PRIMARY_SECONDARY = 0; public void initService () throws ConfigurationException { Element e = getPersist (); muxName = toStringArray(e.getChildTextTrim ("muxes")); String s = e.getChildTextTrim ("strategy"); strategy = "round-robin".equals (s) ? ROUND_ROBIN : PRIMARY_SECONDARY; mux = new MUX[muxName.length]; try { for (int i=0; i<mux.length; i++) mux[i] = QMUX.getMUX (muxName[i]); } catch (NameRegistrar.NotFoundException ex) { throw new ConfigurationException (ex); } NameRegistrar.register ("mux."+getName (), this); } public void stopService () { NameRegistrar.unregister ("mux."+getName ()); } public ISOMsg request (ISOMsg m, long timeout) throws ISOException { int mnumber = 0; long maxWait = System.currentTimeMillis() + timeout; synchronized (this) { mnumber = msgno++; } MUX mux = strategy == ROUND_ROBIN ? nextAvailableMUX (mnumber, maxWait) : firstAvailableMUX (maxWait); if (mux != null) { timeout = maxWait - System.currentTimeMillis(); if (timeout >= 0) return mux.request (m, timeout); } return null; } public boolean isConnected() { for (int i=0; i<mux.length; i++) if (mux[i].isConnected()) return true; return false; } private MUX firstAvailableMUX (long maxWait) { do { for (int i=0; i<mux.length; i++) if (mux[i].isConnected()) return mux[i]; ISOUtil.sleep (1000); } while (System.currentTimeMillis() < maxWait); return null; } private MUX nextAvailableMUX (int mnumber, long maxWait) { do { for (int i=0; i<mux.length; i++) { int j = (mnumber+i) % mux.length; if (mux[j].isConnected()) return mux[j]; } ISOUtil.sleep (1000); } while (System.currentTimeMillis() < maxWait); return null; } private String[] toStringArray (String s) { String[] ss = null; if (s != null && s.length() > 0) { StringTokenizer st = new StringTokenizer (s); ss = new String[st.countTokens()]; for (int i=0; st.hasMoreTokens(); i++) ss[i] = st.nextToken(); } return ss; } public void request (ISOMsg m, long timeout, final ISOResponseListener r, final Object handBack) throws ISOException { int mnumber = 0; long maxWait = System.currentTimeMillis() + timeout; synchronized (this) { mnumber = msgno++; } MUX mux = strategy == ROUND_ROBIN ? nextAvailableMUX (mnumber, maxWait) : firstAvailableMUX (maxWait); if (mux != null) { timeout = maxWait - System.currentTimeMillis(); if (timeout >= 0) mux.request(m, timeout,r, handBack); else { new Thread() { public void run() { r.expired (handBack); } }.start(); } } else throw new ISOException ("No MUX available"); } }
agpl-3.0
boob-sbcm/3838438
src/generated/java/com/rapid_i/repository/wsimport/SetAccessRightsResponse.java
2308
/** * Copyright (C) 2001-2017 by RapidMiner and the contributors * * Complete list of developers available at our web site: * * http://rapidminer.com * * 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/. */ package com.rapid_i.repository.wsimport; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for setAccessRightsResponse complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="setAccessRightsResponse"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="return" type="{http://service.web.rapidanalytics.de/}response" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "setAccessRightsResponse", propOrder = { "_return" }) public class SetAccessRightsResponse { @XmlElement(name = "return") protected Response _return; /** * Gets the value of the return property. * * @return * possible object is * {@link Response } * */ public Response getReturn() { return _return; } /** * Sets the value of the return property. * * @param value * allowed object is * {@link Response } * */ public void setReturn(Response value) { this._return = value; } }
agpl-3.0
ProtocolSupport/ProtocolSupport
src/protocolsupport/protocol/types/networkentity/metadata/objects/NetworkEntityMetadataObjectItemStack.java
712
package protocolsupport.protocol.types.networkentity.metadata.objects; import io.netty.buffer.ByteBuf; import protocolsupport.api.ProtocolVersion; import protocolsupport.protocol.codec.ItemStackCodec; import protocolsupport.protocol.types.NetworkItemStack; import protocolsupport.protocol.types.networkentity.metadata.NetworkEntityMetadataObject; public class NetworkEntityMetadataObjectItemStack extends NetworkEntityMetadataObject<NetworkItemStack> { public NetworkEntityMetadataObjectItemStack(NetworkItemStack itemstack) { this.value = itemstack; } @Override public void writeToStream(ByteBuf to, ProtocolVersion version, String locale) { ItemStackCodec.writeItemStack(to, version, value); } }
agpl-3.0
johnmay/cdk-debug-viewer
src/main/java/org/openscience/cdk/App.java
317
package org.openscience.cdk; /** * @author John May */ public class App { public static void main(String[] args) { View view = View.createAndShow(); // example of programmatic control // view.controller.loadSmi("CCO"); // view.controller.loadName("caffeine"); } }
lgpl-2.1
mbatchelor/pentaho-reporting
engine/extensions-scripting/src/test/java/org/pentaho/reporting/engine/classic/extensions/datasources/scriptable/ScriptableDataFactoryTest.java
6556
/*! * This program is free software; you can redistribute it and/or modify it under the * terms of the GNU Lesser General Public License, version 2.1 as published by the Free Software * Foundation. * * You should have received a copy of the GNU Lesser General Public License along with this * program; if not, you can obtain a copy at http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html * or from the Free Software Foundation, Inc., * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. * * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; * without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. * See the GNU Lesser General Public License for more details. * * Copyright (c) 2002-2017 Hitachi Vantara.. All rights reserved. */ package org.pentaho.reporting.engine.classic.extensions.datasources.scriptable; import static org.hamcrest.CoreMatchers.equalTo; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.CoreMatchers.nullValue; import static org.junit.Assert.assertThat; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.doThrow; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.spy; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import javax.swing.table.TableModel; import org.apache.bsf.BSFException; import org.apache.bsf.BSFManager; import org.junit.Test; import org.pentaho.reporting.engine.classic.core.DataRow; import org.pentaho.reporting.engine.classic.core.ReportDataFactoryException; public class ScriptableDataFactoryTest { private static final String QUERY_NAME = "name"; private static final String QUERY_VALUE = "value"; private static final String LANGUAGE = "lang"; @Test public void testSetQuery() { ScriptableDataFactory dataFactory = new ScriptableDataFactory(); dataFactory.setQuery( QUERY_NAME, QUERY_VALUE ); assertThat( dataFactory.getQuery( QUERY_NAME ), is( equalTo( QUERY_VALUE ) ) ); dataFactory.setQuery( QUERY_NAME, null ); assertThat( dataFactory.getQuery( QUERY_NAME ), is( nullValue() ) ); } @Test( expected = ReportDataFactoryException.class ) public void testQueryDataReportDataFactoryException() throws Exception { ScriptableDataFactory dataFactory = new ScriptableDataFactory(); dataFactory.queryData( QUERY_NAME, null ); } @Test( expected = ReportDataFactoryException.class ) public void testQueryDataBSFException() throws Exception { ScriptableDataFactory dataFactory = spy( new ScriptableDataFactory() ); dataFactory.setQuery( QUERY_NAME, QUERY_VALUE ); dataFactory.setLanguage( LANGUAGE ); DataRow parameters = mock( DataRow.class ); doThrow( BSFException.class ).when( dataFactory ).createInterpreter(); dataFactory.queryData( QUERY_NAME, parameters ); } @Test( expected = ReportDataFactoryException.class ) public void testQueryDataNotTableModel() throws Exception { ScriptableDataFactory dataFactory = spy( new ScriptableDataFactory() ); dataFactory.setQuery( QUERY_NAME, QUERY_VALUE ); dataFactory.setLanguage( LANGUAGE ); DataRow parameters = mock( DataRow.class ); BSFManager interpreter = mock( BSFManager.class ); when( dataFactory.createInterpreter() ).thenReturn( interpreter ); doReturn( "wrong_type" ).when( interpreter ).eval( LANGUAGE, "expression", 1, 1, QUERY_VALUE ); dataFactory.queryData( QUERY_NAME, parameters ); } @Test public void testQueryData() throws Exception { ScriptableDataFactory dataFactory = spy( new ScriptableDataFactory() ); dataFactory.setQuery( QUERY_NAME, QUERY_VALUE ); dataFactory.setLanguage( LANGUAGE ); DataRow parameters = mock( DataRow.class ); BSFManager interpreter = mock( BSFManager.class ); TableModel tableModel = mock( TableModel.class ); when( dataFactory.createInterpreter() ).thenReturn( interpreter ); doReturn( tableModel ).when( interpreter ).eval( LANGUAGE, "expression", 1, 1, QUERY_VALUE ); TableModel result = dataFactory.queryData( QUERY_NAME, parameters ); assertThat( result, is( equalTo( tableModel ) ) ); } @Test public void testClone() throws Exception { ScriptableDataFactory dataFactory = new ScriptableDataFactory(); dataFactory.setQuery( QUERY_NAME, QUERY_VALUE ); ScriptableDataFactory clonedFactory = dataFactory.clone(); assertThat( clonedFactory, is( notNullValue() ) ); assertThat( clonedFactory.getQuery( QUERY_NAME ), is( equalTo( QUERY_VALUE ) ) ); } @Test public void testClose() throws Exception { ScriptableDataFactory dataFactory = spy( new ScriptableDataFactory() ); dataFactory.setQuery( QUERY_NAME, QUERY_VALUE ); dataFactory.setLanguage( LANGUAGE ); dataFactory.setShutdownScript( "test_shutdown_script" ); BSFManager interpreter = mock( BSFManager.class ); TableModel tableModel = mock( TableModel.class ); when( dataFactory.createInterpreter() ).thenReturn( interpreter ); doReturn( tableModel ).when( interpreter ).eval( LANGUAGE, "expression", 1, 1, QUERY_VALUE ); dataFactory.queryData( QUERY_NAME, null ); doReturn( null ).when( interpreter ).eval( LANGUAGE, "shutdown-script", 1, 1, "test_shutdown_script" ); dataFactory.close(); verify( interpreter ).eval( LANGUAGE, "shutdown-script", 1, 1, "test_shutdown_script" ); } @Test public void testIsQueryExecutable() { ScriptableDataFactory dataFactory = new ScriptableDataFactory(); boolean result = dataFactory.isQueryExecutable( QUERY_NAME, null ); assertThat( result, is( equalTo( false ) ) ); dataFactory.setQuery( QUERY_NAME, QUERY_VALUE ); result = dataFactory.isQueryExecutable( QUERY_NAME, null ); assertThat( result, is( equalTo( true ) ) ); } @Test public void testCancelRunningQuery() throws Exception { ScriptableDataFactory dataFactory = spy( new ScriptableDataFactory() ); dataFactory.setQuery( QUERY_NAME, QUERY_VALUE ); dataFactory.setLanguage( LANGUAGE ); BSFManager interpreter = mock( BSFManager.class ); TableModel tableModel = mock( TableModel.class ); when( dataFactory.createInterpreter() ).thenReturn( interpreter ); doReturn( tableModel ).when( interpreter ).eval( LANGUAGE, "expression", 1, 1, QUERY_VALUE ); dataFactory.queryData( QUERY_NAME, null ); dataFactory.cancelRunningQuery(); verify( interpreter ).terminate(); } }
lgpl-2.1
integrated/jfreechart
source/org/jfree/chart/editor/themes/ChartBorder.java
548
package org.jfree.chart.editor.themes; import java.awt.*; /** * Created by IntelliJ IDEA. * User: Dan * Date: 29-Apr-2009 * Time: 15:23:46 * Information that is commonly needed for border styles within JFreeChart. */ public interface ChartBorder extends Cloneable { boolean isVisible(); void setVisible(boolean visible); BasicStroke getStroke(); void setStroke(BasicStroke stroke); Paint getPaint(); void setPaint(Paint paint); Object clone() throws CloneNotSupportedException; }
lgpl-2.1
nablex/http-glue
src/main/java/be/nabu/libs/http/glue/impl/ResponseMethods.java
13557
package be.nabu.libs.http.glue.impl; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.Closeable; import java.io.IOException; import java.io.InputStream; import java.nio.charset.Charset; import java.text.ParseException; import java.util.ArrayList; import java.util.Arrays; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.ws.rs.core.MediaType; import org.w3c.dom.Document; import be.nabu.glue.annotations.GlueParam; import be.nabu.glue.impl.TransactionalCloseable; import be.nabu.glue.utils.ScriptRuntime; import be.nabu.libs.evaluator.annotations.MethodProviderClass; import be.nabu.libs.http.api.HTTPEntity; import be.nabu.libs.http.api.HTTPResponse; import be.nabu.libs.http.core.HTTPUtils; import be.nabu.libs.http.glue.GlueListener; import be.nabu.libs.types.ComplexContentWrapperFactory; import be.nabu.libs.types.api.ComplexContent; import be.nabu.libs.types.binding.api.MarshallableBinding; import be.nabu.libs.types.binding.json.JSONBinding; import be.nabu.libs.types.binding.xml.XMLBinding; import be.nabu.libs.types.xml.XMLContent; import be.nabu.utils.io.IOUtils; import be.nabu.utils.io.api.ByteBuffer; import be.nabu.utils.io.api.ReadableContainer; import be.nabu.utils.mime.api.Header; import be.nabu.utils.mime.api.ModifiableHeader; import be.nabu.utils.mime.api.ModifiablePart; import be.nabu.utils.mime.impl.FormatException; import be.nabu.utils.mime.impl.MimeHeader; import be.nabu.utils.mime.impl.MimeUtils; import be.nabu.utils.xml.XMLUtils; @MethodProviderClass(namespace = "response") public class ResponseMethods { public static Boolean ABSOLUTE = Boolean.parseBoolean(System.getProperty("be.nabu.glue.redirect.absolute", "false")); public static final List<String> allowedTypes = Arrays.asList(MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML); public static final String RESPONSE_HEADERS = "responseHeaders"; public static final String RESPONSE_STREAM = "responseStream"; public static final String RESPONSE_PART = "responsePart"; public static final String RESPONSE_CHARSET = "responseCharset"; public static final String RESPONSE_DEFAULT_CHARSET = "responseDefaultCharset"; public static final String RESPONSE_PREFERRED_TYPE = "responsePreferredType"; /** * Specifically for creating a http response */ public static final String RESPONSE_CODE = "responseCode"; /** * Specifically for rewriting */ public static final String RESPONSE_TARGET = "responseTarget"; public static final String RESPONSE_METHOD = "responseMethod"; public static final String RESPONSE_EMPTY = "responseEmpty"; public static final String RESPONSE_CHANGED = "responseChanged"; /** * If you only pass in the header name, it will simply be removed */ @SuppressWarnings("unchecked") public static Header header(@GlueParam(name = "name") String name, @GlueParam(name = "value") String value, @GlueParam(name = "removeExisting", defaultValue = "true") Boolean removeExisting) throws ParseException, IOException { ScriptRuntime.getRuntime().getContext().put(RESPONSE_CHANGED, true); if (removeExisting == null || removeExisting) { removeHeader(name); } if (value != null) { // the value in this case can include some comments, so parse it Header header = MimeHeader.parseHeader(name + ": " + value); List<Header> headers = (List<Header>) ScriptRuntime.getRuntime().getContext().get(RESPONSE_HEADERS); if (headers == null) { headers = new ArrayList<Header>(); ScriptRuntime.getRuntime().getContext().put(RESPONSE_HEADERS, headers); } headers.add(header); return header; } return null; } public static void target(@GlueParam(name = "target", defaultValue = "/") String target) { ScriptRuntime.getRuntime().getContext().put(RESPONSE_CHANGED, true); if (target == null) { target = "/"; } ScriptRuntime.getRuntime().getContext().put(RESPONSE_TARGET, target); } public static void method(@GlueParam(name = "method", defaultValue = "GET") String method) { ScriptRuntime.getRuntime().getContext().put(RESPONSE_CHANGED, true); if (method == null) { method = "GET"; } ScriptRuntime.getRuntime().getContext().put(RESPONSE_METHOD, method); } @SuppressWarnings("unchecked") private static void removeHeader(String name) { List<Header> headers = (List<Header>) ScriptRuntime.getRuntime().getContext().get(RESPONSE_HEADERS); if (headers != null) { for (int i = headers.size() - 1; i >= 0; i--) { if (headers.get(i).getName().equalsIgnoreCase(name)) { headers.remove(i); } } } } public static void code(Integer code) { ScriptRuntime.getRuntime().getContext().put(RESPONSE_CHANGED, true); ScriptRuntime.getRuntime().getContext().put(RESPONSE_CODE, code); } @SuppressWarnings({ "unchecked" }) public static void content(Object response, String contentType) throws IOException, ParseException { ScriptRuntime.getRuntime().getContext().put(RESPONSE_CHANGED, true); Charset usedCharset = null; if (response == null) { ScriptRuntime.getRuntime().getContext().put(RESPONSE_EMPTY, true); // nothing is known about the response, unset ScriptRuntime.getRuntime().getContext().put(RESPONSE_STREAM, null); removeHeader("Content-Length"); removeHeader("Content-Type"); contentType = null; } else if (response instanceof ModifiablePart) { ScriptRuntime.getRuntime().getContext().put(RESPONSE_PART, response); } else if (response instanceof HTTPResponse) { ScriptRuntime.getRuntime().getContext().put(RESPONSE_PART, ((HTTPResponse) response).getContent()); code(((HTTPResponse) response).getCode()); } else if (response instanceof InputStream) { // IMPORTANT: There was an issue with the stream being set as content being closed by the time it was used for the response (this ended up in 0-byte downloads) // this was because the evaluateexecutor automatically added the stream as a transactioncloseable // so we need to remove the transactionable! ScriptRuntime.getRuntime().removeTransactionable(new TransactionalCloseable((Closeable) response)); ScriptRuntime.getRuntime().getContext().put(RESPONSE_STREAM, response); } else if (response instanceof ReadableContainer) { // see above for reason ScriptRuntime.getRuntime().removeTransactionable(new TransactionalCloseable((Closeable) response)); ScriptRuntime.getRuntime().getContext().put(RESPONSE_STREAM, IOUtils.toInputStream((ReadableContainer<ByteBuffer>) response)); } else if (response instanceof String) { usedCharset = getCharset(); byte[] bytes = ((String) response).getBytes(usedCharset); ScriptRuntime.getRuntime().getContext().put(RESPONSE_STREAM, new ByteArrayInputStream(bytes)); header("Content-Length", "" + bytes.length, true); // for a string a content type is required, otherwise it is impossible to correctly report the used charset later on (you can update the charset after having set the string content) if (contentType == null) { contentType = "text/html"; } } else if (response instanceof byte[]) { ScriptRuntime.getRuntime().getContext().put(RESPONSE_STREAM, new ByteArrayInputStream((byte []) response)); header("Content-Length", "" + ((byte[]) response).length, true); } else if (response != null) { // if you responded with an array, wrap it if (response instanceof Object[]) { Map<String, Object> root = new HashMap<String, Object>(); root.put("anonymous", response); response = root; } if (response instanceof Document) { // there is more logic to automatically detect types from maps response = XMLUtils.toMap(((Document) response).getDocumentElement()); } // undefined xml content else if (response instanceof XMLContent) { response = XMLUtils.toMap(((XMLContent) response).getElement()); } if (!(response instanceof ComplexContent)) { response = ComplexContentWrapperFactory.getInstance().getWrapper().wrap(response); if (response == null) { throw new IllegalArgumentException("Can not marshal the object"); } } usedCharset = getCharset(); // given that we are in a primarily website-driven world, use json as default HTTPEntity request = RequestMethods.entity(); if (contentType == null) { List<String> acceptedTypes = MimeUtils.getAcceptedContentTypes(request.getContent().getHeaders()); acceptedTypes.retainAll(allowedTypes); contentType = acceptedTypes.isEmpty() ? (String) ScriptRuntime.getRuntime().getContext().get(RESPONSE_PREFERRED_TYPE) : acceptedTypes.get(0); } if (!allowedTypes.contains(contentType)) { throw new IOException("The requested content type '" + contentType + "' is not supported"); } MarshallableBinding binding = MediaType.APPLICATION_JSON.equals(contentType) ? new JSONBinding(((ComplexContent) response).getType(), usedCharset) : new XMLBinding(((ComplexContent) response).getType(), usedCharset); if (binding instanceof JSONBinding) { ((JSONBinding) binding).setIgnoreRootIfArrayWrapper(true); } ByteArrayOutputStream output = new ByteArrayOutputStream(); binding.marshal(output, (ComplexContent) response); byte[] byteArray = output.toByteArray(); ScriptRuntime.getRuntime().getContext().put(RESPONSE_STREAM, new ByteArrayInputStream(byteArray)); header("Content-Length", "" + byteArray.length, true); } if (contentType != null) { if (usedCharset != null) { header("Content-Type", contentType + "; charset=" + getCharset().name(), true); } else { header("Content-Type", contentType, true); } } } @SuppressWarnings("unchecked") public static Header cookie(@GlueParam(name = "key") String key, @GlueParam(name = "value") String value, @GlueParam(name = "expires") Date expires, @GlueParam(name = "path") String path, @GlueParam(name = "domain") String domain, @GlueParam(name = "secure") Boolean secure, @GlueParam(name = "httpOnly") Boolean httpOnly) { ScriptRuntime.getRuntime().getContext().put(RESPONSE_CHANGED, true); ModifiableHeader header = HTTPUtils.newSetCookieHeader(key, value, expires, path, domain, secure, httpOnly); List<Header> headers = (List<Header>) ScriptRuntime.getRuntime().getContext().get(ResponseMethods.RESPONSE_HEADERS); if (headers == null) { headers = new ArrayList<Header>(); ScriptRuntime.getRuntime().getContext().put(ResponseMethods.RESPONSE_HEADERS, headers); } headers.add(header); return header; } public static void charset(String charset) { ScriptRuntime.getRuntime().getContext().put(RESPONSE_CHANGED, true); ScriptRuntime.getRuntime().getContext().put(RESPONSE_CHARSET, Charset.forName(charset)); } static Charset getCharset() { Charset charset = (Charset) ScriptRuntime.getRuntime().getContext().get(RESPONSE_CHARSET); if (charset == null) { charset = (Charset) ScriptRuntime.getRuntime().getContext().get(RESPONSE_DEFAULT_CHARSET); } return charset; } public static void redirect(@GlueParam(name = "location") String location, @GlueParam(name = "permanent") Boolean permanent, @GlueParam(name = "code") Integer code) throws ParseException, IOException, FormatException { ScriptRuntime.getRuntime().getContext().put(RESPONSE_CHANGED, true); // response code 302 is dubious, some clients do the new call with the original method, some don't (nodejs in particular does not) // response code 303 and 307 were added to distinguish clearly between the two // where 303 means: if it was a post (or any non-get), change it to a get // and 307 means: do the exact same call again if (code == null) { code = permanent != null && permanent ? 301 : ("get".equalsIgnoreCase(RequestMethods.method()) ? 307 : 303); } ResponseMethods.code(code); // in RFC https://tools.ietf.org/html/rfc2616#section-14.30 it states that location has to be absolute // however in RFC https://tools.ietf.org/html/rfc7231#section-7.1.2 which superceeds the previous RFC, it states that the location can be relative // the latter RFC is active since mid-2014 if (ABSOLUTE) { ResponseMethods.header("Location", location.startsWith("http://") || location.startsWith("https://") ? location : RequestMethods.url(location).toString(), true); } else { ResponseMethods.header("Location", location, true); } ServerMethods.abort(); } public static void notModified() { ScriptRuntime.getRuntime().getContext().put(RESPONSE_CHANGED, true); ResponseMethods.code(304); ServerMethods.abort(); } @SuppressWarnings("unchecked") public static Header cache( @GlueParam(name = "maxAge", description = "How long the cache should live, use '-1' to indicate that it should not be cached and null or 0 to cache indefinately") Long maxAge, @GlueParam(name = "revalidate", description = "Whether or not the cached data should be revalidated", defaultValue = "false") Boolean revalidate, @GlueParam(name = "private", description = "Whether or not the cache is private", defaultValue = "false") Boolean isPrivate) throws ParseException, IOException { ScriptRuntime.getRuntime().getContext().put(RESPONSE_CHANGED, true); Header header = GlueListener.buildCacheHeader(maxAge, revalidate, isPrivate); List<Header> headers = (List<Header>) ScriptRuntime.getRuntime().getContext().get(RESPONSE_HEADERS); if (headers == null) { headers = new ArrayList<Header>(); ScriptRuntime.getRuntime().getContext().put(RESPONSE_HEADERS, headers); } headers.add(header); return header; } }
lgpl-2.1
rajsingh8220/abixen-platform
abixen-platform-web-content-service/src/main/java/com/abixen/platform/service/webcontent/configuration/PlatformWebContentServicePackages.java
1344
/** * Copyright (c) 2010-present Abixen Systems. All rights reserved. * * This library is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 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. */ package com.abixen.platform.service.webcontent.configuration; import lombok.AccessLevel; import lombok.NoArgsConstructor; @NoArgsConstructor(access = AccessLevel.PRIVATE) public class PlatformWebContentServicePackages { public static final String MAIN = "com.abixen.platform.service.webcontent"; public static final String CONFIG = MAIN + ".configuration"; public static final String CONTROLLER = MAIN + ".controller"; public static final String SERVICE = MAIN + ".service"; public static final String REPOSITORY = MAIN + ".repository"; public static final String DOMAIN = MAIN + ".model"; public static final String CLIENT = MAIN + ".client"; public static final String CONVERTER = MAIN + ".converter"; }
lgpl-2.1
mengy007/FusionTech-1.8.9
src/main/java/com/techmafia/mcmods/fusiontech/block/BlockFluxNode.java
665
package com.techmafia.mcmods.fusiontech.block; import com.techmafia.mcmods.fusiontech.block.base.BlockFusiontechPowered; import com.techmafia.mcmods.fusiontech.tileentity.TileEntityFluxNode; import net.minecraft.block.ITileEntityProvider; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.World; /** * Created by myang on 2/10/16. */ public class BlockFluxNode extends BlockFusiontechPowered implements ITileEntityProvider { public BlockFluxNode() { super(); } /* ITileEntityProvider */ @Override public TileEntity createNewTileEntity(World worldIn, int meta) { return new TileEntityFluxNode(); } }
lgpl-2.1
drhee/toxoMine
bio/sources/pdb/main/src/org/intermine/bio/dataconversion/PdbConverter.java
7897
package org.intermine.bio.dataconversion; /* * Copyright (C) 2002-2014 FlyMine * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. See the LICENSE file for more * information or http://www.gnu.org/copyleft/lesser.html. * */ import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.Reader; import java.util.ArrayList; import java.util.Arrays; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Map; import java.util.Set; import org.apache.commons.lang.StringUtils; import org.apache.log4j.Logger; import org.apache.tools.ant.BuildException; import org.biojava.bio.structure.Structure; import org.biojava.bio.structure.io.PDBFileParser; import org.intermine.dataconversion.ItemWriter; import org.intermine.metadata.Model; import org.intermine.objectstore.ObjectStoreException; import org.intermine.util.StringUtil; import org.intermine.xml.full.Item; import org.xml.sax.SAXException; /** * @author Xavier Watkins * */ public class PdbConverter extends BioDirectoryConverter { private static final Logger LOG = Logger.getLogger(PdbConverter.class); protected static final String ENDL = System.getProperty("line.separator"); private Set<String> taxonIds = null; private Map<String, String> proteins = new HashMap<String, String>(); /** * Create a new PdbConverter object. * @param writer the ItemWriter to store the objects in * @param model the Model */ public PdbConverter(ItemWriter writer, Model model) { super(writer, model, "PDB", "PDB dmel data set", null); } /** * {@inheritDoc} */ @Override public void process(File dataDir) throws Exception { /** * if taxonids are specified, only process those directories. otherwise * process them all. */ File[] directories = dataDir.listFiles(); List<File> directoriesToProcess = new ArrayList<File>(); if (directories == null || directories.length == 0) { throw new RuntimeException("no valid PDB directories found"); } for (File f : directories) { if (f.isDirectory()) { String directoryName = f.getName(); if (taxonIds != null && !taxonIds.isEmpty()) { if (taxonIds.contains(directoryName)) { directoriesToProcess.add(f); } } else { directoriesToProcess.add(f); } } } // check that we have valid files before we start storing ANY data if (directoriesToProcess.isEmpty()) { throw new RuntimeException("no valid PDB directories found."); } // one dir per org for (File dir : directoriesToProcess) { String taxonId = dir.getName(); File[] filesToProcess = dir.listFiles(); proteins = new HashMap<String, String>(); for (File f : filesToProcess) { if (f.getName().endsWith(".pdb")) { processPDBFile(f, taxonId); } } } } /** * Sets the list of taxonIds that should be imported if using split input files. * * @param taxonIds a space-separated list of taxonIds */ public void setPdbOrganisms(String taxonIds) { this.taxonIds = new HashSet<String>(Arrays.asList(StringUtil.split(taxonIds, " "))); LOG.info("Setting list of organisms to " + this.taxonIds); } private void processPDBFile(File file, String taxonId) throws Exception { Item proteinStructure = createItem("ProteinStructure"); PDBFileParser pdbfileparser = new PDBFileParser(); Reader reader = new FileReader(file); PdbBufferedReader pdbBuffReader = new PdbBufferedReader(reader); Structure structure = pdbfileparser.parsePDBFile(pdbBuffReader); String idCode = (String) structure.getHeader().get("idCode"); if (StringUtils.isNotEmpty(idCode)) { proteinStructure.setAttribute("identifier", idCode); } else { throw new BuildException("No value for title in structure: " + idCode); } List<String> dbrefs = pdbBuffReader.getDbrefs(); for (String accnum: dbrefs) { String proteinRefId = getProtein(accnum, taxonId); proteinStructure.addToCollection("proteins", proteinRefId); } String title = (((String) structure.getHeader().get("title"))).trim(); if (StringUtils.isNotEmpty(title)) { proteinStructure.setAttribute("title", title); } else { LOG.warn("No value for title in structure: " + idCode); } String technique = ((String) structure.getHeader().get("technique")).trim(); if (StringUtils.isNotEmpty(technique)) { proteinStructure.setAttribute("technique", technique); } else { LOG.warn("No value for technique in structure: " + idCode); } String classification = ((String) structure.getHeader().get("classification")).trim(); proteinStructure.setAttribute("classification", classification); Object resolution = structure.getHeader().get("resolution"); if (resolution instanceof Float) { final Float resolutionFloat = (Float) structure.getHeader().get("resolution"); proteinStructure.setAttribute("resolution", Float.toString(resolutionFloat.floatValue())); } try { proteinStructure.setAttribute("atm", structure.toPDB()); } catch (ArrayIndexOutOfBoundsException e) { LOG.error("Failed to process structure " + idCode); } store(proteinStructure); } private String getProtein(String accession, String taxonId) throws SAXException { String refId = proteins.get(accession); if (refId == null) { Item item = createItem("Protein"); item.setAttribute("primaryAccession", accession); // TODO is there some way we can be certain of this taxonId for this protein? // item.setReference("organism", getOrganism(taxonId)); refId = item.getIdentifier(); proteins.put(accession, refId); try { store(item); } catch (ObjectStoreException e) { throw new SAXException(e); } } return refId; } /** * BioJava doesn't support getting DBREF so we get it as the file is read. * * @author Xavier Watkins * */ public class PdbBufferedReader extends BufferedReader { private List<String> dbrefs = new ArrayList<String>(); /** * Create a new PdbBufferedReader object. * @param reader the underlying Reader object */ public PdbBufferedReader(Reader reader) { super(reader); } /** * {@inheritDoc} */ @Override public String readLine() throws IOException { String line = super.readLine(); if (line != null && line.matches("^DBREF.*")) { String [] split = line.split("\\s+"); if ("SWS".equals(split[5]) || "UNP".equals(split[5])) { dbrefs.add(split[6]); } } return line; } /** * Return the db refs read from the Reader. * @return the List of db refs */ public List<String> getDbrefs() { return dbrefs; } } }
lgpl-2.1
travisbrown/marc4j-old
core/src/main/java/org/marc4j/util/MarcXmlDriver.java
8651
//$Id$ /** * Copyright (C) 2005 Bas Peters * * This file is part of MARC4J * * MARC4J 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. * * MARC4J 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 MARC4J; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.marc4j.util; import java.io.BufferedWriter; import java.io.FileInputStream; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.io.OutputStreamWriter; import java.io.UnsupportedEncodingException; import java.io.Writer; import javax.xml.transform.Result; import javax.xml.transform.Source; import javax.xml.transform.stream.StreamResult; import javax.xml.transform.stream.StreamSource; import org.marc4j.Constants; import org.marc4j.MarcStreamReader; import org.marc4j.MarcXmlWriter; import org.marc4j.converter.CharConverter; import org.marc4j.converter.impl.AnselToUnicode; import org.marc4j.converter.impl.Iso5426ToUnicode; import org.marc4j.converter.impl.Iso6937ToUnicode; import org.marc4j.marc.Record; /** * Provides a basic driver to convert MARC records to MARCXML. Output is encoded in UTF-8. * <p> * The following example reads input.mrc and writes output to the console: * * <pre> * java org.marc4j.util.MarcXmlDriver input.mrc * </pre> * * <p> * The following example reads input.mrc, converts MARC-8 and writes output in * UTF-8 to output.xml: * * <pre> * java org.marc4j.util.MarcXmlDriver -convert MARC8 -out output.xml input.mrc * </pre> * * <p> * It is possible to post-process the result using an XSLT stylesheet. The * following example converts MARC to MODS: * * <pre> * java org.marc4j.util.MarcXmlDriver -convert MARC8 -xsl http://www.loc.gov/standards/mods/v3/MARC21slim2MODS3.xsl -out modsoutput.xml input.mrc * </pre> * * <p> * For usage, run from the command-line with the following command: * * <pre> * java org.marc4j.util.MarcXmlDriver -usage * </pre> * * <p> * Check the home page for <a href="http://www.loc.gov/standards/marcxml/"> * MARCXML </a> for more information about the MARCXML format. * * @author Bas Peters * @version $Revision$ * */ public class MarcXmlDriver { /** * Provides a static entry point. * * <p> * Arguments: * </p> * <ul> * <li>-xsl &lt;stylesheet URL&gt; - post-process using XSLT-stylesheet * </li> * <li>-out &lt;output file&gt; - write to output file</li> * <li>-convert &lt;encoding&gt; - convert &lt;encoding&gt; to UTF-8 (Supported encodings: MARC8, ISO5426, ISO6937)</li> * <li>-encode &lt;encoding&gt; - read data using encoding &lt;encoding&gt;</li> * <li>-normalize - perform Unicode normalization</li> * <li>-usage - show usage</li> * <li>&lt;input file&gt; - input file with MARC records * </ul> */ public static void main(String args[]) { long start = System.currentTimeMillis(); String input = null; String output = null; String stylesheet = null; String convert = null; String encoding = "ISO_8859_1"; boolean normalize = false; for (int i = 0; i < args.length; i++) { if (args[i].equals("-xsl")) { if (i == args.length - 1) { usage(); } stylesheet = args[++i].trim(); } else if (args[i].equals("-out")) { if (i == args.length - 1) { usage(); } output = args[++i].trim(); } else if (args[i].equals("-convert")) { if (i == args.length - 1) { usage(); } convert = args[++i].trim(); } else if (args[i].equals("-encoding")) { if (i == args.length - 1) { usage(); } encoding = args[++i].trim(); } else if (args[i].equals("-normalize")) { normalize = true; } else if (args[i].equals("-usage")) { usage(); } else if (args[i].equals("-help")) { usage(); } else { input = args[i].trim(); // Must be last arg if (i != args.length - 1) { usage(); } } } if (input == null) { usage(); } InputStream in = null; try { in = new FileInputStream(input); } catch (FileNotFoundException e) { e.printStackTrace(); } MarcStreamReader reader = null; if (encoding != null) reader = new MarcStreamReader(in, encoding); else reader = new MarcStreamReader(in); OutputStream out = null; if (output != null) try { out = new FileOutputStream(output); } catch (FileNotFoundException e) { e.printStackTrace(); } else out = System.out; MarcXmlWriter writer = null; if (stylesheet == null) { if (convert != null) writer = new MarcXmlWriter(out, "UTF8"); else writer = new MarcXmlWriter(out, "UTF8"); } else { Writer outputWriter = null; if (convert != null) { try { outputWriter = new OutputStreamWriter(out, "UTF8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } outputWriter = new BufferedWriter(outputWriter); } else { outputWriter = new OutputStreamWriter(out); outputWriter = new BufferedWriter(outputWriter); } Result result = new StreamResult(outputWriter); Source source = new StreamSource(stylesheet); writer = new MarcXmlWriter(result, source); } writer.setIndent(true); if (convert != null) { CharConverter charconv = null; if (Constants.MARC_8_ENCODING.equals(convert)) charconv = new AnselToUnicode(); else if (Constants.ISO5426_ENCODING.equals(convert)) charconv = new Iso5426ToUnicode(); else if (Constants.ISO6937_ENCODING.equals(convert)) charconv = new Iso6937ToUnicode(); else { System.err.println("Unknown character set"); System.exit(1); } writer.setConverter(charconv); } if (normalize) writer.setUnicodeNormalization(true); while (reader.hasNext()) { Record record = reader.next(); if (Constants.MARC_8_ENCODING.equals(convert)) record.getLeader().setCharCodingScheme('a'); writer.write(record); } writer.close(); System.err.println("Total time: " + (System.currentTimeMillis() - start) + " miliseconds"); } private static void usage() { System.err.println("MARC4J, Copyright (C) 2002-2006 Bas Peters"); System.err .println("Usage: org.marc4j.util.MarcXmlDriver [-options] <file.mrc>"); System.err .println(" -convert <encoding> = Converts <encoding> to UTF-8"); System.err.println(" Valid encodings are: MARC8, ISO5426, ISO6937"); System.err.println(" -normalize = perform Unicode normalization"); System.err .println(" -xsl <file> = Post-process MARCXML using XSLT stylesheet <file>"); System.err.println(" -out <file> = Output using <file>"); System.err.println(" -usage or -help = this message"); System.err.println("The program outputs well-formed MARCXML"); System.err .println("See http://marc4j.tigris.org for more information."); System.exit(1); } }
lgpl-2.1
geotools/geotools
modules/extension/mbstyle/src/main/java/org/geotools/mbstyle/function/MapBoxTypeFunction.java
2861
/* * GeoTools - The Open Source Java GIS Toolkit * http://geotools.org * * (C) 2018, Open Source Geospatial Foundation (OSGeo) * * 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; * version 2.1 of the License. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. */ package org.geotools.mbstyle.function; import java.util.ArrayList; import java.util.Collection; import java.util.List; import org.geotools.filter.FunctionExpressionImpl; import org.geotools.filter.capability.FunctionNameImpl; import org.json.simple.JSONObject; import org.opengis.filter.capability.FunctionName; import org.opengis.filter.expression.Expression; /** * Takes one or more arguments and returns the the first argument of type specified by the first * string argument, throws an exception if no arguments are of type specified. */ class MapBoxTypeFunction extends FunctionExpressionImpl { Class<?> type; public static final FunctionName NAME = new FunctionNameImpl("mbType"); MapBoxTypeFunction() { super(NAME); } /** @see org.geotools.filter.FunctionExpressionImpl#setParameters(java.util.List) */ @Override public void setParameters(List<Expression> params) { // set the parameters this.params = new ArrayList<>(params); } @Override public Object evaluate(Object feature) { // loop over the arguments and ensure at least one evaluates to a JSONObject String arg = (this.params.get(0).evaluate(feature, String.class)); type = type(arg); for (int i = 1; i <= this.params.size() - 1; i++) { Object evaluation = this.params.get(i).evaluate(feature); if (type.isAssignableFrom(evaluation.getClass())) { return evaluation; } } // couldn't find a JSONObject value throw new IllegalArgumentException( "Function \"mbType\" failed with no arguments of type JSONObject"); } public Class<?> type(String string) { switch (string) { case "array": return Collection.class; case "boolean": return Boolean.class; case "number": return Number.class; case "object": return JSONObject.class; case "string": return String.class; } throw new IllegalArgumentException( "Requires argument of array, boolean, number, object or string"); } }
lgpl-2.1
melqkiades/yelp
source/java/richcontext/src/main/java/org/insightcentre/richcontext/ReviewCsvDao.java
1499
package org.insightcentre.richcontext; import com.opencsv.CSVReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import java.util.List; /** * Created by fpena on 27/03/2017. */ public class ReviewCsvDao { private static final int USER_ID_INDEX = 0; private static final int ITEM_ID_INDEX = 1; private static final int RATING_INDEX = 2; private static final char separator = '\t'; public static List<Review> readCsvFile(String filePath) throws IOException { CSVReader reader = new CSVReader(new FileReader(filePath), separator); List<Review> reviews = new ArrayList<>(); String [] nextLine; while ((nextLine = reader.readNext()) != null) { long user_id = Long.parseLong(nextLine[USER_ID_INDEX]); long item_id = Long.parseLong(nextLine[ITEM_ID_INDEX]); double rating = Double.parseDouble(nextLine[RATING_INDEX]); Review review = new Review(user_id, item_id, rating); reviews.add(review); } return reviews; } public static void main(String[] args) { String file_path = "/Users/fpena/tmp/rival/data/rich-context/model/train_0.csv"; try { List<Review> reviews = readCsvFile(file_path); for (Review review : reviews) { System.out.println(review); } } catch (IOException e) { e.printStackTrace(); } } }
lgpl-2.1
fjalvingh/domui
to.etc.webapp.core/src/main/java/to/etc/webapp/nls/IBundleCode.java
504
package to.etc.webapp.nls; /** * Interface to be used on message bundle enums. * * @author <a href="mailto:jal@etc.to">Frits Jalvingh</a> * Created on 10-10-17. */ public interface IBundleCode { String name(); default BundleRef getBundle() { return BundleRef.create(getClass(), getClass().getSimpleName()); } default String getString() { return getBundle().getString(name()); } default String format(Object... parameters) { return getBundle().formatMessage(name(), parameters); } }
lgpl-2.1
mwatts15/XSLTXT
src/main/com/zanthan/xsltxt/SimpleToken.java
1439
/** * XSLTXT - An alternative syntax for xslt * Copyright (C) 2002 Alex Moffat * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package com.zanthan.xsltxt; public class SimpleToken extends Token { /** * Create a new SimpleToken * @param indent indentation where the start of the token was found * @param line line number where the token was found * @param value the value for the token */ SimpleToken(int indent, int line, String value) { super(indent, line, value); } /** * Return a string representation of a SimpleToken suitable for * debugging use. * @return string representation */ public String toString() { return toString("SimpleToken"); } }
lgpl-2.1
1fechner/FeatureExtractor
sources/FeatureExtractor/lib/hibernate-release-5.1.0.Final/project/hibernate-core/src/main/java/org/hibernate/cfg/annotations/reflection/XMLContext.java
12116
/* * Hibernate, Relational Persistence for Idiomatic Java * * License: GNU Lesser General Public License (LGPL), version 2.1 or later. * See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>. */ package org.hibernate.cfg.annotations.reflection; import java.io.Serializable; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.persistence.AccessType; import javax.persistence.AttributeConverter; import org.hibernate.AnnotationException; import org.hibernate.boot.registry.classloading.spi.ClassLoadingException; import org.hibernate.boot.spi.ClassLoaderAccess; import org.hibernate.cfg.AttributeConverterDefinition; import org.hibernate.internal.CoreLogging; import org.hibernate.internal.CoreMessageLogger; import org.hibernate.internal.util.StringHelper; import org.dom4j.Document; import org.dom4j.Element; /** * A helper for consuming orm.xml mappings. * * @author Emmanuel Bernard * @author Brett Meyer */ public class XMLContext implements Serializable { private static final CoreMessageLogger LOG = CoreLogging.messageLogger( XMLContext.class ); private final ClassLoaderAccess classLoaderAccess; private Default globalDefaults; private Map<String, Element> classOverriding = new HashMap<String, Element>(); private Map<String, Default> defaultsOverriding = new HashMap<String, Default>(); private List<Element> defaultElements = new ArrayList<Element>(); private List<String> defaultEntityListeners = new ArrayList<String>(); private boolean hasContext = false; public XMLContext(ClassLoaderAccess classLoaderAccess) { this.classLoaderAccess = classLoaderAccess; } /** * @param doc The xml document to add * @return Add a xml document to this context and return the list of added class names. */ @SuppressWarnings( "unchecked" ) public List<String> addDocument(Document doc) { hasContext = true; List<String> addedClasses = new ArrayList<String>(); Element root = doc.getRootElement(); //global defaults Element metadata = root.element( "persistence-unit-metadata" ); if ( metadata != null ) { if ( globalDefaults == null ) { globalDefaults = new Default(); globalDefaults.setMetadataComplete( metadata.element( "xml-mapping-metadata-complete" ) != null ? Boolean.TRUE : null ); Element defaultElement = metadata.element( "persistence-unit-defaults" ); if ( defaultElement != null ) { Element unitElement = defaultElement.element( "schema" ); globalDefaults.setSchema( unitElement != null ? unitElement.getTextTrim() : null ); unitElement = defaultElement.element( "catalog" ); globalDefaults.setCatalog( unitElement != null ? unitElement.getTextTrim() : null ); unitElement = defaultElement.element( "access" ); setAccess( unitElement, globalDefaults ); unitElement = defaultElement.element( "cascade-persist" ); globalDefaults.setCascadePersist( unitElement != null ? Boolean.TRUE : null ); unitElement = defaultElement.element( "delimited-identifiers" ); globalDefaults.setDelimitedIdentifiers( unitElement != null ? Boolean.TRUE : null ); defaultEntityListeners.addAll( addEntityListenerClasses( defaultElement, null, addedClasses ) ); } } else { LOG.duplicateMetadata(); } } //entity mapping default Default entityMappingDefault = new Default(); Element unitElement = root.element( "package" ); String packageName = unitElement != null ? unitElement.getTextTrim() : null; entityMappingDefault.setPackageName( packageName ); unitElement = root.element( "schema" ); entityMappingDefault.setSchema( unitElement != null ? unitElement.getTextTrim() : null ); unitElement = root.element( "catalog" ); entityMappingDefault.setCatalog( unitElement != null ? unitElement.getTextTrim() : null ); unitElement = root.element( "access" ); setAccess( unitElement, entityMappingDefault ); defaultElements.add( root ); setLocalAttributeConverterDefinitions( root.elements( "converter" ) ); List<Element> entities = root.elements( "entity" ); addClass( entities, packageName, entityMappingDefault, addedClasses ); entities = root.elements( "mapped-superclass" ); addClass( entities, packageName, entityMappingDefault, addedClasses ); entities = root.elements( "embeddable" ); addClass( entities, packageName, entityMappingDefault, addedClasses ); return addedClasses; } private void setAccess(Element unitElement, Default defaultType) { if ( unitElement != null ) { String access = unitElement.getTextTrim(); setAccess( access, defaultType ); } } private void setAccess( String access, Default defaultType) { AccessType type; if ( access != null ) { try { type = AccessType.valueOf( access ); } catch ( IllegalArgumentException e ) { throw new AnnotationException( "Invalid access type " + access + " (check your xml configuration)" ); } defaultType.setAccess( type ); } } private void addClass(List<Element> entities, String packageName, Default defaults, List<String> addedClasses) { for (Element element : entities) { String className = buildSafeClassName( element.attributeValue( "class" ), packageName ); if ( classOverriding.containsKey( className ) ) { //maybe switch it to warn? throw new IllegalStateException( "Duplicate XML entry for " + className ); } addedClasses.add( className ); classOverriding.put( className, element ); Default localDefault = new Default(); localDefault.override( defaults ); String metadataCompleteString = element.attributeValue( "metadata-complete" ); if ( metadataCompleteString != null ) { localDefault.setMetadataComplete( Boolean.parseBoolean( metadataCompleteString ) ); } String access = element.attributeValue( "access" ); setAccess( access, localDefault ); defaultsOverriding.put( className, localDefault ); LOG.debugf( "Adding XML overriding information for %s", className ); addEntityListenerClasses( element, packageName, addedClasses ); } } private List<String> addEntityListenerClasses(Element element, String packageName, List<String> addedClasses) { List<String> localAddedClasses = new ArrayList<String>(); Element listeners = element.element( "entity-listeners" ); if ( listeners != null ) { @SuppressWarnings( "unchecked" ) List<Element> elements = listeners.elements( "entity-listener" ); for (Element listener : elements) { String listenerClassName = buildSafeClassName( listener.attributeValue( "class" ), packageName ); if ( classOverriding.containsKey( listenerClassName ) ) { //maybe switch it to warn? if ( "entity-listener".equals( classOverriding.get( listenerClassName ).getName() ) ) { LOG.duplicateListener( listenerClassName ); continue; } throw new IllegalStateException("Duplicate XML entry for " + listenerClassName); } localAddedClasses.add( listenerClassName ); classOverriding.put( listenerClassName, listener ); } } LOG.debugf( "Adding XML overriding information for listeners: %s", localAddedClasses ); addedClasses.addAll( localAddedClasses ); return localAddedClasses; } @SuppressWarnings("unchecked") private void setLocalAttributeConverterDefinitions(List<Element> converterElements) { for ( Element converterElement : converterElements ) { final String className = converterElement.attributeValue( "class" ); final String autoApplyAttribute = converterElement.attributeValue( "auto-apply" ); final boolean autoApply = autoApplyAttribute != null && Boolean.parseBoolean( autoApplyAttribute ); try { final Class<? extends AttributeConverter> attributeConverterClass = classLoaderAccess.classForName( className ); attributeConverterDefinitions.add( new AttributeConverterDefinition( attributeConverterClass.newInstance(), autoApply ) ); } catch (ClassLoadingException e) { throw new AnnotationException( "Unable to locate specified AttributeConverter implementation class : " + className, e ); } catch (Exception e) { throw new AnnotationException( "Unable to instantiate specified AttributeConverter implementation class : " + className, e ); } } } public static String buildSafeClassName(String className, String defaultPackageName) { if ( className.indexOf( '.' ) < 0 && StringHelper.isNotEmpty( defaultPackageName ) ) { className = StringHelper.qualify( defaultPackageName, className ); } return className; } public static String buildSafeClassName(String className, XMLContext.Default defaults) { return buildSafeClassName( className, defaults.getPackageName() ); } public Default getDefault(String className) { Default xmlDefault = new Default(); xmlDefault.override( globalDefaults ); if ( className != null ) { Default entityMappingOverriding = defaultsOverriding.get( className ); xmlDefault.override( entityMappingOverriding ); } return xmlDefault; } public Element getXMLTree(String className ) { return classOverriding.get( className ); } public List<Element> getAllDocuments() { return defaultElements; } public boolean hasContext() { return hasContext; } private List<AttributeConverterDefinition> attributeConverterDefinitions = new ArrayList<AttributeConverterDefinition>(); public void applyDiscoveredAttributeConverters(AttributeConverterDefinitionCollector collector) { for ( AttributeConverterDefinition definition : attributeConverterDefinitions ) { collector.addAttributeConverter( definition ); } attributeConverterDefinitions.clear(); } public static class Default implements Serializable { private AccessType access; private String packageName; private String schema; private String catalog; private Boolean metadataComplete; private Boolean cascadePersist; private Boolean delimitedIdentifier; public AccessType getAccess() { return access; } protected void setAccess(AccessType access) { this.access = access; } public String getCatalog() { return catalog; } protected void setCatalog(String catalog) { this.catalog = catalog; } public String getPackageName() { return packageName; } protected void setPackageName(String packageName) { this.packageName = packageName; } public String getSchema() { return schema; } protected void setSchema(String schema) { this.schema = schema; } public Boolean getMetadataComplete() { return metadataComplete; } public boolean canUseJavaAnnotations() { return metadataComplete == null || !metadataComplete; } protected void setMetadataComplete(Boolean metadataComplete) { this.metadataComplete = metadataComplete; } public Boolean getCascadePersist() { return cascadePersist; } void setCascadePersist(Boolean cascadePersist) { this.cascadePersist = cascadePersist; } public void override(Default globalDefault) { if ( globalDefault != null ) { if ( globalDefault.getAccess() != null ) access = globalDefault.getAccess(); if ( globalDefault.getPackageName() != null ) packageName = globalDefault.getPackageName(); if ( globalDefault.getSchema() != null ) schema = globalDefault.getSchema(); if ( globalDefault.getCatalog() != null ) catalog = globalDefault.getCatalog(); if ( globalDefault.getDelimitedIdentifier() != null ) delimitedIdentifier = globalDefault.getDelimitedIdentifier(); if ( globalDefault.getMetadataComplete() != null ) { metadataComplete = globalDefault.getMetadataComplete(); } //TODO fix that in stone if cascade-persist is set already? if ( globalDefault.getCascadePersist() != null ) cascadePersist = globalDefault.getCascadePersist(); } } public void setDelimitedIdentifiers(Boolean delimitedIdentifier) { this.delimitedIdentifier = delimitedIdentifier; } public Boolean getDelimitedIdentifier() { return delimitedIdentifier; } } public List<String> getDefaultEntityListeners() { return defaultEntityListeners; } }
lgpl-2.1
mharj/jsimconnect
src/main/java/flightsim/simconnect/TextResult.java
2831
package flightsim.simconnect; import flightsim.simconnect.recv.RecvEvent; /** * The <code>TextResult</code> enumeration type is used to specify which * event has occurred as a result of a call to {@link SimConnect#text(int, float, int, String)} * or {@link SimConnect#menu(float, int, String, String, String[])}. * * * @since 0.5 * @author lc0277 * */ public enum TextResult { /** Specifies that the user has selected the menu item. */ MENU_SELECT_1 (0), /** Specifies that the user has selected the menu item. */ MENU_SELECT_2 (1), /** Specifies that the user has selected the menu item. */ MENU_SELECT_3 (2), /** Specifies that the user has selected the menu item. */ MENU_SELECT_4 (3), /** Specifies that the user has selected the menu item. */ MENU_SELECT_5 (4), /** Specifies that the user has selected the menu item. */ MENU_SELECT_6 (5), /** Specifies that the user has selected the menu item. */ MENU_SELECT_7 (6), /** Specifies that the user has selected the menu item. */ MENU_SELECT_8 (7), /** Specifies that the user has selected the menu item. */ MENU_SELECT_9 (8), /** Specifies that the user has selected the menu item. */ MENU_SELECT_10 (9), /** Specifies that the menu or text identified by the EventID is now on display. */ DISPLAYED (0x00010000), /** Specifies that the menu or text identified by the EventID is waiting in a queue. */ QUEUED (0x00010001), /** Specifies that the menu or text identified by the EventID has been removed from the queue. */ REMOVED (0x00010002), /** Specifies that the menu or text identified by the EventID has been replaced in the queue. */ REPLACED (0x00010003), /** Specifies that the menu or text identified by the EventID has timed-out and is no longer on display. */ TIMEOUT (0x00010004); private final int value; private TextResult(int value) { this.value = value; } /** * Returns true if the text result is a selection item (not a * display event) * @return true if the text result is a selection item * @since 0.7 */ public boolean isSelection() { return value < 0x100; } /** * Return the numeric value of the constant * @return value of the event */ public int value() { return value; } /** * Returns a member of the TextResult enumeration given by its value * @param val value * @return member */ public static TextResult type(int val) { TextResult[] values = values(); for (TextResult tr : values) { if (tr.value == val) return tr; } return null; } /** * Returns a member of the TextResult enumeration given by its value * @param ev Event structure * @return member */ public static TextResult type(RecvEvent ev) { return type(ev.getData()); } }
lgpl-2.1
kevin-chen-hw/LDAE
com.huawei.soa.ldae/src/main/java/org/hibernate/loader/plan/exec/internal/EntityLoadQueryDetails.java
10871
/* * Hibernate, Relational Persistence for Idiomatic Java * * Copyright (c) 2013, Red Hat Inc. or third-party contributors as * indicated by the @author tags or express copyright attribution * statements applied by the authors. All third-party contributions are * distributed under license by Red Hat Inc. * * This copyrighted material is made available to anyone wishing to use, modify, * copy, or redistribute it subject to the terms and conditions of the GNU * Lesser General Public License, as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License * for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this distribution; if not, write to: * Free Software Foundation, Inc. * 51 Franklin Street, Fifth Floor * Boston, MA 02110-1301 USA */ package org.hibernate.loader.plan.exec.internal; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Collections; import org.hibernate.LockOptions; import org.hibernate.Session; import org.hibernate.engine.spi.EntityKey; import org.hibernate.engine.spi.SessionFactoryImplementor; import org.hibernate.internal.CoreLogging; import org.hibernate.loader.plan.exec.process.internal.AbstractRowReader; import org.hibernate.loader.plan.exec.process.internal.EntityReferenceInitializerImpl; import org.hibernate.loader.plan.exec.process.internal.EntityReturnReader; import org.hibernate.loader.plan.exec.process.internal.ResultSetProcessingContextImpl; import org.hibernate.loader.plan.exec.process.internal.ResultSetProcessorHelper; import org.hibernate.loader.plan.exec.process.spi.EntityReferenceInitializer; import org.hibernate.loader.plan.exec.process.spi.ReaderCollector; import org.hibernate.loader.plan.exec.process.spi.ResultSetProcessingContext; import org.hibernate.loader.plan.exec.process.spi.RowReader; import org.hibernate.loader.plan.exec.query.internal.SelectStatementBuilder; import org.hibernate.loader.plan.exec.query.spi.QueryBuildingParameters; import org.hibernate.loader.plan.exec.spi.EntityReferenceAliases; import org.hibernate.loader.plan.spi.EntityReturn; import org.hibernate.loader.plan.spi.LoadPlan; import org.hibernate.loader.plan.spi.QuerySpace; import org.hibernate.persister.entity.EntityPersister; import org.hibernate.persister.entity.Joinable; import org.hibernate.persister.entity.OuterJoinLoadable; import org.hibernate.persister.entity.Queryable; import org.hibernate.type.ComponentType; import org.hibernate.type.Type; import org.jboss.logging.Logger; /** * Handles interpreting a LoadPlan (for loading of an entity) by:<ul> * <li>generating the SQL query to perform</li> * <li>creating the readers needed to read the results from the SQL's ResultSet</li> * </ul> * * @author Steve Ebersole * @author Gail Badner */ public class EntityLoadQueryDetails extends AbstractLoadQueryDetails { private static final Logger log = CoreLogging.logger( EntityLoadQueryDetails.class ); private final EntityReferenceAliases entityReferenceAliases; private final ReaderCollector readerCollector; /** * Constructs a EntityLoadQueryDetails object from the given inputs. * * @param loadPlan The load plan * @param keyColumnNames The columns to load the entity by (the PK columns or some other unique set of columns) * @param buildingParameters And influencers that would affect the generated SQL (mostly we are concerned with those * that add additional joins here) * @param factory The SessionFactory */ protected EntityLoadQueryDetails( LoadPlan loadPlan, String[] keyColumnNames, AliasResolutionContextImpl aliasResolutionContext, EntityReturn rootReturn, QueryBuildingParameters buildingParameters, SessionFactoryImplementor factory) { super( loadPlan, aliasResolutionContext, buildingParameters, keyColumnNames, rootReturn, factory ); this.entityReferenceAliases = aliasResolutionContext.generateEntityReferenceAliases( rootReturn.getQuerySpaceUid(), rootReturn.getEntityPersister() ); this.readerCollector = new EntityLoaderReaderCollectorImpl( new EntityReturnReader( rootReturn ), new EntityReferenceInitializerImpl( rootReturn, entityReferenceAliases, true ) ); generate(); } private EntityReturn getRootEntityReturn() { return (EntityReturn) getRootReturn(); } /** * Applies "table fragments" to the FROM-CLAUSE of the given SelectStatementBuilder for the given Loadable * * @param select The SELECT statement builder * * @see org.hibernate.persister.entity.OuterJoinLoadable#fromTableFragment(java.lang.String) * @see org.hibernate.persister.entity.Joinable#fromJoinFragment(java.lang.String, boolean, boolean) */ @Override protected void applyRootReturnTableFragments(SelectStatementBuilder select) { final String fromTableFragment; final String rootAlias = entityReferenceAliases.getTableAlias(); final OuterJoinLoadable outerJoinLoadable = (OuterJoinLoadable) getRootEntityReturn().getEntityPersister(); if ( getQueryBuildingParameters().getLockOptions() != null ) { fromTableFragment = getSessionFactory().getDialect().appendLockHint( getQueryBuildingParameters().getLockOptions(), outerJoinLoadable.fromTableFragment( rootAlias ) ); select.setLockOptions( getQueryBuildingParameters().getLockOptions() ); } else if ( getQueryBuildingParameters().getLockMode() != null ) { fromTableFragment = getSessionFactory().getDialect().appendLockHint( getQueryBuildingParameters().getLockMode(), outerJoinLoadable.fromTableFragment( rootAlias ) ); select.setLockMode( getQueryBuildingParameters().getLockMode() ); } else { fromTableFragment = outerJoinLoadable.fromTableFragment( rootAlias ); } select.appendFromClauseFragment( fromTableFragment + outerJoinLoadable.fromJoinFragment( rootAlias, true, true ) ); } @Override protected void applyRootReturnFilterRestrictions(SelectStatementBuilder selectStatementBuilder) { final Queryable rootQueryable = (Queryable) getRootEntityReturn().getEntityPersister(); selectStatementBuilder.appendRestrictions( rootQueryable.filterFragment( entityReferenceAliases.getTableAlias(), Collections.emptyMap() ) ); } @Override protected void applyRootReturnWhereJoinRestrictions(SelectStatementBuilder selectStatementBuilder) { final Joinable joinable = (OuterJoinLoadable) getRootEntityReturn().getEntityPersister(); selectStatementBuilder.appendRestrictions( joinable.whereJoinFragment( entityReferenceAliases.getTableAlias(), true, true ) ); } @Override protected void applyRootReturnOrderByFragments(SelectStatementBuilder selectStatementBuilder) { } @Override protected ReaderCollector getReaderCollector() { return readerCollector; } @Override protected QuerySpace getRootQuerySpace() { return getQuerySpace( getRootEntityReturn().getQuerySpaceUid() ); } @Override public String getRootTableAlias() { return entityReferenceAliases.getTableAlias(); } @Override protected boolean shouldApplyRootReturnFilterBeforeKeyRestriction() { return false; } @Override protected void applyRootReturnSelectFragments(SelectStatementBuilder selectStatementBuilder) { final OuterJoinLoadable outerJoinLoadable = (OuterJoinLoadable) getRootEntityReturn().getEntityPersister(); selectStatementBuilder.appendSelectClauseFragment( outerJoinLoadable.selectFragment( entityReferenceAliases.getTableAlias(), entityReferenceAliases.getColumnAliases().getSuffix() ) ); } private static class EntityLoaderReaderCollectorImpl extends ReaderCollectorImpl { private final EntityReturnReader entityReturnReader; public EntityLoaderReaderCollectorImpl( EntityReturnReader entityReturnReader, EntityReferenceInitializer entityReferenceInitializer) { this.entityReturnReader = entityReturnReader; add( entityReferenceInitializer ); } @Override public RowReader buildRowReader() { return new EntityLoaderRowReader( this ); } @Override public EntityReturnReader getReturnReader() { return entityReturnReader; } } private static class EntityLoaderRowReader extends AbstractRowReader { private final EntityReturnReader rootReturnReader; public EntityLoaderRowReader(EntityLoaderReaderCollectorImpl entityLoaderReaderCollector) { super( entityLoaderReaderCollector ); this.rootReturnReader = entityLoaderReaderCollector.getReturnReader(); } @Override public Object readRow(ResultSet resultSet, ResultSetProcessingContextImpl context) throws SQLException { final ResultSetProcessingContext.EntityReferenceProcessingState processingState = rootReturnReader.getIdentifierResolutionContext( context ); // if the entity reference we are hydrating is a Return, it is possible that its EntityKey is // supplied by the QueryParameter optional entity information if ( context.shouldUseOptionalEntityInformation() && context.getQueryParameters().getOptionalId() != null ) { EntityKey entityKey = ResultSetProcessorHelper.getOptionalObjectKey( context.getQueryParameters(), context.getSession() ); processingState.registerIdentifierHydratedForm( entityKey.getIdentifier() ); processingState.registerEntityKey( entityKey ); final EntityPersister entityPersister = processingState.getEntityReference().getEntityPersister(); if ( entityPersister.getIdentifierType().isComponentType() ) { final ComponentType identifierType = (ComponentType) entityPersister.getIdentifierType(); if ( !identifierType.isEmbedded() ) { addKeyManyToOnesToSession( context, identifierType, entityKey.getIdentifier() ); } } } return super.readRow( resultSet, context ); } private void addKeyManyToOnesToSession(ResultSetProcessingContextImpl context, ComponentType componentType, Object component ) { for ( int i = 0 ; i < componentType.getSubtypes().length ; i++ ) { final Type subType = componentType.getSubtypes()[ i ]; final Object subValue = componentType.getPropertyValue( component, i, context.getSession() ); if ( subType.isEntityType() ) { ( (Session) context.getSession() ).buildLockRequest( LockOptions.NONE ).lock( subValue ); } else if ( subType.isComponentType() ) { addKeyManyToOnesToSession( context, (ComponentType) subType, subValue ); } } } @Override protected Object readLogicalRow(ResultSet resultSet, ResultSetProcessingContextImpl context) throws SQLException { return rootReturnReader.read( resultSet, context ); } } }
lgpl-2.1
AsoBrain/AsoBrain3D
core/src/main/java/ab/j3d/loader/max3ds/ColorChunk.java
2610
/* $Id$ * ==================================================================== * AsoBrain 3D Toolkit * Copyright (C) 1999-2011 Peter S. Heijnen * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA * ==================================================================== */ package ab.j3d.loader.max3ds; import java.io.*; import ab.j3d.*; /** * Type : {@link #COLOR_FLOAT}, * {@link #COLOR_BYTE}, * {@link #CLR_BYTE_GAMA}, * {@link #CLR_FLOAT_GAMA}. * Parent : any * * @noinspection JavaDoc,PublicField,InstanceVariableMayNotBeInitialized */ class ColorChunk extends Chunk { Color4 _color; Color4 _gamaColor; ColorChunk( final InputStream in, final int chunkType, final int remainingChunkBytes ) throws IOException { super( in, chunkType, remainingChunkBytes ); // System.out.println( " Read: color=" + _color + ", gamaColor=" + _gamaColor ); } @Override protected void processChildChunk( final InputStream in, final int chunkType, final int remainingChunkBytes ) throws IOException { // System.out.println( "ColorChunk.processChildChunk( " + chunkType + " )" ); switch ( chunkType ) { case COLOR_BYTE : _color = new Color4f( readUnsignedByte( in ), readUnsignedByte( in ), readUnsignedByte( in ) ); break; case COLOR_FLOAT : _color = new Color4f( readFloat( in ), readFloat( in ), readFloat( in ) ); break; case CLR_BYTE_GAMA : _gamaColor = new Color4f( readUnsignedByte( in ), readUnsignedByte( in ), readUnsignedByte( in ) ); break; case CLR_FLOAT_GAMA : _gamaColor = new Color4f( readFloat( in ), readFloat( in ), readFloat( in ) ); break; default : // Ignore unknown chunks System.out.println( "Skipped unknown color chunk 0x" + Integer.toHexString( chunkType ) ); skipFully( in, remainingChunkBytes ); } } public Color4 getColor() { return ( _color == null ) ? _gamaColor : _color; } }
lgpl-2.1
motoq/vse
intxm/ISysEqns.java
1258
/* c ISysEqns.java c c Copyright (C) 2000, 2010 Kurt Motekew c c This library is free software; you can redistribute it and/or c modify it under the terms of the GNU Lesser General Public c License as published by the Free Software Foundation; either c version 2.1 of the License, or (at your option) any later version. c c This library is distributed in the hope that it will be useful, c but WITHOUT ANY WARRANTY; without even the implied warranty of c MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU c Lesser General Public License for more details. c c You should have received a copy of the GNU Lesser General Public c License along with this library; if not, write to the Free Software c Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA c 02110-1301 USA */ package com.motekew.vse.intxm; /** * Interface used to define a class that will represent a system of 1st order * differential equations and the supporting architecture to initialize, * propagate, and output the system. An <code>IIntegrator</code> will most * likely be used to solve these equations. * * @author Kurt Motekew * @since 20101116 * */ public interface ISysEqns extends IStateSpace, IStepper { }
lgpl-2.1
jbossws/jbossws-cxf
modules/testsuite/shared-tests/src/test/java/org/jboss/test/ws/jaxws/samples/xop/doclit/FakeInputStream.java
1740
/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, and individual contributors * as indicated by the @author tags. See the copyright.txt file in the * distribution for a full listing of individual contributors. * * This is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation; either version 2.1 of * the License, or (at your option) any later version. * * This software is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this software; if not, write to the Free * Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA * 02110-1301 USA, or see the FSF site: http://www.fsf.org. */ package org.jboss.test.ws.jaxws.samples.xop.doclit; import java.io.InputStream; import java.io.IOException; import java.util.Arrays; public class FakeInputStream extends InputStream { private long size; public FakeInputStream(long size) { this.size = size; } public int read(byte[] b, int off, int len) throws IOException { if (len < 1) return 0; if (size == 0) return -1; int ret = (int)Math.min(size, len); Arrays.fill(b, off, off + ret, (byte)1); size -= ret; return ret; } public int read() throws IOException { if (size > 0) { size--; return 1; } return -1; } }
lgpl-2.1
bitrepository/reference
bitrepository-client/src/main/java/org/bitrepository/commandline/eventhandler/GetFileIDsEventHandler.java
2007
/* * #%L * Bitrepository Command Line * %% * Copyright (C) 2010 - 2013 The State and University Library, The Royal Library and The State Archives, Denmark * %% * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as * published by the Free Software Foundation, either version 2.1 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-2.1.html>. * #L% */ package org.bitrepository.commandline.eventhandler; import org.bitrepository.access.getfileids.conversation.FileIDsCompletePillarEvent; import org.bitrepository.client.eventhandler.OperationEvent; import org.bitrepository.commandline.output.OutputHandler; import org.bitrepository.commandline.resultmodel.GetFileIDsResultModel; /** * Event handler for paging through GetFileIDs results */ public class GetFileIDsEventHandler extends PagingEventHandler { private GetFileIDsResultModel model; public GetFileIDsEventHandler(GetFileIDsResultModel model, Long timeout, OutputHandler outputHandler) { super(timeout, outputHandler); this.model = model; } protected void handleResult(OperationEvent event) { if(event instanceof FileIDsCompletePillarEvent) { FileIDsCompletePillarEvent pillarEvent = (FileIDsCompletePillarEvent) event; if(pillarEvent.isPartialResult()) { pillarsWithPartialResults.add(pillarEvent.getContributorID()); } model.addResults(pillarEvent.getContributorID(), pillarEvent.getFileIDs()); } } }
lgpl-2.1
BigBastardPhony/Valkyrien-Warfare-Revamped
src/main/java/code/elix_x/excomms/jstructure/JavaStructure.java
6881
package code.elix_x.excomms.jstructure; import java.util.function.Function; public class JavaStructure { public static enum JModifier { //@formatter:off PUBLIC, PRIVATE, PROTECTED, STATIC, FINAL, SYNCHRONIZED, VOLATILE, TRANSIENT, NATIVE, INTERFACE, ABSTRACT, STRICT, BRIDGE, VARARGS, SYNTHETIC, ANNOTATION, ENUM, MANDATED; //@formatter:on private final int bit; private final int mask; private JModifier(){ this.bit = ordinal(); this.mask = (int) Math.pow(2, bit); } public int bit(){ return bit; } public int mask(){ return mask; } } public static enum JModifiersMask { //@formatter:off CLASS(3103), INTERFACE(3087), CONSTRUCTOR(7), METHOD(3391), FIELD(223), PARAMETER(16), ACCESS(7); //@formatter:on private final int mask; private JModifiersMask(int mask){ this.mask = mask; } } public static final class JModifiers { private final int mask; public JModifiers(int mask){ this.mask = mask; } public boolean is(JModifier modifier){ return (mask & modifier.mask) != 0; } public JModifiers with(JModifier modifier, boolean active){ return new JModifiers(active ? mask | modifier.mask : mask & (~modifier.mask)); } public JModifiers mask(JModifiersMask mask){ return new JModifiers(this.mask & mask.mask); } } public static interface JType<T> { } public static enum JPrimitive implements JType { //@formatter:off BOOLEAN(JClass.fromClass(boolean.class), JClass.fromClass(Boolean.class), 1), BYTE(JClass.fromClass(byte.class), JClass.fromClass(Byte.class), Byte.SIZE), SHORT(JClass.fromClass(short.class), JClass.fromClass(Short.class), Short.SIZE), INT(JClass.fromClass(int.class), JClass.fromClass(Integer.class), Integer.SIZE), LONG(JClass.fromClass(long.class), JClass.fromClass(Long.class), Long.SIZE), FLOAT(JClass.fromClass(float.class), JClass.fromClass(Float.class), Float.SIZE), DOUBLE(JClass.fromClass(double.class), JClass.fromClass(Double.class), Double.SIZE), CHAR(JClass.fromClass(char.class), JClass.fromClass(Character.class), Character.SIZE); //@formatter:on private final JClass primitive; private final JClass boxed; private final int bits; private JPrimitive(JClass primitive, JClass boxed, int bits){ this.primitive = primitive; this.boxed = boxed; this.bits = bits; } public <T> JClass<T> primitive(){ return primitive; } public <T> JClass<T> boxed(){ return boxed; } public int bits(){ return bits; } public int bytes(){ return (int) Math.ceil(bits / 8f); } } public final class JParameter<T> { private final JModifiers modifiers; private final JType<T> type; public JParameter(JModifiers modifiers, JType<T> type){ this.modifiers = modifiers.mask(JModifiersMask.PARAMETER); this.type = type; } public JModifiers modifiers(){ return modifiers; } public JType<T> type(){ return type; } } public static class JClass<T> implements JType<T> { // The One public static final JClass<Object> OBJECT = new JClass<Object>(new JModifiers(Object.class.getModifiers()), Object.class.getName(), null, new JInterface[0], clas -> new JClass.JField[0], clas -> new JClass.JConstructor[]{clas.new JConstructor(new JModifiers(JModifier.PUBLIC.mask()))}, clas -> new JClass.JMethod[]{}); public static final <T> JClass<T> fromClass(Class<T> clas){ return null; } private final JModifiers modifiers; private final String name; private final JClass<? super T> superClass; private final JInterface[] interfaces; private final JField[] fields; private final JConstructor[] constructors; private final JMethod[] methods; public JClass(JModifiers modifiers, String name, JClass<? super T> superClass, JInterface[] interfaces, Function<JClass<T>, JField[]> fields, Function<JClass<T>, JConstructor[]> constructors, Function<JClass<T>, JMethod[]> methods){ this.modifiers = modifiers.mask(JModifiersMask.CLASS); this.name = name; this.superClass = superClass; this.interfaces = interfaces; this.fields = fields.apply(this); this.constructors = constructors.apply(this); this.methods = methods.apply(this); } public final JModifiers modifiers(){ return modifiers; } public final String name(){ return name; } public final JClass<? super T> superClass(){ return superClass; } public JInterface[] interfaces(){ return interfaces; } public final JField[] fields(){ return fields; } public final JConstructor[] cConstructors(){ return constructors; } public final JMethod[] methods(){ return methods; } public final class JField<F> { private final JModifiers modifiers; private final JType<F> type; private final String name; public JField(JModifiers modifiers, JType<F> type, String name){ this.modifiers = modifiers.mask(JModifiersMask.FIELD); this.type = type; this.name = name; } public JClass<T> clas(){ return JClass.this; } public JModifiers modifiers(){ return modifiers; } public JType<F> type(){ return type; } public String name(){ return name; } } public final class JConstructor { private final JModifiers modifiers; public JConstructor(JModifiers modifiers){ this.modifiers = modifiers.mask(JModifiersMask.CONSTRUCTOR); } public JModifiers modifiers(){ return modifiers; } public JClass<T> clas(){ return JClass.this; } } public final class JMethod<R> { private final JModifiers modifiers; private final JType<R> type; private final String name; private final JParameter[] parameters; public JMethod(JModifiers modifiers, JType<R> type, String name, JParameter... parameters){ this.modifiers = modifiers.mask(JModifiersMask.METHOD); this.type = type; this.name = name; this.parameters = parameters; } public JClass<T> clas(){ return JClass.this; } public JModifiers modifiers(){ return modifiers; } public JType<R> returnType(){ return type; } public String name(){ return name; } public JParameter[] parameters(){ return parameters; } } /*@formatter:off public static final class JArray<T> extends JClass<T[]> { public JArray(JModifiers modifiers){ super(modifiers, name, superClass, fields, constructors, methods); } } @formatter:on*/ public static final class JInterface<T> extends JClass<T> { public JInterface(JModifiers modifiers, String name, JInterface[] interfaces, Function<JClass<T>, JMethod[]> methods){ super(modifiers.with(JModifier.ABSTRACT, true).with(JModifier.INTERFACE, true).mask(JModifiersMask.INTERFACE), name, null, interfaces, clas -> new JClass.JField[0], clas -> new JClass.JConstructor[0], methods); } } } }
lgpl-2.1
nflantier/SFA2.0-1.10.2
src/main/java/noelflantier/sfartifacts/common/container/ContainerInjector.java
5657
package noelflantier.sfartifacts.common.container; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.inventory.IInventory; import net.minecraft.inventory.Slot; import net.minecraft.item.ItemStack; import noelflantier.sfartifacts.common.container.slot.FluidsSlots; import noelflantier.sfartifacts.common.handlers.ModFluids; import noelflantier.sfartifacts.common.tileentities.TileInjector; public class ContainerInjector extends ContainerMachine{ private int slotId = -1; public ContainerInjector(InventoryPlayer inventory,TileInjector tile){ super(inventory,tile); for(int x = 0 ; x < 9 ; x++){ this.addSlotToContainer(new Slot(inventory,x,8+18*x,176)); } for(int x = 0 ; x < 9 ; x++) for(int y = 0 ; y < 3 ; y++) this.addSlotToContainer(new Slot(inventory,x+y*9+9,8+18*x,118+18*y)); this.addSlotToContainer(new FluidsSlots(tile, nextId(),15,75,true,ModFluids.fluidLiquefiedAsgardite)); for(int j=0;j<3;j++){ for(int i=0;i<2;i++) this.addSlotToContainer(new InjectorSlots(tile, nextId(),53+18*i,23+25*j, false)); } for(int j=0;j<3;j++){ for(int i=0;i<2;i++) this.addSlotToContainer(new InjectorSlots(tile, nextId(),123+18*i,23+25*j, true)); } } private int nextId(){ this.slotId++; return this.slotId; } @Override public ItemStack transferStackInSlot(EntityPlayer player, int index) { Slot slot = getSlot(index); if (slot != null && slot.getHasStack()) { ItemStack stack = slot.getStack(); ItemStack result = stack.copy(); if (index >= 36){ //To player if (!mergeItemStack(stack, 0, 36, false)){ return null; } }else{ boolean success = false; for(int i = 0 ; i <= this.slotId ; i++){ if(this.tmachine.getStackInSlot(i)==null){ if(!this.tmachine.isItemValidForSlot(i, stack) || !mergeItemStack(stack, 36+i, 37+i, false)) success = false; else{ success = true; break; } }else if(this.tmachine.getStackInSlot(i).getItem()==slot.getStack().getItem()){ if(!mergeItemStack(stack, 36+i, 37+i, false)) success = false; else{ success = true; break; } } } if(!success) return null; } if (stack.stackSize == 0) { slot.putStack(null); }else{ slot.onSlotChanged(); } slot.onPickupFromSlot(player, stack); return result; } return null; } /*@Override protected boolean mergeItemStack(ItemStack stack, int p_75135_2_, int p_75135_3_, boolean p_75135_4_) { boolean flag1 = false; int k = p_75135_2_; if (p_75135_4_) { k = p_75135_3_ - 1; } Slot slot; ItemStack itemstack1; if (stack.isStackable()) { while (stack.stackSize > 0 && (!p_75135_4_ && k < p_75135_3_ || p_75135_4_ && k >= p_75135_2_)) { slot = (Slot)this.inventorySlots.get(k); itemstack1 = slot.getStack(); if (itemstack1 != null && itemstack1.getItem() == stack.getItem() && (!stack.getHasSubtypes() || stack.getItemDamage() == itemstack1.getItemDamage()) && ItemStack.areItemStackTagsEqual(stack, itemstack1)) { int l = itemstack1.stackSize + stack.stackSize; if (l <= stack.getMaxStackSize()) { stack.stackSize = 0; itemstack1.stackSize = l; slot.onSlotChanged(); flag1 = true; } else if (itemstack1.stackSize < stack.getMaxStackSize()) { stack.stackSize -= stack.getMaxStackSize() - itemstack1.stackSize; itemstack1.stackSize = stack.getMaxStackSize(); slot.onSlotChanged(); flag1 = true; } } if (p_75135_4_) { --k; } else { ++k; } } } if (stack.stackSize > 0) { if (p_75135_4_) { k = p_75135_3_ - 1; } else { k = p_75135_2_; } while (!p_75135_4_ && k < p_75135_3_ || p_75135_4_ && k >= p_75135_2_) { slot = (Slot)this.inventorySlots.get(k); itemstack1 = slot.getStack(); if (itemstack1 == null) { ItemStack t = stack.copy(); t.stackSize = Math.min(t.stackSize, slot.getSlotStackLimit()); slot.putStack(t.copy()); slot.onSlotChanged(); stack.stackSize -= t.stackSize; flag1 = true; break; } if (p_75135_4_) { --k; } else { ++k; } } } return flag1; }*/ private class InjectorSlots extends Slot{ public boolean isResult; public InjectorSlots(IInventory inv, int id,int x, int y, boolean isr) { super(inv, id, x, y); this.isResult = isr; } @Override public boolean isItemValid(ItemStack stack) { return !this.isResult; } @Override public int getSlotStackLimit() { return 64; } } }
lgpl-2.1
pellcorp/schemaspy
src/main/java/net/sourceforge/schemaspy/view/HtmlAnomaliesPage.java
12799
/* * This file is a part of the SchemaSpy project (http://schemaspy.sourceforge.net). * Copyright (C) 2004, 2005, 2006, 2007, 2008, 2009, 2010, 2011 John Currier * * SchemaSpy 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. * * SchemaSpy is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA */ package net.sourceforge.schemaspy.view; import java.io.IOException; import java.text.NumberFormat; import java.util.Collection; import java.util.HashSet; import java.util.List; import net.sourceforge.schemaspy.DbAnalyzer; import net.sourceforge.schemaspy.model.Database; import net.sourceforge.schemaspy.model.ForeignKeyConstraint; import net.sourceforge.schemaspy.model.Table; import net.sourceforge.schemaspy.model.TableColumn; import net.sourceforge.schemaspy.util.LineWriter; /** * This page lists all of the 'things that might not be quite right' * about the schema. * * @author John Currier */ public class HtmlAnomaliesPage extends HtmlFormatter { private static HtmlAnomaliesPage instance = new HtmlAnomaliesPage(); /** * Singleton: Don't allow instantiation */ private HtmlAnomaliesPage() { } /** * Singleton accessor * * @return the singleton instance */ public static HtmlAnomaliesPage getInstance() { return instance; } public void write(Database database, Collection<Table> tables, List<? extends ForeignKeyConstraint> impliedConstraints, LineWriter out) throws IOException { writeHeader(database, out); writeImpliedConstraints(impliedConstraints, out); writeTablesWithoutIndexes(DbAnalyzer.getTablesWithoutIndexes(new HashSet<Table>(tables)), out); writeUniqueNullables(DbAnalyzer.getMustBeUniqueNullableColumns(new HashSet<Table>(tables)), out); writeTablesWithOneColumn(DbAnalyzer.getTablesWithOneColumn(tables), out); writeTablesWithIncrementingColumnNames(DbAnalyzer.getTablesWithIncrementingColumnNames(tables), out); writeDefaultNullStrings(DbAnalyzer.getDefaultNullStringColumns(new HashSet<Table>(tables)), out); writeFooter(out); } private void writeHeader(Database database, LineWriter html) throws IOException { writeHeader(database, null, "Anomalies", html); html.writeln("<table width='100%'>"); if (sourceForgeLogoEnabled()) html.writeln(" <tr><td class='container' align='right' valign='top' colspan='2'><a href='http://sourceforge.net' target='_blank'><img src='http://sourceforge.net/sflogo.php?group_id=137197&amp;type=1' alt='SourceForge.net' border='0' height='31' width='88'></a></td></tr>"); html.writeln(" <tr><td class='container'><b>Things that might not be 'quite right' about your schema:</b></td></tr>"); html.writeln("</table>"); html.writeln("<ul>"); } private void writeImpliedConstraints(List<? extends ForeignKeyConstraint> impliedConstraints, LineWriter out) throws IOException { out.writeln("<li>"); out.writeln("<b>Columns whose name and type imply a relationship to another table's primary key:</b>"); int numDetected = 0; for (ForeignKeyConstraint impliedConstraint : impliedConstraints) { Table childTable = impliedConstraint.getChildTable(); if (!childTable.isView()) { ++numDetected; } } if (numDetected > 0) { out.writeln("<table class='dataTable' border='1' rules='groups'>"); out.writeln("<colgroup>"); out.writeln("<colgroup>"); out.writeln("<thead align='left'>"); out.writeln("<tr>"); out.writeln(" <th>Child Column</th>"); out.writeln(" <th>Implied Parent Column</th>"); out.writeln("</tr>"); out.writeln("</thead>"); out.writeln("<tbody>"); for (ForeignKeyConstraint impliedConstraint : impliedConstraints) { Table childTable = impliedConstraint.getChildTable(); if (!childTable.isView()) { out.writeln(" <tr>"); out.write(" <td class='detail'>"); String tableName = childTable.getName(); out.write("<a href='tables/"); out.write(urlEncode(tableName)); out.write(".html'>"); out.write(tableName); out.write("</a>."); out.write(ForeignKeyConstraint.toString(impliedConstraint.getChildColumns())); out.writeln("</td>"); out.write(" <td class='detail'>"); tableName = impliedConstraint.getParentTable().getName(); out.write("<a href='tables/"); out.write(urlEncode(tableName)); out.write(".html'>"); out.write(tableName); out.write("</a>."); out.write(ForeignKeyConstraint.toString(impliedConstraint.getParentColumns())); out.writeln("</td>"); out.writeln(" </tr>"); } } out.writeln("</tbody>"); out.writeln("</table>"); } writeSummary(numDetected, out); out.writeln("<p></li>"); } private void writeUniqueNullables(List<TableColumn> uniqueNullables, LineWriter out) throws IOException { out.writeln("<li>"); out.writeln("<b>Columns that are flagged as both 'nullable' and 'must be unique':</b>"); writeColumnBasedAnomaly(uniqueNullables, out); out.writeln("<p></li>"); } private void writeTablesWithoutIndexes(List<Table> unindexedTables, LineWriter out) throws IOException { out.writeln("<li>"); out.writeln("<b>Tables without indexes:</b>"); if (!unindexedTables.isEmpty()) { out.writeln("<table class='dataTable' border='1' rules='groups'>"); out.writeln("<colgroup>"); if (displayNumRows) out.writeln("<colgroup>"); out.writeln("<thead align='left'>"); out.writeln("<tr>"); out.write(" <th>Table</th>"); if (displayNumRows) out.write("<th>Rows</th>"); out.writeln(); out.writeln("</tr>"); out.writeln("</thead>"); out.writeln("<tbody>"); for (Table table : unindexedTables) { out.writeln(" <tr>"); out.write(" <td class='detail'>"); out.write("<a href='tables/"); out.write(urlEncode(table.getName())); out.write(".html'>"); out.write(table.getName()); out.write("</a>"); out.writeln("</td>"); if (displayNumRows) { out.write(" <td class='detail' align='right'>"); if (table.getNumRows() >= 0) out.write(String.valueOf(NumberFormat.getIntegerInstance().format(table.getNumRows()))); else out.write("&nbsp;"); out.writeln("</td>"); } out.writeln(" </tr>"); } out.writeln("</tbody>"); out.writeln("</table>"); } writeSummary(unindexedTables.size(), out); out.writeln("<p></li>"); } private void writeTablesWithIncrementingColumnNames(List<Table> tables, LineWriter out) throws IOException { out.writeln("<li>"); out.writeln("<b>Tables with incrementing column names, potentially indicating denormalization:</b>"); if (!tables.isEmpty()) { out.writeln("<table class='dataTable' border='1' rules='groups'>"); out.writeln("<thead align='left'>"); out.writeln("<tr>"); out.writeln(" <th>Table</th>"); out.writeln("</tr>"); out.writeln("</thead>"); out.writeln("<tbody>"); for (Table table : tables) { out.writeln(" <tr>"); out.write(" <td class='detail'>"); out.write("<a href='tables/"); out.write(urlEncode(table.getName())); out.write(".html'>"); out.write(table.getName()); out.write("</a>"); out.writeln("</td>"); out.writeln(" </tr>"); } out.writeln("</tbody>"); out.writeln("</table>"); } writeSummary(tables.size(), out); out.writeln("<p></li>"); } private void writeTablesWithOneColumn(List<Table> tables, LineWriter out) throws IOException { out.writeln("<li>"); out.write("<b>Tables that contain a single column:</b>"); if (!tables.isEmpty()) { out.writeln("<table class='dataTable' border='1' rules='groups'>"); out.writeln("<colgroup>"); out.writeln("<colgroup>"); out.writeln("<thead align='left'>"); out.writeln("<tr>"); out.writeln(" <th>Table</th>"); out.writeln(" <th>Column</th>"); out.writeln("</tr>"); out.writeln("</thead>"); out.writeln("<tbody>"); for (Table table : tables) { out.writeln(" <tr>"); out.write(" <td class='detail'>"); out.write("<a href='tables/"); out.write(urlEncode(table.getName())); out.write(".html'>"); out.write(table.getName()); out.write("</a></td><td class='detail'>"); out.write(table.getColumns().get(0).toString()); out.writeln("</td>"); out.writeln(" </tr>"); } out.writeln("</tbody>"); out.writeln("</table>"); } writeSummary(tables.size(), out); out.writeln("<p></li>"); } private void writeDefaultNullStrings(List<TableColumn> uniqueNullables, LineWriter out) throws IOException { out.writeln("<li>"); out.writeln("<b>Columns whose default value is the word 'NULL' or 'null', but the SQL NULL value may have been intended:</b>"); writeColumnBasedAnomaly(uniqueNullables, out); out.writeln("<p></li>"); } private void writeColumnBasedAnomaly(List<TableColumn> columns, LineWriter out) throws IOException { if (!columns.isEmpty()) { out.writeln("<table class='dataTable' border='1' rules='groups'>"); out.writeln("<thead align='left'>"); out.writeln("<tr>"); out.writeln(" <th>Column</th>"); out.writeln("</tr>"); out.writeln("</thead>"); out.writeln("<tbody>"); for (TableColumn column : columns) { out.writeln(" <tr>"); out.write(" <td class='detail'>"); String tableName = column.getTable().getName(); out.write("<a href='tables/"); out.write(urlEncode(tableName)); out.write(".html'>"); out.write(tableName); out.write("</a>."); out.write(column.getName()); out.writeln("</td>"); out.writeln(" </tr>"); } out.writeln("</tbody>"); out.writeln("</table>"); } writeSummary(columns.size(), out); } private void writeSummary(int numAnomalies, LineWriter out) throws IOException { switch (numAnomalies) { case 0: out.write("<br>Anomaly not detected"); break; case 1: out.write("1 instance of anomaly detected"); break; default: out.write(numAnomalies + " instances of anomaly detected"); } } @Override protected void writeFooter(LineWriter out) throws IOException { out.writeln("</ul>"); super.writeFooter(out); } @Override protected boolean isAnomaliesPage() { return true; } }
lgpl-2.1
jimregan/languagetool
languagetool-language-modules/de/src/main/java/org/languagetool/rules/de/ProhibitedCompoundRule.java
35681
/* LanguageTool, a natural language style checker * Copyright (C) 2018 Daniel Naber (http://www.danielnaber.de) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 * USA */ package org.languagetool.rules.de; import com.hankcs.algorithm.AhoCorasickDoubleArrayTrie; import org.jetbrains.annotations.NotNull; import org.jetbrains.annotations.Nullable; import org.languagetool.*; import org.languagetool.broker.ResourceDataBroker; import org.languagetool.language.GermanyGerman; import org.languagetool.languagemodel.BaseLanguageModel; import org.languagetool.languagemodel.LanguageModel; import org.languagetool.rules.*; import java.io.IOException; import java.io.InputStream; import java.util.*; import static org.languagetool.tools.StringTools.*; /** * Find compounds that might be morphologically correct but are still probably wrong, like 'Lehrzeile'. * @since 4.1 */ public class ProhibitedCompoundRule extends Rule { /** * @since 4.3 * @deprecated each pair has its own id since LT 5.1 */ public static final String RULE_ID = "DE_PROHIBITED_COMPOUNDS"; // have objects static for better performance (rule gets initialized for every check) private static final List<Pair> lowercasePairs = Arrays.asList( // NOTE: words here must be all-lowercase // NOTE: no need to add words from confusion_sets.txt, they will be used automatically (if starting with uppercase char) new Pair("lage", "Position", "alge", "im Wasser lebende Organismen"), new Pair("sphäre", "Kugel", "spähreh", null), new Pair("schenke", "Gastwirtschaft (auch: Schänke)", "schenkel", "Ober- und Unterschenkel"), new Pair("rune", "Schriftzeichen der Germanen", "runde", "Rundstrecke"), new Pair("mai", "Monat nach April", "mail", "E-Mail"), new Pair("pump", "'auf Pump': umgangssprachlich für 'auf Kredit'", "pumpe", "Gerät zur Beförderung von Flüssigkeiten"), new Pair("mitte", "zentral", "mittel", "Methode, um etwas zu erreichen"), new Pair("fein", "feinkörnig, genau, gut", "feind", "Gegner"), new Pair("traum", "Erleben während des Schlafes", "trauma", "Verletzung"), new Pair("name", "Bezeichnung (z.B. 'Vorname')", "nahme", "zu 'nehmen' (z.B. 'Teilnahme')"), new Pair("bart", "Haarbewuchs im Gesicht", "dart", "Wurfpfeil"), new Pair("hart", "fest", "dart", "Wurfpfeil"), new Pair("speiche", "Verbindung zwischen Nabe und Felge beim Rad", "speicher", "Lagerraum"), new Pair("speichen", "Verbindung zwischen Nabe und Felge beim Rad", "speicher", "Lagerraum"), new Pair("kart", "Gokart (Fahrzeug)", "karte", "Fahrkarte, Postkarte, Landkarte, ..."), new Pair("karts", "Kart = Gokart (Fahrzeug)", "karte", "Fahrkarte, Postkarte, Landkarte, ..."), new Pair("kurz", "Gegenteil von 'lang'", "kur", "medizinische Vorsorge und Rehabilitation"), new Pair("kiefer", "knöcherner Teil des Schädels", "kiefern", "Kieferngewächse (Baum)"), new Pair("gel", "dickflüssige Masse", "geld", "Zahlungsmittel"), new Pair("flucht", "Entkommen, Fliehen", "frucht", "Ummantelung des Samens einer Pflanze"), new Pair("kamp", "Flurname für ein Stück Land", "kampf", "Auseinandersetzung"), new Pair("obst", "Frucht", "ost", "Himmelsrichtung"), new Pair("beeren", "Früchte", "bären", "Raubtiere"), new Pair("laus", "Insekt", "lauf", "Bewegungsart"), new Pair("läuse", "Insekt", "läufe", "Bewegungsart"), new Pair("läusen", "Insekt", "läufen", "Bewegungsart"), new Pair("ruck", "plötzliche Bewegung", "druck", "Belastung"), new Pair("brüste", "Plural von Brust", "bürste", "Gerät mit Borsten, z.B. zum Reinigen"), new Pair("attraktion", "Sehenswürdigkeit", "akttaktion", "vermutlicher Tippfehler"), new Pair("nah", "zu 'nah' (wenig entfernt)", "näh", "zu 'nähen' (mit einem Faden verbinden)"), new Pair("turn", "zu 'turnen'", "turm", "hohes Bauwerk"), new Pair("mit", "Präposition", "miet", "zu 'Miete' (Überlassung gegen Bezahlung)"), new Pair("bart", "Behaarung im Gesicht", "brat", "zu 'braten', z.B. 'Bratkartoffel'"), new Pair("uhr", "Instrument zur Zeitmessung", "ur", "ursprünglich"), new Pair("abschluss", "Ende", "abschuss", "Vorgang des Abschießens, z.B. mit einer Waffe"), new Pair("brache", "verlassenes Grundstück", "branche", "Wirtschaftszweig"), new Pair("wieder", "erneut, wiederholt, nochmal (Wiederholung, Wiedervorlage, ...)", "wider", "gegen, entgegen (Widerwille, Widerstand, Widerspruch, ...)"), new Pair("leer", "ohne Inhalt", "lehr", "bezogen auf Ausbildung und Wissen"), new Pair("gewerbe", "wirtschaftliche Tätigkeit", "gewebe", "gewebter Stoff; Verbund ähnlicher Zellen"), new Pair("schuh", "Fußbekleidung", "schul", "auf die Schule bezogen"), new Pair("klima", "langfristige Wetterzustände", "lima", "Hauptstadt von Peru"), new Pair("modell", "vereinfachtes Abbild der Wirklichkeit", "model", "Fotomodell"), new Pair("treppen", "Folge von Stufen (Mehrzahl)", "truppen", "Armee oder Teil einer Armee (Mehrzahl)"), new Pair("häufigkeit", "Anzahl von Ereignissen", "häutigkeit", "z.B. in Dunkelhäutigkeit"), new Pair("hin", "in Richtung", "hirn", "Gehirn, Denkapparat"), new Pair("verklärung", "Beschönigung, Darstellung in einem besseren Licht", "erklärung", "Darstellung, Erläuterung"), new Pair("spitze", "spitzes Ende eines Gegenstandes", "spritze", "medizinisches Instrument zur Injektion"), new Pair("punk", "Jugendkultur", "punkt", "Satzzeichen"), new Pair("reis", "Nahrungsmittel", "eis", "gefrorenes Wasser"), new Pair("balkan", "Region in Südosteuropa", "balkon", "Plattform, die aus einem Gebäude herausragt"), new Pair("haft", "Freiheitsentzug", "schaft", "-schaft (Element zur Wortbildung)"), new Pair("stande", "zu 'Stand'", "stange", "länglicher Gegenstand") ); public static final GermanyGerman german = new GermanyGerman(); private static GermanSpellerRule spellerRule; private static LinguServices linguServices; private static final List<String> ignoreWords = Arrays.asList("Die", "De"); private static final List<String> blacklistRegex = Arrays.asList( "reisender", // Ägyptenreisender etc. "[a-zöäüß]+sender", // wg. sende/sender, z.B. bremsender, abzulassender "gra(ph|f)ische?", // kosmografisch etc. "gra(ph|f)ische[rsnm]", // kosmografischen etc. "gra(ph|f)s?$", // Elektrokardiograph "gra(ph|f)en", // Elektrokardiographen "gra(ph|f)in", // Demographin/Demografin "gra(ph|f)ik", // Kunstgrafik "gra(ph|f)ie", // Geographie "Gra(ph|f)it" // Grafit/Graphit ); private static final Set<String> blacklist = new HashSet<>(Arrays.asList( "Teilspiegel", // vs Heilspiegel "Preiseseite", // vs Presseseite "Teamfahrers", // vs Teamführers "Supportzeiten", // vs Supportseiten "Schwabenweg", "Datenspende", "Datenspenden", "Designermaske", "Designermasken", "Herdenschutz", "Maskendisziplin", "Maskenmode", "Maskenmoden", "Maskenmoral", "Impfvorrang", "Volksmaske", "Volksmasken", "Testmeilen", // vs Testteilen "Hauptstrand", // vs Hauptstand "Hauptstrands", "Hauptstrandes", "Hüttenschuhe", "Hüttenschuhen", "Hüttenschuhs", "Mietbedingung", "Mietbedingungen", "Modeltyp", "Modeltyps", "Modeltypen", "Musikversand", "Musikversands", "Musikversandes", "Paragrafzeichen", "Paragrafzeichens", "Pflanzenmarkt", "Pflanzenmarkts", "Pflanzenmarktes", "Privatstrand", "Privatstrands", "Privatstrände", "Privatstränden", "Privatstrandes", "Reisessig", "Reisessigs", "Reiswein", "Reisweins", "Reisweine", "Schuhabteilung", "Schuhabteilungen", "Schulfirma", "Schulfirmen", "Schulmagazin", "Schulmagazins", "Schulmagazinen", "Schulmagazinen", "Segelschuhe", "Segelschuhen", "Spitzenhaus", "Spitzenhauses", "Spitzenhäuser", "Spitzenhäusern", "Standgebläse", "Standgebläsen", "Standgebläses", "Standstreifen", "Standstreifens", "Strandfigur", "Strandfoto", "Strandfotos", "Strandkonzert", "Strandkonzerts", "Strandkonzertes", "Strandkonzerte", "Strandkonzerten", "Strandverlust", "Strandverluste", "Strandverlusten", "Tierversand", "Tierversands", "Treppenart", "Treppenarten", "Winterflucht", "Nachtmitte", // vs. Nachtmittel "Gemeindemitte", // vs. Gemeindemittel "Feinbeurteilung", // vs. Feindbeurteilung "Bremssand", "Bratform", "Devisenspritze", "Einkaufszielen", "einnähmt", "hinübernähmen", "maschinennäher", "zentrumsnäher", "Einzelversandes", "Eisbällchen", "Eisenbahnrades", "Eisläufer", "Eisläufern", "Eisläufers", "Fachversand", "Fachversandes", "Feinwahrnehmung", "Feinwahrnehmungen", "Fluchtkapsel", "Fluchtkapseln", "Fluchtschiffe", "Fluchtschiffes", "Fluchtschiffs", "Fluchtschiffen", "Flügeltreppe", "Flügeltreppen", "Fruchtspiel", "Gletschersand", "Gletschersands", "Gletschersandes", "Grafem", "Grafems", "Grafeme", "Grafemen", "grafitgrau", "grafithaltig", "grafithaltige", "grafithaltiger", "grafithaltigen", "grafithaltigem", "grafithaltiges", "grafithaltigeren", "grafithaltigerem", "Reitschuhe", "Reitschuhen", "Nordbalkon", "Ostbalkon", "Südbalkon", "Westbalkon", "Zahngel", "Reinigungsgel", "Schutzname", "Schutznamen", "Gebrauchsname", "Gebrauchsnamen", "Erbname", "Erbnamen", "Datenname", "Datennamen", "Geldnahme", "Geldnahmen", "Kreispokal", "Gründertag", "Korrekturlösung", "Regelschreiber", "Glasreinigern", "Holzstele", "Brandschutz", "Testbahn", "Testbahnen", "Startglocke", "Startglocken", "Ladepunkte", "Kinderpreise", "Kinderpreisen", "Belegungsoptionen", "Brandgebiete", "Brandgebieten", "Innenfell", "Innenfelle", "Batteriepreis", "Alltagsschuhe", "Alltagsschuhen", "Arbeiterschuhe", "Arbeiterschuhen", "Bartvogel", "Abschiedsmail", "Abschiedsmails", "Wohnindex", "Entwicklungsstudio", "Ermittlungsgesetz", "Lindeverfahren", "Stromspender", "Turmverlag", // eigtl. Turm-Verlag, muss hier als Ausnahme aber so stehen "Bäckerlunge", "Reisbeutel", "Reisbeuteln", "Reisbeutels", "Fellnase", "Fellnasen", "Kletterwald", "Kletterwalds", "Lusthöhle", "Lusthöhlen", "Abschlagswert", "Schuhfach", "Schuhfächer", "Spülkanüle", "Spülkanülen", "Tankkosten", "Hangout", "Hangouts", "Kassenloser", "kassenloser", "Reisnadel", "Reisnadeln", "stielloses", "stielloser", "stiellosen", "Beiratsregelung", "Beiratsregelungen", "Kreiskongress", "Lagekosten", "hineinfeiern", "Maskenhersteller", // vs Marken "Wabendesign", "Maskenherstellers", "Maskenherstellern", "Firmenvokabular", "Maskenproduktion", "Maskenpflicht", "Nachmiete", "Ringseil", "Ringseilen", "Jagdschule", "Tachograf", "Tachografs", "Tachografen", "Grafitpulver", "Grafitmine", "Grafitminen", "Nesselstraße", "Reitsachen", "Mehrfachabrechnung", "Stuhlrolle", "Stuhlrollen", "neugestartet", "Vertragskonto", "Männerding", "Restwoche", "Startpakete", // vs Rakete "Startpaketen", // vs Rakete "Suchintention", // vs Sach "Wettglück", // vs Welt "Wettprogramm", // vs Welt "Wettprogramme", // vs Welt "Zählerwechsel", "Zählerwechsels", "Nährstoffleitungen", // vs ...leistungen "Verhandlungskreise", "Verhandlungskreisen", "Mietsuchenden", "Mietsuchende", "Mietsuchender", "Autoboss", "Autobossen", "Testmonat", "Testmonats", "Testmonate", "Naturseife", "Naturseifen", "Ankerkraut", // Firmenname (Lebensmittel) "Ankerkrauts", "Bewerbungstool", "Bewerbungstools", "Elektromarke", "Elektromarken", "Ankerkraut", "Testuser", "Testangeboten", "Testangebots", "Testangebotes", "verkeimt", "verkeimte", "verkeimter", "verkeimtes", "verkeimten", "verkeimtem", "Flugscham", // vs. Flugschau "Kurseinführung", "Januar-Miete", "Februar-Miete", "März-Miete", "April-Miete", "Mai-Miete", "Juni-Miete", "Juli-Miete", "August-Miete", "September-Miete", "Oktober-Miete", "November-Miete", "Dezember-Miete", "Suchindices", "Kirchenfreizeit", "Kirchenfreizeiten", "Erklärbär", "Wettart", "Wettarten", "Einzelwette", "Einzelwetten", "Artikelzeile", "Artikelzeilen", "Echtgeld", "Kartenansicht", "Kartenansichten", "Systemwette", "Systemwetten", "Dachzelt", "Dachzelte", "Badeloch", "Bonusaktion", "Bonusaktionen", "Projektannahme", "Pollenbelastung", "Fastenfenster", "Bauchtasche", "Bauchtaschen", "Zahloption", "Zahloptionen", "Zeckenschutz", "Vertragskonto", "Zeichengrenze", "Zeichengrenzen", "Kartontasche", "Kartontaschen", "Mietbestätigung", "Mietbestätigungen", "Tunnelzelt", "Tunnelzelts", "Tunnelzelte", "Dichtleistung", "Dichtleistungen", "Testkonto", "Testkontos", "Konzernnummer", "Konzernnummern", "Vertragsstunde", "Vertragsstunden", "Zaunträger", "Zaunträgern", "Zaunträgers", "Hallenschuh", "Hallenschuhs", "Hallenschuhe", "Rekrutierungsausgabe", "Rekrutierungsausgaben", "geruchsfreies", "Tafelfolie", "Gartenservice", "Gartenservices", "Rollgerüste", "Rollgerüsten", "Grasabfall", "Grasabfällen", "Ketogrippe", "Gerätehülle", "kaltweiß", "Maskenbefreiung", "Lusttropfen", "Kundenstimme", "Deichschafen", "Industriehefe", "Freizeitschuhe", "Freizeitschuhen", "Trainingsschuhe", "Trainingsschuhen", "Schuhblatt", "Nachbacken", "Wassermelder", "Schutzsegen", "Fischversteigerung", "Fischversteigerungen", "Konfigurationsteile", "Konfigurationsteilen", "Wasserbauch", "Wasserbauchs", "Stadtrad", "Stadtrads", "Seniorenrad", "Seniorenrads", "Bodenplane", "Schwimmschuhe", "Familienstrand", "versiegelbaren", "Überraschungsfeier", "Überraschungsfeiern", "ballseitig", "Genussgarten", "Genussgartens", "Edelsteingarten", "Edelsteingartens", "Insektengarten", "Insektengartens", "Klimakurs", "Klimakurses", "Kursperioden", "Musikreise", "Musikreisen", "Ziegenhof", "Ziegenhofs", "Außendecke", "Außendecken", "Bewegungsbarriere", "Bewegungsbarrieren", "Gerichtsantrag", "Gerichtsantrags", "Gerichtsanträge", "Spezialwette", "Spezialwetten", "Geldmagnet", "Testartikel", "Testartikeln", "Testartikels", "folierte", "foliert", "folierten", "foliertes", "foliertem", "Implementierungsvorgaben", "Bücherzelle", "Bücherzellen", "Cuttermesser", "Cuttermessern", "Cuttermessers", "Kabelsammlung", "Kabelsammlungen", "Schleifschwamm", "Schleifschwamms", "Schleifschwämme", "Teemarke", "Teemarken", "Vorzelt", "Vorzelte", "Supportleitung", // vs leistung "Kursname", "Schmucksorte", "Schmucksorten", "Farbsorte", "Farbsorten", "Donaublick", "Rundhals", "Trittschutz", "Laufhaus", "Wickeltasche", "Bayernliga", "Badsanierung", "Laufbereitschaft", "Geschenkkarten", "Landesklasse", "Firmenlauf", "Satzverlust", "Satzgewinn", "Monatslinsen", "Tageslinsen", "Sexstellung", "Traumbad", "Schlafsystem", "Startspieler", "Tabellenrang", "Heimerfolg", "Dachboxen", "Videotest", "Zugbindung", "Badplanung", "Badschrank", "Reiturlaub", "Zeittraining", "Dichtungssatz", "Wettbörsen", "Bildungspaket", "anklickst", "Frauenlauf", "Problemhaut", "Absperrpfosten", "Regenhülle", "Satzball", "Auswärtsfahrt", "Dichtsatz", "Nutzungserlebnis", "Saumabschluss", "Rundengewinn", "Haussteuerung", "Unterfederung", "Sterneküche", "Wickeltaschen", "Jahreslinsen", "Blutmond", "Badeplattform", "Wettquote", "Haarmaske", "Schlussgang", "Damengrößen", "Hautanalyse", "Außenkamera", "Kuscheldecken", "Feinhefe", "Radstation", "Satzbälle", "gelinkter", "Nacktbild", "Bücherbär", "Winzerhof", "Laufhäuser", "Verbandsklasse", "Rennrunde", "Luftmasche", "Suchfiltern", "Wohndecke", "bespaßt", "Endrohren", "ablutschte", "Waldkatzen", "Sicherheitsweste", "Gelbsperre", "Kopfdichtung", "Wurfzelt", "Gemeinschaftskarten", "Kornkreis", "Bronzerang", "Fensterfolien", "einköpfen", "Einkaufsnacht", "Reiserad", "Leistungsspange", "Ladepunkten", "Breitbänder", "Wochenplaner", "Leserunden", "Königsleiten", "Hochlader", "Lauferlebnis", "Radstrecken", "Kinderlauf", "Bettsystem", "Reifentests", "Fettleder", "Bildungsstreik", "Satzrückstand", "Bürstenköpfe", "Werbegesicht", "Bassreflex", "Postrock", "gelaserten", "Ohrbügel", "Bestweite", "Golfschuhe", "Genussreise", "Barkultur", "Ladepunkt", "Sportreifen", "Begleitdamen", "Tauchgebiet", "Stadttouren", "vermixen", "Suchvorschläge", "Damenmodell", "Putzkittel", "Eistees", "Begleitdame", "Frontmanns", "Katzenbett", "Pizzaöfen", "Sitzerhöhungen", "Golfkurse", "Ventilkappen", "Kinderuhr", "Bachblüte", "rockigem", "Kinderpreis", "Massivhauses", "Golfstar", "Herstellerwertung", "Herznoten", "Geldklammer", "Einzelkatze", "Fellwechsels", "Duftreis", "Jugendpokal", "Werbelüge", "Superzoom", "Inselpark", "Golfschuh", "Schuhwahl", "Schwingtor", "Sexabenteuern", "Insektenhaus", "Ramschniveau", "Verbrenners", "Doppelklingen", "Clubkonzert", "pullert", "Meisterchor", "Bienenfarm", "Windknoten", "Feuchtmann" //name )); // have per-class static list of these and reference that in instance // -> avoid loading word list for every instance, but allow variations in subclasses protected AhoCorasickDoubleArrayTrie<String> ahoCorasickDoubleArrayTrie; protected Map<String, List<Pair>> pairMap; private static final AhoCorasickDoubleArrayTrie<String> prohibitedCompoundRuleSearcher; private static final Map<String, List<Pair>> prohibitedCompoundRulePairMap; static { List<Pair> pairs = new ArrayList<>(); Map<String, List<Pair>> pairMap = new HashMap<>(); addUpperCaseVariants(pairs); addItemsFromConfusionSets(pairs, "/de/confusion_sets.txt", true); prohibitedCompoundRuleSearcher = setupAhoCorasickSearch(pairs, pairMap); prohibitedCompoundRulePairMap = pairMap; } private static void addAllCaseVariants(List<Pair> candidatePairs, Pair lcPair) { candidatePairs.add(new Pair(lcPair.part1, lcPair.part1Desc, lcPair.part2, lcPair.part2Desc)); String ucPart1 = uppercaseFirstChar(lcPair.part1); String ucPart2 = uppercaseFirstChar(lcPair.part2); if (!lcPair.part1.equals(ucPart1) || !lcPair.part2.equals(ucPart2)) { candidatePairs.add(new Pair(ucPart1, lcPair.part1Desc, ucPart2, lcPair.part2Desc)); } } private static void addUpperCaseVariants(List<Pair> pairs) { for (Pair lcPair : lowercasePairs) { if (startsWithUppercase(lcPair.part1)) { throw new IllegalArgumentException("Use all-lowercase word in " + ProhibitedCompoundRule.class + ": " + lcPair.part1); } if (startsWithUppercase(lcPair.part2)) { throw new IllegalArgumentException("Use all-lowercase word in " + ProhibitedCompoundRule.class + ": " + lcPair.part2); } addAllCaseVariants(pairs, lcPair); } } protected static void addItemsFromConfusionSets(List<Pair> pairs, String confusionSetsFile, boolean isUpperCase) { try { ResourceDataBroker dataBroker = JLanguageTool.getDataBroker(); try (InputStream confusionSetStream = dataBroker.getFromResourceDirAsStream(confusionSetsFile)) { ConfusionSetLoader loader = new ConfusionSetLoader(german); Map<String, List<ConfusionPair>> confusionPairs = loader.loadConfusionPairs(confusionSetStream); for (Map.Entry<String, List<ConfusionPair>> entry : confusionPairs.entrySet()) { for (ConfusionPair pair : entry.getValue()) { boolean allUpper = pair.getTerms().stream().allMatch(k -> startsWithUppercase(k.getString()) && !ignoreWords.contains(k.getString())); if (allUpper || !isUpperCase) { List<ConfusionString> cSet = pair.getTerms(); if (cSet.size() != 2) { throw new RuntimeException("Got confusion set with != 2 items: " + cSet); } Iterator<ConfusionString> it = cSet.iterator(); ConfusionString part1 = it.next(); ConfusionString part2 = it.next(); pairs.add(new Pair(part1.getString(), part1.getDescription(), part2.getString(), part2.getDescription())); if (isUpperCase) { pairs.add(new Pair(lowercaseFirstChar(part1.getString()), part1.getDescription(), lowercaseFirstChar(part2.getString()), part2.getDescription())); } else { pairs.add(new Pair(uppercaseFirstChar(part1.getString()), part1.getDescription(), uppercaseFirstChar(part2.getString()), part2.getDescription())); } } } } } } catch (IOException e) { throw new RuntimeException(e); } } protected static AhoCorasickDoubleArrayTrie<String> setupAhoCorasickSearch(List<Pair> pairs, Map<String, List<Pair>> pairMap) { TreeMap<String, String> map = new TreeMap<>(); for (Pair pair : pairs) { map.put(pair.part1, pair.part1); map.put(pair.part2, pair.part2); pairMap.putIfAbsent(pair.part1, new LinkedList<>()); pairMap.putIfAbsent(pair.part2, new LinkedList<>()); pairMap.get(pair.part1).add(pair); pairMap.get(pair.part2).add(pair); } // Build an AhoCorasickDoubleArrayTrie AhoCorasickDoubleArrayTrie<String> ahoCorasickDoubleArrayTrie = new AhoCorasickDoubleArrayTrie<>(); ahoCorasickDoubleArrayTrie.build(map); return ahoCorasickDoubleArrayTrie; } private final BaseLanguageModel lm; private Pair confusionPair = null; // specify single pair for evaluation public ProhibitedCompoundRule(ResourceBundle messages, LanguageModel lm, UserConfig userConfig) { super(messages); this.lm = (BaseLanguageModel) Objects.requireNonNull(lm); super.setCategory(Categories.TYPOS.getCategory(messages)); this.ahoCorasickDoubleArrayTrie = prohibitedCompoundRuleSearcher; this.pairMap = prohibitedCompoundRulePairMap; linguServices = userConfig != null ? userConfig.getLinguServices() : null; spellerRule = linguServices == null ? new GermanSpellerRule(JLanguageTool.getMessageBundle(), german, null, null) : null; addExamplePair(Example.wrong("Da steht eine <marker>Lehrzeile</marker> zu viel."), Example.fixed("Da steht eine <marker>Leerzeile</marker> zu viel.")); } @Override public String getId() { return RULE_ID; } @Override public String getDescription() { return "Markiert wahrscheinlich falsche Komposita wie 'Lehrzeile', wenn 'Leerzeile' häufiger vorkommt."; } @Override public RuleMatch[] match(AnalyzedSentence sentence) throws IOException { List<RuleMatch> ruleMatches = new ArrayList<>(); for (AnalyzedTokenReadings readings : sentence.getTokensWithoutWhitespace()) { String tmpWord = readings.getToken(); List<String> wordsParts = new ArrayList<>(Arrays.asList(tmpWord.split("-"))); int partsStartPos = 0; for (String wordPart : wordsParts) { partsStartPos = getMatches(sentence, ruleMatches, readings, partsStartPos, wordPart, 0); } String noHyphens = removeHyphensAndAdaptCase(tmpWord); if (noHyphens != null) { getMatches(sentence, ruleMatches, readings, 0, noHyphens, tmpWord.length()-noHyphens.length()); } } return toRuleMatchArray(ruleMatches); } private boolean isMisspelled (String word) { return (linguServices == null ? spellerRule.isMisspelled(word) : !linguServices.isCorrectSpell(word, german)); } private int getMatches(AnalyzedSentence sentence, List<RuleMatch> ruleMatches, AnalyzedTokenReadings readings, int partsStartPos, String wordPart, int toPosCorrection) { /* optimizations: only nouns can be compounds all parts are at least 3 characters long -> words must have at least 6 characters */ if ((readings.isTagged() && !readings.hasPartialPosTag("SUB")) && !readings.hasPosTagStartingWith("EIG:") || wordPart.length() <= 6) { // EIG: e.g. "Obstdeutschland" -> "Ostdeutschland" partsStartPos += wordPart.length() + 1; return partsStartPos; } List<Pair> candidatePairs = new ArrayList<>(); // ignore other pair when confusionPair is set (-> running for evaluation) if (confusionPair == null) { List<AhoCorasickDoubleArrayTrie.Hit<String>> wordList = ahoCorasickDoubleArrayTrie.parseText(wordPart); // might get duplicates, but since we only ever allow one match per word it doesn't matter for (AhoCorasickDoubleArrayTrie.Hit<String> hit : wordList) { List<Pair> pair = pairMap.get(hit.value); if (pair != null) { candidatePairs.addAll(pair); } } } else { addAllCaseVariants(candidatePairs, confusionPair); } List<WeightedRuleMatch> weightedMatches = new ArrayList<>(); for (Pair pair : candidatePairs) { String variant = null; if (wordPart.contains(pair.part1)) { variant = wordPart.replaceFirst(pair.part1, pair.part2); } else if (wordPart.contains(pair.part2)) { variant = wordPart.replaceFirst(pair.part2, pair.part1); } //System.out.println(word + " <> " + variant); if (variant == null) { partsStartPos += wordPart.length() + 1; continue; } long wordCount = lm.getCount(wordPart); long variantCount = lm.getCount(variant); //float factor = variantCount / (float)Math.max(wordCount, 1); //System.out.println("word: " + wordPart + " (" + wordCount + "), variant: " + variant + " (" + variantCount + "), factor: " + factor + ", pair: " + pair); if (variantCount > 0 && wordCount == 0 && !blacklist.contains(wordPart) && !isMisspelled(variant) && blacklistRegex.stream().noneMatch(k -> wordPart.matches(".*" + k + ".*"))) { String msg; if (pair.part1Desc != null && pair.part2Desc != null) { msg = "Möglicher Tippfehler. " + uppercaseFirstChar(pair.part1) + ": " + pair.part1Desc + ", " + uppercaseFirstChar(pair.part2) + ": " + pair.part2Desc; } else { msg = "Möglicher Tippfehler: " + pair.part1 + "/" + pair.part2; } int fromPos = readings.getStartPos() + partsStartPos; int toPos = fromPos + wordPart.length() + toPosCorrection; String id = getId() + "_" + cleanId(pair.part1) + "_" + cleanId(pair.part2); RuleMatch match = new RuleMatch(new SpecificIdRule(id, pair.part1, pair.part2, messages), sentence, fromPos, toPos, msg); match.setSuggestedReplacement(variant); weightedMatches.add(new WeightedRuleMatch(variantCount, match)); } } if (weightedMatches.size() > 0) { Collections.sort(weightedMatches); // sort by most popular alternative ruleMatches.add(weightedMatches.get(0).match); } partsStartPos += wordPart.length() + 1; return partsStartPos; } private String cleanId(String id) { return id.toUpperCase().replace("Ä", "AE").replace("Ü", "UE").replace("Ö", "OE"); } /** * ignore automatically loaded pairs and only match using given confusionPair * used for evaluation by ProhibitedCompoundRuleEvaluator * @param confusionPair pair to evaluate, parts are assumed to be lowercase / null to reset */ public void setConfusionPair(Pair confusionPair) { this.confusionPair = confusionPair; } @Nullable String removeHyphensAndAdaptCase(String word) { String[] parts = word.split("-"); if (parts.length > 1) { StringBuilder sb = new StringBuilder(); int i = 0; for (String part : parts) { if (part.length() <= 1) { // don't: S-Bahn -> Sbahn return null; } sb.append(i == 0 ? part : lowercaseFirstChar(part)); i++; } return sb.toString(); } return null; } static class WeightedRuleMatch implements Comparable<WeightedRuleMatch> { long weight; RuleMatch match; WeightedRuleMatch(long weight, RuleMatch match) { this.weight = weight; this.match = match; } @Override public int compareTo(@NotNull WeightedRuleMatch other) { return Long.compare(other.weight, weight); } } public static class Pair { private final String part1; private final String part1Desc; private final String part2; private final String part2Desc; public Pair(String part1, String part1Desc, String part2, String part2Desc) { this.part1 = part1; this.part1Desc = part1Desc; this.part2 = part2; this.part2Desc = part2Desc; } @Override public String toString() { return part1 + "/" + part2; } } static private class SpecificIdRule extends Rule { // don't extend ProhibitedCompoundRule for performance reasons (speller would get re-initialized a lot) private final String id; private final String desc; SpecificIdRule(String id, String part1, String part2, ResourceBundle messages) { this.id = Objects.requireNonNull(id); this.desc = "Markiert wahrscheinlich falsche Komposita mit Teilwort '" + uppercaseFirstChar(part1) + "' statt '" + uppercaseFirstChar(part2) + "' und umgekehrt"; setCategory(Categories.TYPOS.getCategory(messages)); } @Override public String getId() { return id; } @Override public String getDescription() { return desc; } @Override public RuleMatch[] match(AnalyzedSentence sentence) throws IOException { return RuleMatch.EMPTY_ARRAY; } } }
lgpl-2.1
fjalvingh/domui
to.etc.domui/src/main/java/to/etc/domui/component/tbl/SimpleColumnDef.java
13109
/* * DomUI Java User Interface library * Copyright (c) 2010 by Frits Jalvingh, Itris B.V. * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA * * See the "sponsors" file for a list of supporters. * * The latest version of DomUI and related code, support and documentation * can be found at http://www.domui.org/ * The contact for the project is Frits Jalvingh <jal@etc.to>. */ package to.etc.domui.component.tbl; import org.eclipse.jdt.annotation.NonNull; import org.eclipse.jdt.annotation.Nullable; import to.etc.domui.component.meta.NumericPresentation; import to.etc.domui.component.meta.PropertyMetaModel; import to.etc.domui.component.meta.SortableType; import to.etc.domui.component.meta.YesNoType; import to.etc.domui.component.meta.impl.ExpandedDisplayProperty; import to.etc.domui.converter.ConverterRegistry; import to.etc.domui.converter.IConverter; import to.etc.domui.converter.IObjectToStringConverter; import to.etc.domui.dom.css.TextAlign; import to.etc.domui.util.IRenderInto; import to.etc.domui.util.IValueTransformer; /** * Contains data for rendering a column in a data table. * * @author <a href="mailto:jal@etc.to">Frits Jalvingh</a> * Created on Jun 18, 2008 */ final public class SimpleColumnDef<T> { static public final String NOWRAP = "-NOWRAP"; static public final String WRAP = "-WRAP"; static public final String DEFAULTSORT = "-DSORT"; /** The label text, if needed, to use as the column heading */ @Nullable private String m_columnLabel; @NonNull final private ColumnDefList< ? > m_defList; @NonNull final private Class<T> m_columnType; @NonNull private SortableType m_sortable = SortableType.UNKNOWN; /** * If this column is sortable with help from outside code: this defines that helper * which will sort the main model for the table for this column. Watch out: the type * passed to the sort helper is the ROW TYPE, not this-column's type! */ @Nullable private ISortHelper<?> m_sortHelper; @Nullable private String m_width; @Nullable private String m_propertyName; @Nullable private String m_cssClass; @Nullable private String m_headerCssClass; @Deprecated private int m_displayLength; /** When set, specifically define wrap or nowrap. When unset use the default. */ @Nullable private Boolean m_nowrap; /** The thingy which obtains the column's value (as an object) */ @Nullable private IValueTransformer<T> m_valueTransformer; @Nullable private IObjectToStringConverter<T> m_presentationConverter; @NonNull private NumericPresentation m_numericPresentation = NumericPresentation.UNKNOWN; @Nullable private TextAlign m_align; @Nullable private IRenderInto<T> m_contentRenderer; @Nullable private ICellClicked<T> m_cellClicked; @Nullable private String m_renderHint; public <X> SimpleColumnDef(@NonNull ColumnDefList< ? > cdl, @NonNull Class<T> valueClass) { m_columnType = valueClass; m_defList = cdl; } /** * Create a column definition using metadata for the column. * @param pmm */ public SimpleColumnDef(@NonNull ColumnDefList< ? > cdl, @NonNull PropertyMetaModel<T> pmm) { m_defList = cdl; m_columnType = pmm.getActualType(); setColumnLabel(pmm.getDefaultLabel()); setValueTransformer(pmm); // Thing which can obtain the value from the property setPresentationConverter(ConverterRegistry.findBestConverter(pmm)); setSortable(pmm.getSortable()); setPropertyName(pmm.getName()); setNumericPresentation(pmm.getNumericPresentation()); if(pmm.getNowrap() == YesNoType.YES) setNowrap(Boolean.TRUE); } public SimpleColumnDef(@NonNull ColumnDefList< ? > cdl, @NonNull ExpandedDisplayProperty<T> m) { m_defList = cdl; m_columnType = m.getActualType(); setColumnLabel(m.getDefaultLabel()); setValueTransformer(m); // Thing which can obtain the value from the property setPresentationConverter(m.getBestConverter()); setSortable(SortableType.UNSORTABLE); // FIXME From meta pls setSortable(m.getSortable()); setPropertyName(m.getName()); if(m.getName() == null) throw new IllegalStateException("All columns MUST have some name"); setNumericPresentation(m.getNumericPresentation()); setRenderHint(m.getRenderHint()); if(m.getDisplayLength() > 0) setDisplayLength(m.getDisplayLength()); if(m.getNowrap() == YesNoType.YES) setNowrap(Boolean.TRUE); } @Nullable public String getColumnLabel() { return m_columnLabel; } public void setColumnLabel(@Nullable String columnLabel) { label(columnLabel); } <R> T getColumnValue(@NonNull R instance) throws Exception { IValueTransformer<T> valueTransformer = getValueTransformer(); if(valueTransformer == null) return (T) instance; else return valueTransformer.getValue(instance); } @NonNull public Class<T> getColumnType() { return m_columnType; } @NonNull public SortableType getSortable() { return m_sortable; } public void setSortable(@NonNull SortableType sortable) { m_sortable = sortable == null ? SortableType.UNKNOWN : sortable; } @Nullable public String getWidth() { return m_width; } public void setWidth(@Nullable String width) { width(width); } @Nullable public IValueTransformer<T> getValueTransformer() { return m_valueTransformer; } public void setValueTransformer(@Nullable IValueTransformer<T> valueTransformer) { m_valueTransformer = valueTransformer; } /** * Returns the optional converter to use to convert raw object values to some presentation string value. * @return */ @Nullable public IObjectToStringConverter<T> getPresentationConverter() { return m_presentationConverter; } public void setPresentationConverter(@Nullable IConverter<T> valueConverter) { m_presentationConverter = valueConverter; } @Nullable public String getPropertyName() { return m_propertyName; } public void setPropertyName(@Nullable String propertyName) { m_propertyName = propertyName; } @Nullable public IRenderInto<T> getContentRenderer() { return m_contentRenderer; } public void setContentRenderer(@Nullable IRenderInto<T> contentRenderer) { m_contentRenderer = contentRenderer; } /** * When set this defines the css class to set on each value cell for this column. Setting this * does NOT set a css class for the header!! * @return */ @Nullable public String getCssClass() { return m_cssClass; } /** * When set this defines the css class to set on each value cell for this column. Setting this * does NOT set a css class for the header!! * @param cssClass */ public void setCssClass(@Nullable String cssClass) { m_cssClass = cssClass; } /** * When set this defines the css class to set on the header of this column. * @return */ @Nullable public String getHeaderCssClass() { return m_headerCssClass; } /** * When set this defines the css class to set on the header of this column. * * @param headerCssClass */ public void setHeaderCssClass(@Nullable String headerCssClass) { m_headerCssClass = headerCssClass; } /** * Seems nonsense, use width instead. * @return */ @Deprecated public int getDisplayLength() { return m_displayLength; } /** * Seems nonsense, use width instead. * @param displayLength * @return */ @Deprecated public void setDisplayLength(int displayLength) { m_displayLength = displayLength; } @Nullable public Boolean isNowrap() { return m_nowrap; } public void setNowrap(@Nullable Boolean nowrap) { m_nowrap = nowrap; } @Nullable public ICellClicked<T> getCellClicked() { return m_cellClicked; } public void setCellClicked(@Nullable ICellClicked<T> cellClicked) { m_cellClicked = cellClicked; } @NonNull public NumericPresentation getNumericPresentation() { return m_numericPresentation; } public void setNumericPresentation(@NonNull NumericPresentation numericPresentation) { m_numericPresentation = numericPresentation; } @Nullable public TextAlign getAlign() { return m_align; } public void setAlign(@Nullable TextAlign align) { m_align = align; } @Nullable public String getRenderHint() { return m_renderHint; } public void setRenderHint(@Nullable String renderHint) { m_renderHint = renderHint; } /** * If this column is sortable with help from outside code: this defines that helper * which will sort the main model for the table for this column. Watch out: the type * passed to the sort helper is the ROW TYPE, not this-column's type! * @return */ @Nullable public ISortHelper<?> getSortHelper() { return m_sortHelper; } public void setSortHelper(@Nullable ISortHelper<?> sortHelper) { m_sortHelper = sortHelper; } @NonNull @Override public String toString() { return "SimpleColumnDef[" + getPropertyName() + ", type=" + getColumnType() + ", lbl=" + getColumnLabel() + "]"; } /*--------------------------------------------------------------*/ /* CODING: Chainable setters. */ /*--------------------------------------------------------------*/ /** * Set the column header's label. * @param columnLabel * @return */ @NonNull public SimpleColumnDef<T> label(@Nullable String columnLabel) { m_columnLabel = columnLabel; return this; } /** * Set the text align for this column. Defaults depend on the numeric type of the column, if known. * @param align * @return */ @NonNull public SimpleColumnDef<T> align(@NonNull TextAlign align) { m_align = align; return this; } /** * Set the cell click handler. * @param ck * @return */ @NonNull public SimpleColumnDef<T> cellClicked(@NonNull ICellClicked<T> ck) { m_cellClicked = ck; return this; } /** * Set the node content renderer. * @param cr * @return */ @NonNull public SimpleColumnDef<T> renderer(@NonNull IRenderInto<T> cr) { m_contentRenderer = cr; return this; } /** * Set the css class of this column's values. * @param css * @return */ @NonNull public SimpleColumnDef<T> css(@NonNull String css) { m_cssClass = css; return this; } /** * Set the css class of this column's header. * @param css * @return */ @NonNull public SimpleColumnDef<T> cssHeader(@NonNull String css) { m_headerCssClass = css; return this; } /** * Make sure this column's contents are wrapped (by default columns added by {@link RowRenderer} are marked as not wrappable. * @return */ @NonNull public SimpleColumnDef<T> wrap() { m_nowrap = Boolean.FALSE; return this; } /** * Set the column to nowrap. * @return */ @NonNull public SimpleColumnDef<T> nowrap() { m_nowrap = Boolean.TRUE; return this; } /** * Set the numeric presentation for this column. * @param np * @return */ @NonNull public SimpleColumnDef<T> numeric(@NonNull NumericPresentation np) { m_numericPresentation = np; return this; } /** * Set a column value-to-string converter to be used. * @param c * @return */ @NonNull public SimpleColumnDef<T> converter(@NonNull IObjectToStringConverter<T> c) { m_presentationConverter = c; return this; } /** * Set the hint for a column. * @param hint * @return */ @NonNull public SimpleColumnDef<T> hint(@NonNull String hint) { m_renderHint = hint; return this; } /** * Set the default sort order to ascending first. * @return */ @NonNull public SimpleColumnDef<T> ascending() { setSortable(SortableType.SORTABLE_ASC); return this; } /** * Set the default sort order to descending first. * @return */ @NonNull public SimpleColumnDef<T> descending() { setSortable(SortableType.SORTABLE_DESC); return this; } /** * Set this column as the default column to sort on. * @return */ @NonNull public SimpleColumnDef<T> sortdefault() { m_defList.setSortColumn(this); return this; } /** * Set a sort helper to be used for this column. * @param sh * @return */ @NonNull public SimpleColumnDef<T> sort(@NonNull ISortHelper<T> sh) { m_sortHelper = sh; if(m_sortable == SortableType.UNKNOWN) m_sortable = SortableType.SORTABLE_ASC; return this; } /** * Set a value transformer to convert this column value into something else. * @param vt * @return */ @NonNull public SimpleColumnDef<T> transform(@NonNull IValueTransformer<T> vt) { m_valueTransformer = vt; return this; } @NonNull public SimpleColumnDef<T> width(@Nullable String w) { m_width = w; return this; } }
lgpl-2.1
opensagres/xdocreport.eclipse
commons/fr.opensagres.eclipse.forms/src/fr/opensagres/eclipse/forms/widgets/ISearchListener.java
222
package fr.opensagres.eclipse.forms.widgets; import org.eclipse.swt.internal.SWTEventListener; public interface ISearchListener extends SWTEventListener { void modelChanged(Object oldModel, Object newModel); }
lgpl-2.1