repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
MarSik/shelves
backend/server/src/main/java/org/marsik/elshelves/backend/repositories/SanityRepository.java
588
package org.marsik.elshelves.backend.repositories; import org.marsik.elshelves.backend.entities.NamedEntity; import org.marsik.elshelves.backend.entities.Type; import org.springframework.data.jpa.repository.JpaRepository; import org.springframework.data.jpa.repository.Query; import org.springframework.data.querydsl.QueryDslPredicateExecutor; import java.util.UUID; public interface SanityRepository extends JpaRepository<NamedEntity, UUID>, QueryDslPredicateExecutor<NamedEntity> { @Query("SELECT t FROM Type t WHERE t.groups IS EMPTY") Iterable<Type> findOrphanedTypes(); }
agpl-3.0
saep/MONET-bundles
graph/src/com/github/monet/graph/interfaces/Edge.java
154
package com.github.monet.graph.interfaces; /** * Models an edge. * * @author Christopher Morris * */ public interface Edge extends GraphElement { }
agpl-3.0
automenta/java_dann
src/syncleus/dann/learn/pattern/algorithms/frequentpatterns/eclat/AlgoDEclat_Bitset.java
6705
package syncleus.dann.learn.pattern.algorithms.frequentpatterns.eclat; /* This file is copyright (c) 2008-2013 Philippe Fournier-Viger * * This file is part of the SPMF DATA MINING SOFTWARE * (http://www.philippe-fournier-viger.com/spmf). * * SPMF 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. * * SPMF 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 * SPMF. If not, see <http://www.gnu.org/licenses/>. */ import java.util.BitSet; import java.util.Map; import syncleus.dann.learn.pattern.datastructures.triangularmatrix.TriangularMatrix; import syncleus.dann.learn.pattern.input.transaction_database_list_integers.TransactionDatabase; import syncleus.dann.learn.pattern.patterns.itemset_array_integers_with_tids_bitset.Itemset; import syncleus.dann.learn.pattern.patterns.itemset_array_integers_with_tids_bitset.Itemsets; import syncleus.dann.learn.pattern.tools.MemoryLogger; /** * This is an implementation of the dECLAT algorithm. The difference between DECLAT * and ECLAT is that dECLAT utilizes diffsets instead of tidsets. * In this implementation, diffsets are represented as bitsets. * Note that this class is a subclass of the ECLAT algorithm because a lot of * code is the same and we wanted to avoid redundancy. * Note also that implementing diffsets using bitsets may not provide the optimal performance for * dEclat since even if diffsets are smaller than tidsets, as a bitset, they may not be much * smaller. It is thus recommended to try also the regular implementation * * IMPORTANT: dEClat returns Itemsets annotated with their diffsets * rather than tidsets when the user choose to keep the result in memory. * * DEclat was proposed by ZAKI (2000). * <br/><br/> * * See this article for details about ECLAT: * <br/><br/> * * Zaki, M. J. (2000). Scalable algorithms for association mining. Knowledge and Data Engineering, IEEE Transactions on, 12(3), 372-390. * <br/><br/> * * and: <br/><br/> * * M. J. Zaki and K. Gouda. Fast vertical mining using Diffsets. Technical Report 01-1, Computer Science * Dept., Rensselaer Polytechnic Institute, March 2001. * * This version saves the result to a file * or keep it into memory if no output path is provided * by the user to the runAlgorithm method(). * * @see TriangularMatrix * @see TransactionDatabase * @see Itemset * @see Itemsets * @author Philippe Fournier-Viger */ public class AlgoDEclat_Bitset extends AlgoEclat_Bitset{ /** * Print statistics about the algorithm execution to System.out. */ public void printStats() { System.out.println("============= DECLAT vALTERNATE-Bitset - STATS ============="); long temps = endTime - startTimestamp; System.out.println(" Transactions count from database : " + database.size()); System.out.println(" Frequent itemsets count : " + itemsetCount); System.out.println(" Total time ~ " + temps + " ms"); System.out.println(" Maximum memory usage : " + MemoryLogger.getInstance().getMaxMemory() + " mb"); System.out.println("==================================================="); } /** * This method scans the database to calculate the support of each single item * @param database the transaction database * @param mapItemTIDS a map to store the tidset corresponding to each item * @return the maximum item id appearing in this database */ private int calculateSupportSingleItems(TransactionDatabase database, final Map<Integer, BitSetSupport> mapItemTIDS) { // (1) First database pass : calculate diffsets of each item. int maxItemId = 0; // for each transaction for (int i = 0; i < database.size(); i++) { // Add the transaction id to the set of all transaction ids // for each item in that transaction // For each item for (Integer item : database.getTransactions().get(i)) { // Get the current tidset of that item BitSetSupport tids = mapItemTIDS.get(item); // If none, then we create one if(tids == null){ tids = new BitSetSupport(); // For a new item, we sets all the bits of its diffset to true tids.bitset.set(0, database.size(), true); mapItemTIDS.put(item, tids); // we remember the largest item seen until now if (item > maxItemId) { maxItemId = item; } } //We set to false the bit corresponding to this transaction // in the diffset of that item tids.bitset.set(i, false); // END DECLAT // we increase the support of that item tids.support++; } } return maxItemId; } /** * Perform the intersection of two diffsets for itemsets containing more than one item. * @param tidsetI the first diffset * @param tidsetJ the second diffset * @return the resulting diffset and its support */ private BitSetSupport performAND(BitSetSupport tidsetI, BitSetSupport tidsetJ) { // Create the new diffset BitSetSupport bitsetSupportIJ = new BitSetSupport(); // Calculate the diffset bitsetSupportIJ.bitset = (BitSet)tidsetJ.bitset.clone(); bitsetSupportIJ.bitset.andNot(tidsetI.bitset); // Calculate the support bitsetSupportIJ.support = tidsetI.support - bitsetSupportIJ.bitset.cardinality(); // return the new diffset return bitsetSupportIJ; } /** * Perform the intersection of two diffsets representing single items. * @param tidsetI the first diffset * @param tidsetJ the second diffset * @param supportIJ the support of the intersection (already known) so it does not need to * be calculated again * @return the resulting diffset and its support */ private BitSetSupport performANDFirstTime(BitSetSupport tidsetI, BitSetSupport tidsetJ, int supportIJ) { // Create the new diffset and perform the logical AND to intersect the diffsets BitSetSupport bitsetSupportIJ = new BitSetSupport(); //Calculate the diffset bitsetSupportIJ.bitset = (BitSet)tidsetJ.bitset.clone(); bitsetSupportIJ.bitset.andNot(tidsetI.bitset); // Calculate the support bitsetSupportIJ.support = tidsetI.support - bitsetSupportIJ.bitset.cardinality(); // return the new tidset return bitsetSupportIJ; } }
agpl-3.0
jankotek/asterope
aladin/cds/tools/parser/DivideOp.java
1062
// Copyright 2010 - UDS/CNRS // The Aladin program is distributed under the terms // of the GNU General Public License version 3. // //This file is part of Aladin. // // Aladin is free software: you can redistribute it and/or modify // it under the terms of the GNU General Public License as published by // the Free Software Foundation, version 3 of the License. // // Aladin 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. // // The GNU General Public License is available in COPYING file // along with Aladin. // package cds.tools.parser; /** Opérateur 'division' * @author Thomas Boch [CDS] * @kickoff October 2006 */ public final class DivideOp extends BinaryOperateur { public DivideOp(AbstractOperateur op1, AbstractOperateur op2) { super(op1, op2); } public final double compute() { return ops[0].compute()/ops[1].compute(); } }
agpl-3.0
jpmml/jpmml-sklearn
pmml-sklearn/src/main/java/sklearn/preprocessing/OneHotEncoder.java
3546
/* * Copyright (c) 2015 Villu Ruusmann * * This file is part of JPMML-SkLearn * * JPMML-SkLearn 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. * * JPMML-SkLearn 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 JPMML-SkLearn. If not, see <http://www.gnu.org/licenses/>. */ package sklearn.preprocessing; import java.util.ArrayList; import java.util.List; import com.google.common.collect.ContiguousSet; import com.google.common.collect.DiscreteDomain; import com.google.common.collect.Range; import org.dmg.pmml.DataType; import org.dmg.pmml.OpType; import org.jpmml.converter.BinaryFeature; import org.jpmml.converter.CategoricalFeature; import org.jpmml.converter.Feature; import org.jpmml.converter.TypeUtil; import org.jpmml.converter.ValueUtil; import org.jpmml.converter.WildcardFeature; import org.jpmml.python.ClassDictUtil; import org.jpmml.sklearn.SkLearnEncoder; import sklearn.Transformer; public class OneHotEncoder extends Transformer { public OneHotEncoder(String module, String name){ super(module, name); } @Override public OpType getOpType(){ return OpType.CATEGORICAL; } @Override public DataType getDataType(){ List<? extends Number> values = getValues(); return TypeUtil.getDataType(values, DataType.INTEGER); } @Override public List<Feature> encodeFeatures(List<Feature> features, SkLearnEncoder encoder){ List<? extends Number> values = getValues(); ClassDictUtil.checkSize(1, features); Feature feature = features.get(0); List<Feature> result = new ArrayList<>(); if(feature instanceof CategoricalFeature){ CategoricalFeature categoricalFeature = (CategoricalFeature)feature; ClassDictUtil.checkSize(values, categoricalFeature.getValues()); for(int i = 0; i < values.size(); i++){ result.add(new BinaryFeature(encoder, categoricalFeature, categoricalFeature.getValue(i))); } } else if(feature instanceof WildcardFeature){ WildcardFeature wildcardFeature = (WildcardFeature)feature; List<Integer> categories = new ArrayList<>(); for(int i = 0; i < values.size(); i++){ Number value = values.get(i); Integer category = ValueUtil.asInt(value); categories.add(category); result.add(new BinaryFeature(encoder, wildcardFeature, category)); } wildcardFeature.toCategoricalFeature(categories); } else { throw new IllegalArgumentException(); } return result; } public List<? extends Number> getValues(){ List<Integer> featureSizes = getFeatureSizes(); ClassDictUtil.checkSize(1, featureSizes); Object numberOfValues = getOptionalScalar("n_values"); if(("auto").equals(numberOfValues)){ return getActiveFeatures(); } Integer featureSize = featureSizes.get(0); List<Integer> result = new ArrayList<>(); result.addAll(ContiguousSet.create(Range.closedOpen(0, featureSize), DiscreteDomain.integers())); return result; } public List<? extends Number> getActiveFeatures(){ return getNumberArray("active_features_"); } public List<Integer> getFeatureSizes(){ return getIntegerArray("n_values_"); } }
agpl-3.0
lpellegr/programming
programming-extensions/programming-extension-amqp/src/main/java/org/objectweb/proactive/extensions/amqp/remoteobject/AbstractFindQueuesRPCClient.java
4333
/* * ################################################################ * * ProActive Parallel Suite(TM): The Java(TM) library for * Parallel, Distributed, Multi-Core Computing for * Enterprise Grids & Clouds * * Copyright (C) 1997-2012 INRIA/University of * Nice-Sophia Antipolis/ActiveEon * Contact: proactive@ow2.org or contact@activeeon.com * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; version 3 of * the License. * * 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 * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA * * If needed, contact us to obtain a release under GPL Version 2 or 3 * or a different license than the AGPL. * * Initial developer(s): The ActiveEon Team * http://www.activeeon.com/ * Contributor(s): * * ################################################################ * $$ACTIVEEON_INITIAL_DEV$$ */ package org.objectweb.proactive.extensions.amqp.remoteobject; import java.io.IOException; import java.net.URI; import java.util.ArrayList; import java.util.List; import org.objectweb.proactive.utils.TimeoutAccounter; import com.rabbitmq.client.AMQP.BasicProperties; import com.rabbitmq.client.Channel; import com.rabbitmq.client.QueueingConsumer; /** * AMQP specification does not provide a way to list existing queues. However the Remote Object Factory * is expected to provide such a feature. To overcome the limitation a custom discovery mechanism * has been introduced. When created, each remote object creates dedicated queue and binds * it to the to the global fanout exchange. To discover all remote objects message with * special type is sent to this exchange, and as reply all remote objects should send its * URLs. * <p> * Abstract class was introduced since since some parts of communication * algorithm should be handled differently for 'amqp' and 'amqp-federation' * protocols. AbstractFindQueuesRPCClient implements general discover algorithm common * for both AMQP protocols. * * @author ProActive team * @since 5.2.0 * */ public abstract class AbstractFindQueuesRPCClient { public static String DISCOVERY_QUEUES_MESSAGE_TYPE = "proactive.discover_queues"; protected abstract ReusableChannel getReusableChannel(URI uri) throws IOException; protected abstract String createReplyQueue(Channel channel) throws IOException; public final List<URI> discover(URI uri, String exchangeName, long timeout) throws Exception { ReusableChannel reusableChannel = getReusableChannel(uri); try { Channel channel = reusableChannel.getChannel(); String replyQueueName = createReplyQueue(channel); QueueingConsumer consumer = new QueueingConsumer(channel); String consumerTag = channel.basicConsume(replyQueueName, true, consumer); List<URI> response = new ArrayList<URI>(); BasicProperties props = new BasicProperties.Builder().replyTo(replyQueueName) .type(DISCOVERY_QUEUES_MESSAGE_TYPE).build(); channel.basicPublish(exchangeName, "", props, null); TimeoutAccounter time = TimeoutAccounter.getAccounter(timeout); while (!time.isTimeoutElapsed()) { QueueingConsumer.Delivery delivery = consumer.nextDelivery(200); if (delivery != null) { URI u = URI.create(new String(delivery.getBody())); response.add(u); } } // stop consuming, this also should delete temporary queue channel.basicCancel(consumerTag); reusableChannel.returnChannel(); return response; } catch (Exception e) { reusableChannel.close(); throw e; } } }
agpl-3.0
pvendil/c2c-common
src/main/java/org/certificateservices/custom/c2x/ieee1609dot2/datastructs/p2p/Ieee1609dot2Peer2PeerPDU.java
2695
/************************************************************************ * * * Certificate Service - Car2Car Core * * * * This software is free software; you can redistribute it and/or * * modify it under the terms of the GNU Affero General Public License * * License as published by the Free Software Foundation; either * * version 3 of the License, or any later version. * * * * See terms of license at gnu.org. * * * *************************************************************************/ package org.certificateservices.custom.c2x.ieee1609dot2.datastructs.p2p; import org.certificateservices.custom.c2x.asn1.coer.COERSequence; import org.certificateservices.custom.c2x.ieee1609dot2.datastructs.basic.Uint8; /** * This data structure defines the structure of Ieee1609dot2Peer2PeerPDU. * * @author Philip Vendil, p.vendil@cgi.com * */ public class Ieee1609dot2Peer2PeerPDU extends COERSequence { public static final int DEFAULT_VERSION = 1; private static final long serialVersionUID = 1L; private static final int VERSION = 0; private static final int CONTENT = 1; /** * Constructor used when decoding */ public Ieee1609dot2Peer2PeerPDU(){ super(false,2); init(); } /** * Constructor used when encoding */ public Ieee1609dot2Peer2PeerPDU(int version, Ieee1609dot2Peer2PeerPDUContent content){ super(false,2); init(); set(VERSION, new Uint8(version)); set(CONTENT, content); } /** * Constructor used when encoding with default version */ public Ieee1609dot2Peer2PeerPDU(Ieee1609dot2Peer2PeerPDUContent content){ this(DEFAULT_VERSION,content); } /** * * @return version */ public int getVersion(){ return (int) ((Uint8) get(VERSION)).getValueAsLong(); } /** * * @return content */ public Ieee1609dot2Peer2PeerPDUContent getContent(){ return (Ieee1609dot2Peer2PeerPDUContent) get(CONTENT); } private void init(){ addField(VERSION, false, new Uint8(), null); addField(CONTENT, false, new Ieee1609dot2Peer2PeerPDUContent(), null); } @Override public String toString() { return "Ieee1609dot2Peer2PeerPDU [\n" + " version=" + getVersion() + ",\n" + " content=" + getContent().toString().replace("Ieee1609dot2Peer2PeerPDUContent ", "").replaceAll("\n", "\n ") + "\n]"; } }
agpl-3.0
simonzhangsm/voltdb
tests/frontend/org/voltdb/rejoin/TestStreamSnapshotRequestConfig.java
4734
/* This file is part of VoltDB. * Copyright (C) 2008-2018 VoltDB Inc. * * Permission is hereby granted, free of charge, to any person obtaining * a copy of this software and associated documentation files (the * "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, * distribute, sublicense, and/or sell copies of the Software, and to * permit persons to whom the Software is furnished to do so, subject to * the following conditions: * * The above copyright notice and this permission notice shall be * included in all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. */ package org.voltdb.rejoin; import static junit.framework.Assert.assertNull; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import java.io.IOException; import java.util.Arrays; import org.json_voltpatches.JSONException; import org.json_voltpatches.JSONObject; import org.json_voltpatches.JSONStringer; import org.junit.BeforeClass; import org.junit.Test; import org.voltdb.benchmark.tpcc.TPCCProjectBuilder; import org.voltdb.catalog.Database; import org.voltdb.sysprocs.saverestore.SnapshotUtil; import org.voltdb.sysprocs.saverestore.StreamSnapshotRequestConfig; import com.google_voltpatches.common.collect.HashMultimap; import com.google_voltpatches.common.collect.Multimap; import com.google_voltpatches.common.collect.Sets; public class TestStreamSnapshotRequestConfig { private static Database database; @BeforeClass public static void setupBeforeClass() throws IOException { database = TPCCProjectBuilder.getTPCCSchemaCatalog() .getClusters().get("cluster") .getDatabases().get("database"); } @Test public void testRejoinConfigRoundtrip() throws JSONException { Multimap<Long, Long> pairs = HashMultimap.create(); pairs.put(1l, 3l); pairs.put(1l, 4l); pairs.put(2l, 3l); StreamSnapshotRequestConfig.Stream stream = new StreamSnapshotRequestConfig.Stream(pairs, null); JSONStringer stringer = new JSONStringer(); stringer.object(); new StreamSnapshotRequestConfig(SnapshotUtil.getTablesToSave(database), Arrays.asList(stream), false).toJSONString(stringer); stringer.endObject(); StreamSnapshotRequestConfig config = new StreamSnapshotRequestConfig(new JSONObject(stringer.toString()), database); assertEquals(1, config.streams.size()); assertFalse(config.shouldTruncate); assertNull(config.streams.get(0).newPartition); assertEquals(Sets.newHashSet(3l, 4l), Sets.newHashSet(config.streams.get(0).streamPairs.get(1l))); assertEquals(Sets.newHashSet(3l), Sets.newHashSet(config.streams.get(0).streamPairs.get(2l))); } @Test public void testJoinConfigRoundtrip() throws JSONException { Multimap<Long, Long> pairs = HashMultimap.create(); pairs.put(1l, 3l); pairs.put(1l, 4l); pairs.put(2l, 3l); StreamSnapshotRequestConfig.Stream stream = new StreamSnapshotRequestConfig.Stream(pairs, 5); JSONStringer stringer = new JSONStringer(); stringer.object(); new StreamSnapshotRequestConfig(SnapshotUtil.getTablesToSave(database), Arrays.asList(stream), false).toJSONString(stringer); stringer.endObject(); StreamSnapshotRequestConfig config = new StreamSnapshotRequestConfig(new JSONObject(stringer.toString()), database); assertEquals(1, config.streams.size()); assertFalse(config.shouldTruncate); assertEquals(5, config.streams.get(0).newPartition.intValue()); assertEquals(Sets.newHashSet(3l, 4l), Sets.newHashSet(config.streams.get(0).streamPairs.get(1l))); assertEquals(Sets.newHashSet(3l), Sets.newHashSet(config.streams.get(0).streamPairs.get(2l))); } }
agpl-3.0
dzc34/Asqatasun
rules/rules-rgaa3.2016/src/main/java/org/asqatasun/rules/rgaa32016/Rgaa32016Rule040103.java
1532
/* * 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.rgaa32016; import org.asqatasun.ruleimplementation.AbstractNotTestedRuleImplementation; /** * Implementation of the rule 4.1.3 of the referential RGAA 3.2016 * <br/> * For more details about the implementation, refer to <a href="http://doc.asqatasun.org/en/90_Rules/rgaa3.2016/04.Multimedia/Rule-4-1-3.html">the rule 4.1.3 design page.</a> * @see <a href="http://references.modernisation.gouv.fr/rgaa-accessibilite/2016/criteres.html#test-4-1-3">4.1.3 rule specification</a> * * @author */ public class Rgaa32016Rule040103 extends AbstractNotTestedRuleImplementation { /** * Default constructor */ public Rgaa32016Rule040103 () { super(); } }
agpl-3.0
simplyianm/SuperPlots
src/main/java/com/simplyian/superplots/plot/PlotUpgrade.java
484
package com.simplyian.superplots.plot; /** * Contains different plot upgrades. * * @author simplyianm */ public enum PlotUpgrade { /** * Town upgrade. */ TOWN(50000); private int cost; PlotUpgrade(int cost) { this.cost = cost; } /** * Gets the cost of this upgrade. * * @return */ public int getCost() { return cost; } @Override public String toString() { return name(); } }
agpl-3.0
uniteddiversity/mycollab
mycollab-web/src/main/java/com/esofthead/mycollab/module/user/accountsettings/profile/view/ProfileReadPresenter.java
1888
/** * This file is part of mycollab-web. * * mycollab-web 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-web 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-web. If not, see <http://www.gnu.org/licenses/>. */ package com.esofthead.mycollab.module.user.accountsettings.profile.view; import com.esofthead.mycollab.module.user.accountsettings.view.AccountSettingBreadcrumb; import com.esofthead.mycollab.module.user.domain.User; import com.esofthead.mycollab.vaadin.AppContext; import com.esofthead.mycollab.vaadin.mvp.ScreenData; import com.esofthead.mycollab.vaadin.mvp.ViewManager; import com.esofthead.mycollab.vaadin.ui.AbstractPresenter; import com.vaadin.ui.ComponentContainer; /** * * @author MyCollab Ltd. * @since 1.0 * */ public class ProfileReadPresenter extends AbstractPresenter<ProfileReadView> { private static final long serialVersionUID = 1L; public ProfileReadPresenter() { super(ProfileReadView.class); } @Override protected void onGo(ComponentContainer container, ScreenData<?> data) { ProfileContainer profileContainer = (ProfileContainer) container; profileContainer.removeAllComponents(); profileContainer.addComponent(view.getWidget()); User currentUser = AppContext.getUser(); view.previewItem(currentUser); AccountSettingBreadcrumb breadcrumb = ViewManager .getCacheComponent(AccountSettingBreadcrumb.class); breadcrumb.gotoProfile(); } }
agpl-3.0
Metatavu/kunta-api-spec
java-client-generated/src/main/java/fi/metatavu/kuntaapi/client/model/Municipality.java
3374
/** * Kunta API * Solution to combine municipality services under single API. * * OpenAPI spec version: 0.1.0 * * * NOTE: This class is auto generated by the swagger code generator program. * https://github.com/swagger-api/swagger-codegen.git * Do not edit the class manually. * * 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 fi.metatavu.kuntaapi.client.model; import java.util.Objects; import com.google.gson.annotations.SerializedName; import fi.metatavu.kuntaapi.client.model.LocalizedValue; import io.swagger.annotations.ApiModel; import io.swagger.annotations.ApiModelProperty; import java.util.ArrayList; import java.util.List; /** * Municipality */ @javax.annotation.Generated(value = "class io.swagger.codegen.languages.JavaClientCodegen", date = "2019-07-08T18:08:24.691+03:00") public class Municipality { @SerializedName("code") private String code = null; @SerializedName("names") private List<LocalizedValue> names = new ArrayList<LocalizedValue>(); public Municipality code(String code) { this.code = code; return this; } /** * Municipality code (like 491 or 091). * @return code **/ @ApiModelProperty(example = "null", value = "Municipality code (like 491 or 091).") public String getCode() { return code; } public void setCode(String code) { this.code = code; } public Municipality names(List<LocalizedValue> names) { this.names = names; return this; } public Municipality addNamesItem(LocalizedValue namesItem) { this.names.add(namesItem); return this; } /** * Get names * @return names **/ @ApiModelProperty(example = "null", value = "") public List<LocalizedValue> getNames() { return names; } public void setNames(List<LocalizedValue> names) { this.names = names; } @Override public boolean equals(java.lang.Object o) { if (this == o) { return true; } if (o == null || getClass() != o.getClass()) { return false; } Municipality municipality = (Municipality) o; return Objects.equals(this.code, municipality.code) && Objects.equals(this.names, municipality.names); } @Override public int hashCode() { return Objects.hash(code, names); } @Override public String toString() { StringBuilder sb = new StringBuilder(); sb.append("class Municipality {\n"); sb.append(" code: ").append(toIndentedString(code)).append("\n"); sb.append(" names: ").append(toIndentedString(names)).append("\n"); sb.append("}"); return sb.toString(); } /** * Convert the given object to string with each line indented by 4 spaces * (except the first line). */ private String toIndentedString(java.lang.Object o) { if (o == null) { return "null"; } return o.toString().replace("\n", "\n "); } }
agpl-3.0
cm-is-dog/rapidminer-studio-core
src/main/java/com/rapidminer/operator/nio/file/RepositoryBlobObject.java
4485
/** * 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.rapidminer.operator.nio.file; import com.rapidminer.operator.OperatorException; import com.rapidminer.repository.BlobEntry; import com.rapidminer.repository.Entry; import com.rapidminer.repository.RepositoryException; import com.rapidminer.repository.RepositoryLocation; import com.rapidminer.tools.Tools; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; /** * Simple implementation of a {@link FileObject} backed by a {@link RepositoryLocation}. The * repository entry has to be of type 'blob'. * * @author Nils Woehler, Marius Helf */ public class RepositoryBlobObject extends FileObject { private static final long serialVersionUID = 1L; private RepositoryLocation location; private File file = null; /** * Instantiates a new Repository blob object. * * @param location the location */ public RepositoryBlobObject(RepositoryLocation location) { super(); this.location = location; } @Override public InputStream openStream() throws OperatorException { BlobEntry blobEntry; try { Entry entry = location.locateEntry(); if (entry != null) { if (entry instanceof BlobEntry) { blobEntry = (BlobEntry) entry; return blobEntry.openInputStream(); } else { throw new OperatorException("942", null, location.getAbsoluteLocation(), "blob", entry.getType()); } } else { throw new OperatorException("312", null, location.getAbsoluteLocation(), "entry does not exist"); } } catch (RepositoryException e) { throw new OperatorException("319", e, location.getAbsoluteLocation()); } } @Override public File getFile() throws OperatorException { if (file == null) { try { file = File.createTempFile("rm_file_", ".dump"); FileOutputStream fos = new FileOutputStream(file); BlobEntry blobEntry; try { Entry entry = location.locateEntry(); if (entry != null) { if (entry instanceof BlobEntry) { blobEntry = (BlobEntry) entry; } else { throw new OperatorException("942", null, location.getAbsoluteLocation(), "blob", entry.getType()); } } else { throw new OperatorException("312", null, location.getAbsoluteLocation(), "entry does not exist"); } InputStream in = blobEntry.openInputStream(); try { Tools.copyStreamSynchronously(in, fos, true); file.deleteOnExit(); } finally { in.close(); } } finally { fos.close(); } } catch (IOException e) { throw new OperatorException("303", e, file, e.getMessage()); } catch (RepositoryException e) { throw new OperatorException("319", e, location.getAbsoluteLocation()); } } return file; } /** * Firstly, this method calls {@link #getFile()}. As the file usually exists in the repository, * it is simply accessed. If it does not exist, a temporary file is created. Secondly, the * length of the file is returned. */ @Override public long getLength() throws OperatorException { // There is no easier way to receive the length, as the underlying BlobEntry only supports // an InputStream return getFile().length(); } @Override public String toString() { return file != null ? "Repository location stored in temporary file: " + file.getAbsolutePath() : "Repository location: " + location.getAbsoluteLocation(); } @Override protected void finalize() throws Throwable { if (file != null) { file.delete(); } super.finalize(); } }
agpl-3.0
ama-axelor/axelor-business-suite
axelor-human-resource/src/main/java/com/axelor/apps/hr/web/AppHumanResourceController.java
1245
/* * Axelor Business Solutions * * Copyright (C) 2019 Axelor (<http://axelor.com>). * * 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/>. */ package com.axelor.apps.hr.web; import com.axelor.apps.hr.service.app.AppHumanResourceService; import com.axelor.rpc.ActionRequest; import com.axelor.rpc.ActionResponse; import com.google.inject.Inject; import com.google.inject.Singleton; @Singleton public class AppHumanResourceController { @Inject private AppHumanResourceService appHumanResourceService; public void generateHrConfigurations(ActionRequest request, ActionResponse response) { appHumanResourceService.generateHrConfigurations(); response.setReload(true); } }
agpl-3.0
paulmartel/voltdb
third_party/java/src/com/google_voltpatches/common/collect/RangeMap.java
5116
/* * Copyright (C) 2012 The Guava Authors * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.google_voltpatches.common.collect; import com.google_voltpatches.common.annotations.Beta; import java.util.Map; import javax.annotation_voltpatches.Nullable; /** * A mapping from disjoint nonempty ranges to non-null values. Queries look up the value * associated with the range (if any) that contains a specified key. * * <p>In contrast to {@link RangeSet}, no "coalescing" is done of {@linkplain * Range#isConnected(Range) connected} ranges, even if they are mapped to the same value. * * @author Louis Wasserman * @since 14.0 */ @Beta public interface RangeMap<K extends Comparable, V> { /** * Returns the value associated with the specified key, or {@code null} if there is no * such value. * * <p>Specifically, if any range in this range map contains the specified key, the value * associated with that range is returned. */ @Nullable V get(K key); /** * Returns the range containing this key and its associated value, if such a range is present * in the range map, or {@code null} otherwise. */ @Nullable Map.Entry<Range<K>, V> getEntry(K key); /** * Returns the minimal range {@linkplain Range#encloses(Range) enclosing} the ranges * in this {@code RangeMap}. * * @throws NoSuchElementException if this range map is empty */ Range<K> span(); /** * Maps a range to a specified value (optional operation). * * <p>Specifically, after a call to {@code put(range, value)}, if * {@link Range#contains(Comparable) range.contains(k)}, then {@link #get(Comparable) get(k)} * will return {@code value}. * * <p>If {@code range} {@linkplain Range#isEmpty() is empty}, then this is a no-op. */ void put(Range<K> range, V value); /** * Puts all the associations from {@code rangeMap} into this range map (optional operation). */ void putAll(RangeMap<K, V> rangeMap); /** * Removes all associations from this range map (optional operation). */ void clear(); /** * Removes all associations from this range map in the specified range (optional operation). * * <p>If {@code !range.contains(k)}, {@link #get(Comparable) get(k)} will return the same result * before and after a call to {@code remove(range)}. If {@code range.contains(k)}, then * after a call to {@code remove(range)}, {@code get(k)} will return {@code null}. */ void remove(Range<K> range); /** * Returns a view of this range map as an unmodifiable {@code Map<Range<K>, V>}. * Modifications to this range map are guaranteed to read through to the returned {@code Map}. * * <p>The returned {@code Map} iterates over entries in ascending order of the bounds of the * {@code Range} entries. * * <p>It is guaranteed that no empty ranges will be in the returned {@code Map}. */ Map<Range<K>, V> asMapOfRanges(); /** * Returns a view of this range map as an unmodifiable {@code Map<Range<K>, V>}. * Modifications to this range map are guaranteed to read through to the returned {@code Map}. * * <p>The returned {@code Map} iterates over entries in descending order of the bounds of the * {@code Range} entries. * * <p>It is guaranteed that no empty ranges will be in the returned {@code Map}. * * @since 19.0 */ Map<Range<K>, V> asDescendingMapOfRanges(); /** * Returns a view of the part of this range map that intersects with {@code range}. * * <p>For example, if {@code rangeMap} had the entries * {@code [1, 5] => "foo", (6, 8) => "bar", (10, \u2025) => "baz"} * then {@code rangeMap.subRangeMap(Range.open(3, 12))} would return a range map * with the entries {@code (3, 5) => "foo", (6, 8) => "bar", (10, 12) => "baz"}. * * <p>The returned range map supports all optional operations that this range map supports, * except for {@code asMapOfRanges().iterator().remove()}. * * <p>The returned range map will throw an {@link IllegalArgumentException} on an attempt to * insert a range not {@linkplain Range#encloses(Range) enclosed} by {@code range}. */ RangeMap<K, V> subRangeMap(Range<K> range); /** * Returns {@code true} if {@code obj} is another {@code RangeMap} that has an equivalent * {@link #asMapOfRanges()}. */ @Override boolean equals(@Nullable Object o); /** * Returns {@code asMapOfRanges().hashCode()}. */ @Override int hashCode(); /** * Returns a readable string representation of this range map. */ @Override String toString(); }
agpl-3.0
opensourceBIM/BIMserver
PluginBase/generated/org/bimserver/models/ifc4/impl/IfcSurfaceReinforcementAreaImpl.java
8855
/** * 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.ifc4.impl; /****************************************************************************** * 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/>}. *****************************************************************************/ import org.bimserver.models.ifc4.Ifc4Package; import org.bimserver.models.ifc4.IfcSurfaceReinforcementArea; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EClass; /** * <!-- begin-user-doc --> * An implementation of the model object '<em><b>Ifc Surface Reinforcement Area</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link org.bimserver.models.ifc4.impl.IfcSurfaceReinforcementAreaImpl#getSurfaceReinforcement1 <em>Surface Reinforcement1</em>}</li> * <li>{@link org.bimserver.models.ifc4.impl.IfcSurfaceReinforcementAreaImpl#getSurfaceReinforcement1AsString <em>Surface Reinforcement1 As String</em>}</li> * <li>{@link org.bimserver.models.ifc4.impl.IfcSurfaceReinforcementAreaImpl#getSurfaceReinforcement2 <em>Surface Reinforcement2</em>}</li> * <li>{@link org.bimserver.models.ifc4.impl.IfcSurfaceReinforcementAreaImpl#getSurfaceReinforcement2AsString <em>Surface Reinforcement2 As String</em>}</li> * <li>{@link org.bimserver.models.ifc4.impl.IfcSurfaceReinforcementAreaImpl#getShearReinforcement <em>Shear Reinforcement</em>}</li> * <li>{@link org.bimserver.models.ifc4.impl.IfcSurfaceReinforcementAreaImpl#getShearReinforcementAsString <em>Shear Reinforcement As String</em>}</li> * </ul> * * @generated */ public class IfcSurfaceReinforcementAreaImpl extends IfcStructuralLoadOrResultImpl implements IfcSurfaceReinforcementArea { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected IfcSurfaceReinforcementAreaImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return Ifc4Package.Literals.IFC_SURFACE_REINFORCEMENT_AREA; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public EList<Double> getSurfaceReinforcement1() { return (EList<Double>) eGet(Ifc4Package.Literals.IFC_SURFACE_REINFORCEMENT_AREA__SURFACE_REINFORCEMENT1, true); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void unsetSurfaceReinforcement1() { eUnset(Ifc4Package.Literals.IFC_SURFACE_REINFORCEMENT_AREA__SURFACE_REINFORCEMENT1); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean isSetSurfaceReinforcement1() { return eIsSet(Ifc4Package.Literals.IFC_SURFACE_REINFORCEMENT_AREA__SURFACE_REINFORCEMENT1); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public EList<String> getSurfaceReinforcement1AsString() { return (EList<String>) eGet(Ifc4Package.Literals.IFC_SURFACE_REINFORCEMENT_AREA__SURFACE_REINFORCEMENT1_AS_STRING, true); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void unsetSurfaceReinforcement1AsString() { eUnset(Ifc4Package.Literals.IFC_SURFACE_REINFORCEMENT_AREA__SURFACE_REINFORCEMENT1_AS_STRING); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean isSetSurfaceReinforcement1AsString() { return eIsSet(Ifc4Package.Literals.IFC_SURFACE_REINFORCEMENT_AREA__SURFACE_REINFORCEMENT1_AS_STRING); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public EList<Double> getSurfaceReinforcement2() { return (EList<Double>) eGet(Ifc4Package.Literals.IFC_SURFACE_REINFORCEMENT_AREA__SURFACE_REINFORCEMENT2, true); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void unsetSurfaceReinforcement2() { eUnset(Ifc4Package.Literals.IFC_SURFACE_REINFORCEMENT_AREA__SURFACE_REINFORCEMENT2); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean isSetSurfaceReinforcement2() { return eIsSet(Ifc4Package.Literals.IFC_SURFACE_REINFORCEMENT_AREA__SURFACE_REINFORCEMENT2); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public EList<String> getSurfaceReinforcement2AsString() { return (EList<String>) eGet(Ifc4Package.Literals.IFC_SURFACE_REINFORCEMENT_AREA__SURFACE_REINFORCEMENT2_AS_STRING, true); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void unsetSurfaceReinforcement2AsString() { eUnset(Ifc4Package.Literals.IFC_SURFACE_REINFORCEMENT_AREA__SURFACE_REINFORCEMENT2_AS_STRING); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean isSetSurfaceReinforcement2AsString() { return eIsSet(Ifc4Package.Literals.IFC_SURFACE_REINFORCEMENT_AREA__SURFACE_REINFORCEMENT2_AS_STRING); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public double getShearReinforcement() { return (Double) eGet(Ifc4Package.Literals.IFC_SURFACE_REINFORCEMENT_AREA__SHEAR_REINFORCEMENT, true); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void setShearReinforcement(double newShearReinforcement) { eSet(Ifc4Package.Literals.IFC_SURFACE_REINFORCEMENT_AREA__SHEAR_REINFORCEMENT, newShearReinforcement); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void unsetShearReinforcement() { eUnset(Ifc4Package.Literals.IFC_SURFACE_REINFORCEMENT_AREA__SHEAR_REINFORCEMENT); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean isSetShearReinforcement() { return eIsSet(Ifc4Package.Literals.IFC_SURFACE_REINFORCEMENT_AREA__SHEAR_REINFORCEMENT); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String getShearReinforcementAsString() { return (String) eGet(Ifc4Package.Literals.IFC_SURFACE_REINFORCEMENT_AREA__SHEAR_REINFORCEMENT_AS_STRING, true); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void setShearReinforcementAsString(String newShearReinforcementAsString) { eSet(Ifc4Package.Literals.IFC_SURFACE_REINFORCEMENT_AREA__SHEAR_REINFORCEMENT_AS_STRING, newShearReinforcementAsString); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void unsetShearReinforcementAsString() { eUnset(Ifc4Package.Literals.IFC_SURFACE_REINFORCEMENT_AREA__SHEAR_REINFORCEMENT_AS_STRING); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean isSetShearReinforcementAsString() { return eIsSet(Ifc4Package.Literals.IFC_SURFACE_REINFORCEMENT_AREA__SHEAR_REINFORCEMENT_AS_STRING); } } //IfcSurfaceReinforcementAreaImpl
agpl-3.0
alamarre/maestro-media-center
services/maestro-core-service/src/main/java/org/maestromedia/services/core/apis/MaestroApiConstants.java
166
package org.maestromedia.services.core.apis; public class MaestroApiConstants { public static String base = ""; public static String[] versions = {"1.0"}; }
agpl-3.0
d3b-center/pedcbioportal
web/src/main/java/org/cbioportal/web/parameter/StudyViewFilter.java
3481
package org.cbioportal.web.parameter; import java.io.Serializable; import java.util.List; import java.util.Objects; import javax.validation.constraints.AssertTrue; import javax.validation.constraints.Size; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonInclude.Include; @JsonInclude(Include.NON_NULL) public class StudyViewFilter implements Serializable { @Size(min = 1) private List<SampleIdentifier> sampleIdentifiers; @Size(min = 1) private List<String> studyIds; private List<ClinicalDataEqualityFilter> clinicalDataEqualityFilters; private List<ClinicalDataIntervalFilter> clinicalDataIntervalFilters; private List<MutationGeneFilter> mutatedGenes; private List<CopyNumberGeneFilter> cnaGenes; private Boolean withMutationData; private Boolean withCNAData; private RectangleBounds mutationCountVsCNASelection; @AssertTrue private boolean isEitherSampleIdentifiersOrStudyIdsPresent() { return sampleIdentifiers != null ^ studyIds != null; } @AssertTrue private boolean isEitherValueOrRangePresentInClinicalDataIntervalFilters() { long invalidCount = 0; if (clinicalDataIntervalFilters != null) { invalidCount = clinicalDataIntervalFilters.stream() .flatMap(f -> f.getValues().stream()) .filter(Objects::nonNull) .filter(v -> v.getValue() != null == (v.getStart() != null || v.getEnd() != null)) .count(); } return invalidCount == 0; } public List<SampleIdentifier> getSampleIdentifiers() { return sampleIdentifiers; } public void setSampleIdentifiers(List<SampleIdentifier> sampleIdentifiers) { this.sampleIdentifiers = sampleIdentifiers; } public List<String> getStudyIds() { return studyIds; } public void setStudyIds(List<String> studyIds) { this.studyIds = studyIds; } public List<ClinicalDataEqualityFilter> getClinicalDataEqualityFilters() { return clinicalDataEqualityFilters; } public void setClinicalDataEqualityFilters(List<ClinicalDataEqualityFilter> clinicalDataEqualityFilters) { this.clinicalDataEqualityFilters = clinicalDataEqualityFilters; } public List<ClinicalDataIntervalFilter> getClinicalDataIntervalFilters() { return clinicalDataIntervalFilters; } public void setClinicalDataIntervalFilters(List<ClinicalDataIntervalFilter> clinicalDataIntervalFilters) { this.clinicalDataIntervalFilters = clinicalDataIntervalFilters; } public List<MutationGeneFilter> getMutatedGenes() { return mutatedGenes; } public void setMutatedGenes(List<MutationGeneFilter> mutatedGenes) { this.mutatedGenes = mutatedGenes; } public List<CopyNumberGeneFilter> getCnaGenes() { return cnaGenes; } public void setCnaGenes(List<CopyNumberGeneFilter> cnaGenes) { this.cnaGenes = cnaGenes; } public Boolean getWithMutationData() { return withMutationData; } public void setWithMutationData(Boolean withMutationData) { this.withMutationData = withMutationData; } public Boolean getWithCNAData() { return withCNAData; } public void setWithCNAData(Boolean withCNAData) { this.withCNAData = withCNAData; } public RectangleBounds getMutationCountVsCNASelection() { return mutationCountVsCNASelection; } public void setMutationCountVsCNASelection(RectangleBounds mutationCountVsCNASelection) { this.mutationCountVsCNASelection = mutationCountVsCNASelection; } }
agpl-3.0
Orichievac/FallenGalaxy
src-server/fr/fg/server/action/allies/Delegate.java
2911
/* Copyright 2010 Nicolas Bosc This file is part of Fallen Galaxy. Fallen Galaxy 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. Fallen Galaxy 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 Fallen Galaxy. If not, see <http://www.gnu.org/licenses/>. */ package fr.fg.server.action.allies; import java.util.Map; import fr.fg.server.core.UpdateTools; import fr.fg.server.data.Ally; import fr.fg.server.data.DataAccess; import fr.fg.server.data.Event; import fr.fg.server.data.IllegalOperationException; import fr.fg.server.data.Player; import fr.fg.server.servlet.Action; import fr.fg.server.servlet.Session; public class Delegate extends Action { //--------------------------------------------------------- CONSTANTES --// //---------------------------------------------------------- ATTRIBUTS --// //------------------------------------------------------ CONSTRUCTEURS --// //----------------------------------------------------------- METHODES --// @Override protected String execute(Player player, Map<String, Object> params, Session session) throws Exception { Player target = DataAccess.getPlayerById((Integer)params.get("target")); Ally ally = player.getAlly(); if( ally==null ) throw new IllegalOperationException("Vous n'appartanez à aucune alliance."); boolean ok = false; for(Player leader : ally.getLeaders()){ if(player == leader && player.getAllyRank()>1) { ok = true; } } if(ok==false) throw new IllegalOperationException("Vous n'êtes pas leader de votre alliance."); if(player.getAllyRank()==target.getAllyRank()) throw new IllegalOperationException("Vous ne pouvez pas échanger votre rang d'alliance avec un membre qui a le même que vous."); int targetAllyRank = target.getAllyRank(); synchronized(target.getLock()){ target = DataAccess.getEditable(target); target.setAllyRank(player.getAllyRank()); target.save(); } synchronized(player.getLock()){ player = DataAccess.getEditable(player); player.setAllyRank(targetAllyRank); player.save(); } Event event = new Event( Event.EVENT_LEADER_DELEGATE, Event.TARGET_ALLY, ally.getId(), 0, -1, -1, player.getLogin(), target.getLogin() ); event.save(); UpdateTools.queueNewEventUpdate(ally.getMembers(), false); return FORWARD_SUCCESS; } //--------------------------------------------------- METHODES PRIVEES --// }
agpl-3.0
quikkian-ua-devops/will-financials
kfs-kns/src/main/java/org/kuali/kfs/krad/comparator/TemporalValueComparator.java
1972
/* * The Kuali Financial System, a comprehensive financial management system for higher education. * * Copyright 2005-2017 Kuali, 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 this program. If not, see <http://www.gnu.org/licenses/>. */ package org.kuali.kfs.krad.comparator; import org.kuali.rice.core.web.format.DateFormatter; import java.io.Serializable; import java.util.Comparator; import java.util.Date; public class TemporalValueComparator implements Comparator, Serializable { private static final TemporalValueComparator theInstance = new TemporalValueComparator(); public TemporalValueComparator() { } public static TemporalValueComparator getInstance() { return theInstance; } public int compare(Object o1, Object o2) { // null guard. non-null value is greater. equal if both are null if (null == o1 || null == o2) { return null == o1 && null == o2 ? 0 : null == o1 ? -1 : 1; } String s1 = (String) o1; String s2 = (String) o2; DateFormatter f1 = new DateFormatter(); Date d1 = (Date) f1.convertFromPresentationFormat(s1); Date d2 = (Date) f1.convertFromPresentationFormat(s2); if (null == d1 || null == d2) { return null == d1 && null == d2 ? 0 : null == d1 ? -1 : 1; } return d1.equals(d2) ? 0 : d1.before(d2) ? -1 : 1; } }
agpl-3.0
shenan4321/BIMplatform
generated/cn/dlb/bim/models/ifc4/IfcParameterizedProfileDef.java
3021
/** * 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; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Ifc Parameterized Profile Def</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * </p> * <ul> * <li>{@link cn.dlb.bim.models.ifc4.IfcParameterizedProfileDef#getPosition <em>Position</em>}</li> * </ul> * * @see cn.dlb.bim.models.ifc4.Ifc4Package#getIfcParameterizedProfileDef() * @model * @generated */ public interface IfcParameterizedProfileDef extends IfcProfileDef { /** * Returns the value of the '<em><b>Position</b></em>' reference. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Position</em>' reference isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Position</em>' reference. * @see #isSetPosition() * @see #unsetPosition() * @see #setPosition(IfcAxis2Placement2D) * @see cn.dlb.bim.models.ifc4.Ifc4Package#getIfcParameterizedProfileDef_Position() * @model unsettable="true" * @generated */ IfcAxis2Placement2D getPosition(); /** * Sets the value of the '{@link cn.dlb.bim.models.ifc4.IfcParameterizedProfileDef#getPosition <em>Position</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Position</em>' reference. * @see #isSetPosition() * @see #unsetPosition() * @see #getPosition() * @generated */ void setPosition(IfcAxis2Placement2D value); /** * Unsets the value of the '{@link cn.dlb.bim.models.ifc4.IfcParameterizedProfileDef#getPosition <em>Position</em>}' reference. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #isSetPosition() * @see #getPosition() * @see #setPosition(IfcAxis2Placement2D) * @generated */ void unsetPosition(); /** * Returns whether the value of the '{@link cn.dlb.bim.models.ifc4.IfcParameterizedProfileDef#getPosition <em>Position</em>}' reference is set. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @return whether the value of the '<em>Position</em>' reference is set. * @see #unsetPosition() * @see #getPosition() * @see #setPosition(IfcAxis2Placement2D) * @generated */ boolean isSetPosition(); } // IfcParameterizedProfileDef
agpl-3.0
Bram28/LEGUP
code/edu/rpi/phil/legup/newgui/JustificationAppliedListener.java
458
package edu.rpi.phil.legup.newgui; import edu.rpi.phil.legup.BoardState; import edu.rpi.phil.legup.Justification; /** * Justification(rule, case rule, contradiction) applied * */ public interface JustificationAppliedListener { /** * A justification has been applied * @param state The current board state * @param j The justification that was applied */ public void justificationApplied(BoardState state, Justification j); }
agpl-3.0
autermann/enviroCar-server
mongo/src/main/java/org/envirocar/server/mongo/dao/MongoMeasurementDao.java
13498
/* * Copyright (C) 2013-2018 The enviroCar project * * 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.envirocar.server.mongo.dao; import static java.util.stream.Collectors.toList; import java.util.ArrayList; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.stream.StreamSupport; import org.bson.BSONObject; import org.bson.types.ObjectId; import org.envirocar.server.core.SpatialFilter; import org.envirocar.server.core.SpatialFilter.SpatialFilterOperator; import org.envirocar.server.core.TemporalFilter; import org.envirocar.server.core.dao.MeasurementDao; import org.envirocar.server.core.entities.Measurement; import org.envirocar.server.core.entities.Measurements; import org.envirocar.server.core.entities.Track; import org.envirocar.server.core.entities.User; import org.envirocar.server.core.exception.GeometryConverterException; import org.envirocar.server.core.filter.MeasurementFilter; import org.envirocar.server.core.util.GeometryConverter; import org.envirocar.server.core.util.pagination.Pagination; import org.envirocar.server.mongo.MongoDB; import org.envirocar.server.mongo.entity.MongoMeasurement; import org.envirocar.server.mongo.entity.MongoTrack; import org.envirocar.server.mongo.entity.MongoUser; import org.envirocar.server.mongo.util.MongoUtils; import org.envirocar.server.mongo.util.MorphiaUtils; import org.mongodb.morphia.Datastore; import org.mongodb.morphia.Key; import org.mongodb.morphia.mapping.Mapper; import org.mongodb.morphia.query.FindOptions; import org.mongodb.morphia.query.MorphiaIterator; import org.mongodb.morphia.query.Query; import org.mongodb.morphia.query.QueryImpl; import org.mongodb.morphia.query.UpdateResults; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.google.inject.Inject; import com.mongodb.AggregationOptions; import com.mongodb.BasicDBList; import com.mongodb.BasicDBObject; import com.mongodb.BasicDBObjectBuilder; import com.mongodb.Cursor; import com.mongodb.DBCollection; import com.mongodb.DBCursor; import com.mongodb.DBDecoderFactory; import com.mongodb.DBObject; import com.mongodb.DBRef; import com.mongodb.WriteResult; import com.vividsolutions.jts.geom.Geometry; /** * TODO JavaDoc * * @author Arne de Wall */ public class MongoMeasurementDao extends AbstractMongoDao<ObjectId, MongoMeasurement, Measurements> implements MeasurementDao { public static final String ID = Mapper.ID_KEY; private static final Logger log = LoggerFactory .getLogger(MongoMeasurementDao.class); private static final String TRACKS = "tracks"; private static final String TRACK_NAME_PATH = MongoUtils .path(TRACKS, MongoMeasurement.TRACK, MongoMeasurement.IDENTIFIER); private static final String TRACK_NAME_VALUE = MongoUtils.valueOf(TRACK_NAME_PATH); public static final String TRACK_VALUE = MongoUtils.valueOf(MongoMeasurement.TRACK); private final MongoDB mongoDB; private final GeometryConverter<BSONObject> geometryConverter; @Inject private MongoTrackDao trackDao; @Inject protected MongoMeasurementDao(MongoDB mongoDB, GeometryConverter<BSONObject> geometryConverter) { super(MongoMeasurement.class, mongoDB); this.mongoDB = mongoDB; this.geometryConverter = geometryConverter; } @Override public MongoMeasurement create(Measurement measurement) { return save(measurement); } @Override public MongoMeasurement save(Measurement measurement) { MongoMeasurement mongoMeasurement = (MongoMeasurement) measurement; save(mongoMeasurement); return mongoMeasurement; } @Override public void delete(Measurement m) { delete(((MongoMeasurement) m).getId()); if (m.hasTrack()) { updateTrackTimeForDeletedMeasurement(m); } } public void updateTrackTimeForDeletedMeasurement(Measurement m) { boolean update = false; Track track = m.getTrack(); if (track.hasBegin() && m.getTime().equals(track.getBegin())) { Iterator<MongoMeasurement> it = q() .field(MongoMeasurement.TRACK).equal(key(track)) .order(MongoMeasurement.TIME) .fetch(new FindOptions().limit(1)); MongoMeasurement newBegin = it.hasNext() ? it.next() : null; track.setBegin(newBegin == null ? null : newBegin.getTime()); update = true; } if (track.hasEnd() && m.getTime().equals(track.getEnd())) { Iterator<MongoMeasurement> it = q() .field(MongoMeasurement.TRACK).equal(key(track)) .order(MongoUtils.reverse(MongoMeasurement.TIME)) .fetch(new FindOptions().limit(1)); MongoMeasurement newEnd = it.hasNext() ? it.next() : null; track.setEnd(newEnd == null ? null : newEnd.getTime()); update = true; } if (update) { trackDao.save(track); } } @Override public Measurements get(MeasurementFilter request) { if (request.hasSpatialFilter()) { //needed because of lacking geo2d support in morphia return getMongo(request); } else { return getMorphia(request); } } private Measurements getMorphia(MeasurementFilter request) { Query<MongoMeasurement> q = q().order(MongoMeasurement.TIME); if (request.hasTrack()) { q.field(MongoMeasurement.TRACK).equal(key(request.getTrack())); } if (request.hasUser()) { q.field(MongoMeasurement.USER).equal(key(request.getUser())); } if (request.hasTemporalFilter()) { MorphiaUtils.temporalFilter(q.field(MongoMeasurement.TIME), request.getTemporalFilter()); } return fetch(q, request.getPagination()); } private Measurements getMongo(MeasurementFilter request) { BasicDBObjectBuilder q = new BasicDBObjectBuilder(); if (request.hasSpatialFilter()) { SpatialFilter sf = request.getSpatialFilter(); try { q.add(MongoMeasurement.GEOMETRY, MongoUtils.spatialFilter(sf, geometryConverter)); } catch (GeometryConverterException e) { log.error("Error while applying spatial filter: {}", e.getLocalizedMessage()); } } if (request.hasTrack()) { q.add(MongoMeasurement.TRACK, ref(request.getTrack())); } if (request.hasUser()) { q.add(MongoMeasurement.USER, ref(request.getUser())); } if (request.hasTemporalFilter()) { q.add(MongoMeasurement.TIME, MongoUtils.temporalFilter(request.getTemporalFilter())); } return query(q.get(), request.getPagination()); } @Override public Measurement getById(String id) { ObjectId oid; try { oid = new ObjectId(id); } catch (IllegalArgumentException e) { return null; } return get(oid); } void removeUser(MongoUser user) { UpdateResults result = update( q().field(MongoMeasurement.USER).equal(key(user)), up().unset(MongoMeasurement.USER)); if (result.getWriteResult() != null && !result.getWriteResult().wasAcknowledged()) { log.error("Error removing user {} from measurement: {}", user, result.getWriteResult()); } else { log.debug("Removed user {} from {} measurements", user, result.getUpdatedCount()); } } void deleteUser(MongoUser user) { WriteResult result = delete(q().field(MongoTrack.USER).equal(key(user))); if (result.wasAcknowledged()) { log.debug("Removed user {} from {} measurement", user, result.getN()); } else { log.error("Error removing user {} from measurement: {}", user, result); } } @Override protected Measurements createPaginatedIterable(Iterable<MongoMeasurement> i, Pagination p, long count) { return Measurements.from(i).withPagination(p).withElements(count).build(); } void removeTrack(MongoTrack track) { WriteResult delete = delete(q().field(MongoMeasurement.TRACK).equal(key(track))); if (delete.wasAcknowledged()) { log.debug("Removed track {} from {} measurements", track, delete.getN()); } else { log.error("Error removing track {} from measurements: {}", track, delete); } } List<Key<MongoTrack>> getTrackKeysByBbox(MeasurementFilter filter) { ArrayList<DBObject> ops = new ArrayList<>(4); if (filter.hasSpatialFilter()) { SpatialFilter sf = filter.getSpatialFilter(); if (sf.getOperator() == SpatialFilterOperator.BBOX) { ops.add(matchGeometry(filter.getSpatialFilter().getGeom())); } //TODO add further spatial filters } if (filter.hasUser()) { ops.add(matchUser(filter.getUser())); } if (filter.hasTrack()) { ops.add(matchTrack(filter.getTrack())); } if (filter.hasTemporalFilter()) { ops.add(matchTime(filter.getTemporalFilter())); } ops.add(project()); ops.add(group()); return toKeyList(aggregate(ops)); } private Iterable<DBObject> aggregate(List<DBObject> ops) { AggregationOptions options = AggregationOptions.builder().build(); DBCollection collection = mongoDB.getDatastore().getCollection(MongoMeasurement.class); try (Cursor cursor = collection.aggregate(ops, options)) { LinkedList<DBObject> list = new LinkedList<>(); cursor.forEachRemaining(list::add); return list; } } private DBObject matchGeometry(Geometry polygon) { return MongoUtils.match(MongoMeasurement.GEOMETRY, withinGeometry(polygon)); } private DBObject matchUser(User user) { return MongoUtils.match(MongoMeasurement.USER, ref(user)); } private DBObject matchTrack(Track track) { return MongoUtils.match(MongoMeasurement.TRACK, ref(track)); } private DBObject matchTime(TemporalFilter tf) { return MongoUtils.match(MongoMeasurement.TIME, MongoUtils.temporalFilter(tf)); } private DBObject withinGeometry(Geometry polygon) { try { return MongoUtils.geoWithin(geometryConverter.encode(polygon)); } catch (GeometryConverterException e) { throw new RuntimeException(e); } } private DBObject project() { return MongoUtils.project(new BasicDBObject(MongoMeasurement.TRACK, 1)); } private DBObject group() { BasicDBObject fields = new BasicDBObject(); fields.put(ID, TRACK_NAME_VALUE); fields.put(TRACKS, MongoUtils.addToSet(TRACK_VALUE)); return MongoUtils.group(fields); } protected List<Key<MongoTrack>> toKeyList(Iterable<DBObject> res) { return StreamSupport.stream(res.spliterator(), false) .map(obj -> (BasicDBList) obj.get(TRACKS)) .flatMap(BasicDBList::stream) .map(refObj -> (DBRef) refObj) .map(getMapper()::<MongoTrack>refToKey) .collect(toList()); } private Measurements query(DBObject query, Pagination p) { final Mapper mapper = this.mongoDB.getMapper(); final Datastore ds = this.mongoDB.getDatastore(); final DBCollection coll = ds.getCollection(MongoMeasurement.class); DBCursor cursor = coll.find(query); long count = 0; DBDecoderFactory dbDecoderFactory = coll.getDBDecoderFactory(); if (dbDecoderFactory == null) { dbDecoderFactory = mongoDB.getMongoClient() .getMongoClientOptions() .getDbDecoderFactory(); } cursor.setDecoderFactory(dbDecoderFactory); if (p != null) { count = coll.count(query); if (p.getBegin() > 0) { cursor.skip((int) p.getBegin()); } if (p.getLimit() > 0) { cursor.limit((int) p.getLimit()); } } cursor.sort(QueryImpl.parseFieldsString(MongoMeasurement.TIME, MongoMeasurement.class, mapper, true)); Iterable<MongoMeasurement> i = new MorphiaIterator<>(ds, cursor, mapper, MongoMeasurement.class, coll.getName(), mapper.createEntityCache()); return createPaginatedIterable(i, p, count); } }
agpl-3.0
CBSoft2016/Aplicativo_CBSoft2016
app/src/main/java/com/applications/fronchetti/cbsoft2016/Fragmentos/Minicursos.java
7877
package com.applications.fronchetti.cbsoft2016.Fragmentos; import android.app.Dialog; import android.content.Intent; import android.os.Bundle; import android.app.Fragment; import android.provider.CalendarContract; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.AdapterView; import android.widget.Button; import android.widget.ListView; import android.provider.CalendarContract.Events; import android.widget.TextView; import com.applications.fronchetti.cbsoft2016.Adapters.MinicursosAdapter; import com.applications.fronchetti.cbsoft2016.R; import com.mikepenz.fontawesome_typeface_library.FontAwesome; import org.json.JSONArray; import org.json.JSONException; import org.json.JSONObject; import java.io.IOException; import java.io.InputStream; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.List; public class Minicursos extends Fragment { public Minicursos() { // Required empty public constructor } @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); if (getArguments() != null) { } } @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment_minicursos, container, false); final List<com.applications.fronchetti.cbsoft2016.Adapters.Minicursos> Minicursos = new ArrayList<>(); try { JSONObject obj = new JSONObject(loadJSONFromAsset()); JSONArray m_jArry = obj.getJSONArray("minicursos"); ArrayList<HashMap<String, String>> formList = new ArrayList<HashMap<String, String>>(); HashMap<String, String> m_li; for (int i = 0; i < m_jArry.length(); i++) { JSONObject jo_inside = m_jArry.getJSONObject(i); String nome = jo_inside.getString("titulo"); String horario = jo_inside.getString("horario"); String data = jo_inside.getString("data"); String descricao = jo_inside.getString("descricao"); String localdetrabalho = jo_inside.getString("localtrabalho"); String local = jo_inside.getString("local"); String instrutor = jo_inside.getString("instrutor"); String imagem = jo_inside.getString("imagem"); String url = jo_inside.getString("url"); Minicursos.add(new com.applications.fronchetti.cbsoft2016.Adapters.Minicursos(nome, horario, data, descricao, local, instrutor, localdetrabalho, imagem, url)); m_li = new HashMap<String, String>(); m_li.put("titulo", nome); m_li.put("local", local); m_li.put("horario", horario); m_li.put("data", data); m_li.put("descricao", descricao); m_li.put("localtrabalho", localdetrabalho); m_li.put("imagem", imagem); m_li.put("url", url); m_li.put("instrutor", instrutor); formList.add(m_li); } } catch (JSONException e) { e.printStackTrace(); } MinicursosAdapter adapter = new MinicursosAdapter(getActivity(), R.layout.fragment_minicursos_item, Minicursos); ListView Lista = (ListView) view.findViewById(R.id.listView_minicursos); Lista.setOnItemClickListener(new AdapterView.OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { final com.applications.fronchetti.cbsoft2016.Adapters.Minicursos minicursos = Minicursos.get(position); // custom dialog final Dialog dialog = new Dialog(getActivity()); dialog.setContentView(R.layout.fragment_minicursos_dialog); TextView nome_minicurso = (TextView) dialog.findViewById(R.id.textViewNomeMinicurso); nome_minicurso.setText(minicursos.getTitulo()); TextView local_minicurso = (TextView) dialog.findViewById(R.id.textViewLocal); local_minicurso.setText(minicursos.getLocal()); TextView data_minicurso = (TextView) dialog.findViewById(R.id.textViewData); data_minicurso.setText(minicursos.getData()); TextView palestrante_minicurso = (TextView) dialog.findViewById(R.id.textViewMinistrante); palestrante_minicurso.setText(minicursos.getInstrutor()); TextView descricao_minicurso = (TextView) dialog.findViewById(R.id.textViewDescricao); descricao_minicurso.setText(minicursos.getDescricao()); Button button_agendar = (Button) dialog.findViewById(R.id.f_agendar_button); button_agendar.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { String titulo = minicursos.getTitulo(); String local = minicursos.getLocal(); String descricao = minicursos.getDescricao(); String date = minicursos.getData(); String[] separated_date = date.split("-"); int ano = Integer.parseInt(separated_date[0]); int mes = Integer.parseInt(separated_date[1]); int dia = Integer.parseInt(separated_date[2]); String hour = minicursos.getHorario(); String [] separated_hour = hour.split(":"); int hours = Integer.parseInt(separated_hour[0]); int minutes = Integer.parseInt(separated_hour[1]); calendarMinicursos(titulo, local, descricao, ano, mes, dia, hours, minutes); } }); dialog.show(); } }); Lista.setAdapter(adapter); return view; } public String loadJSONFromAsset() { String json = null; try { InputStream is = getActivity().getAssets().open("minicursos.json"); int size = is.available(); byte[] buffer = new byte[size]; is.read(buffer); is.close(); json = new String(buffer, "UTF-8"); } catch (IOException ex) { ex.printStackTrace(); return null; } return json; } public void calendarMinicursos(String titulo, String local, String descricao, int ano, int mes, int dia, int horas, int minutos){ Calendar beginTime = Calendar.getInstance(); beginTime.set(ano, mes-1, dia, horas, minutos); Calendar endtime = Calendar.getInstance(); endtime.set(ano, mes-1, dia, horas+1, minutos); Intent intent_calendar = new Intent(Intent.ACTION_INSERT); intent_calendar.setData(Events.CONTENT_URI); //Configurações do evento. intent_calendar.putExtra(Events.TITLE, titulo); intent_calendar.putExtra(Events.EVENT_LOCATION, local); intent_calendar.putExtra(Events.DESCRIPTION, descricao); intent_calendar.putExtra(CalendarContract.EXTRA_EVENT_BEGIN_TIME, beginTime.getTimeInMillis()); intent_calendar.putExtra(CalendarContract.EXTRA_EVENT_END_TIME, endtime.getTimeInMillis()); startActivity(intent_calendar); } }
agpl-3.0
podd/podd-redesign
api/src/main/java/com/github/podd/api/data/SSHFileReference.java
1756
/** * PODD is an OWL ontology database used for scientific project management * * Copyright (C) 2009-2013 The University Of Queensland * * 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.github.podd.api.data; /** * Encapsulates SSH File References that are tracked inside of PODD Artifacts. * * @author Peter Ansell p_ansell@yahoo.com * */ public interface SSHFileReference extends DataReference { /** * @return The "filename" component which is needed to identify and locate this SSH file * reference. */ String getFilename(); /** * @return The "path" component which is needed to identify and locate this SSH file reference. */ String getPath(); /** * @param filename * The "filename" component which is needed to identify and locate this SSH file * reference. */ void setFilename(final String filename); /** * @param path * The "path" component which is needed to identify and locate this SSH file * reference. */ void setPath(final String path); }
agpl-3.0
automenta/narchy
nar/src/test/java/nars/nal/nal1/NAL1Deprecated.java
713
package nars.nal.nal1; import nars.test.NALTest; import nars.test.TestNAR; import org.junit.jupiter.api.Disabled; import org.junit.jupiter.api.Test; @Disabled public class NAL1Deprecated extends NALTest { static final int cycles = 20; @Test @Disabled void inheritanceToSimilarity3() { TestNAR tester = test; tester.believe("<swan --> bird>", 0.9f, 0.9f); tester.ask("<bird <-> swan>"); tester.mustBelieve(cycles, "<bird <-> swan>", 0.9f, 0.45f); } @Test @Disabled void conversion() { test.believe("<bird --> swimmer>") .ask("<swimmer --> bird>") .mustOutput(cycles, "<swimmer --> bird>. %1.00;0.47%"); } }
agpl-3.0
metabit/bitsquare
core/src/main/java/io/bitsquare/btc/pricefeed/GetPriceRequest.java
2723
package io.bitsquare.btc.pricefeed; import com.google.common.util.concurrent.*; import io.bitsquare.btc.pricefeed.providers.PriceProvider; import io.bitsquare.common.util.Utilities; import org.jetbrains.annotations.NotNull; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import java.util.Map; class GetPriceRequest { private static final Logger log = LoggerFactory.getLogger(GetPriceRequest.class); private static final ListeningExecutorService executorService = Utilities.getListeningExecutorService("GetPriceRequest", 3, 5, 10 * 60); public GetPriceRequest() { } public SettableFuture<Map<String, MarketPrice>> requestAllPrices(PriceProvider provider) { final SettableFuture<Map<String, MarketPrice>> resultFuture = SettableFuture.create(); ListenableFuture<Map<String, MarketPrice>> future = executorService.submit(() -> { Thread.currentThread().setName("requestAllPrices-" + provider.toString()); return provider.getAllPrices(); }); Futures.addCallback(future, new FutureCallback<Map<String, MarketPrice>>() { public void onSuccess(Map<String, MarketPrice> marketPrice) { log.debug("Received marketPrice of {}\nfrom provider {}", marketPrice, provider); resultFuture.set(marketPrice); } public void onFailure(@NotNull Throwable throwable) { resultFuture.setException(throwable); } }); return resultFuture; } public SettableFuture<MarketPrice> requestPrice(String currencyCode, PriceProvider provider) { final SettableFuture<MarketPrice> resultFuture = SettableFuture.create(); return requestPrice(currencyCode, provider, resultFuture); } private SettableFuture<MarketPrice> requestPrice(String currencyCode, PriceProvider provider, SettableFuture<MarketPrice> resultFuture) { // Log.traceCall(currencyCode); ListenableFuture<MarketPrice> future = executorService.submit(() -> { Thread.currentThread().setName("requestPrice-" + provider.toString()); return provider.getPrice(currencyCode); }); Futures.addCallback(future, new FutureCallback<MarketPrice>() { public void onSuccess(MarketPrice marketPrice) { log.debug("Received marketPrice of {}\nfor currencyCode {}\nfrom provider {}", marketPrice, currencyCode, provider); resultFuture.set(marketPrice); } public void onFailure(@NotNull Throwable throwable) { resultFuture.setException(throwable); } }); return resultFuture; } }
agpl-3.0
splicemachine/spliceengine
db-testing/src/test/java/com/splicemachine/dbTesting/functionTests/tests/store/LongColumnTest.java
30475
/* * 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 - 2020 Splice Machine, Inc., * and are licensed to you under the GNU Affero General Public License. */ package com.splicemachine.dbTesting.functionTests.tests.store; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import junit.framework.Test; import junit.framework.TestSuite; import com.splicemachine.dbTesting.junit.BaseJDBCTestCase; import com.splicemachine.dbTesting.junit.JDBC; import com.splicemachine.dbTesting.junit.TestConfiguration; public class LongColumnTest extends BaseJDBCTestCase { public LongColumnTest(String name) { super(name); } public static Test suite() { TestSuite suite = new TestSuite("LongColumnTest"); suite.addTest(TestConfiguration.defaultSuite(LongColumnTest.class)); return suite; } protected void setUp() { try { Statement s = createStatement(); s.execute("CREATE FUNCTION PADSTRING (DATA VARCHAR(32000), " + "LENGTH INTEGER) RETURNS VARCHAR(32000) EXTERNAL NAME " + "'com.splicemachine.dbTesting.functionTests.util.Formatters" + ".padString' LANGUAGE JAVA PARAMETER STYLE JAVA"); s.execute("CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY" + "('db.storage.pageSize', '4096')"); s.execute("CALL SYSCS_UTIL.SYSCS_SET_DATABASE_PROPERTY" + "('db.storage.pageCacheSize', '40')"); s.close(); } catch (SQLException se) { se.printStackTrace(); } try { dropTable("testing"); } catch (SQLException e) { //ignore } } public void tearDown() throws Exception { Statement st = createStatement(); st.executeUpdate("DROP FUNCTION PADSTRING"); st.close(); dropTable("testing"); super.tearDown(); } /** * test 1: one long column */ public void testOneLongColumn() throws SQLException { Statement st = createStatement(); st.execute("create table testing (a varchar(8096))"); st.execute("insert into testing values (PADSTRING('1 2 3 4 5 6 7 8 9 0', 8096))"); st.execute("insert into testing values (PADSTRING('a b c d e f g h i j', 8096))"); st.execute("insert into testing values (PADSTRING('11 22 33 44 55 66 77', 8096))"); st.execute("insert into testing values (PADSTRING('aa bb cc dd ee ff gg', 8096))"); ResultSet rs = st.executeQuery("select a from testing"); JDBC.assertFullResultSet(rs, new String[][]{ {"1 2 3 4 5 6 7 8 9 0"}, {"a b c d e f g h i j"}, {"11 22 33 44 55 66 77"}, {"aa bb cc dd ee ff gg"} }); st.close(); } /** * test 2: testing two column (1 short, 1 long) table */ public void testTwoColumnsShortAndLong() throws SQLException { Statement st = createStatement(); st.execute("create table testing (a int, b varchar(32384))"); st.execute("insert into testing values (1, PADSTRING('1 2 3 4 5 6 7 8 9 0', 32384))"); st.execute("insert into testing values (2, PADSTRING('a b c d e f g h i j', 32384))"); st.execute("insert into testing values (3, PADSTRING('11 22 33 44 55 66 77', 32384))"); st.execute("insert into testing values (4, PADSTRING('aa bb cc dd ee ff gg', 32384))"); ResultSet rs = st.executeQuery("select * from testing"); JDBC.assertFullResultSet(rs, new String[][]{ {"1", "1 2 3 4 5 6 7 8 9 0"}, {"2", "a b c d e f g h i j"}, {"3", "11 22 33 44 55 66 77"}, {"4", "aa bb cc dd ee ff gg"} }); rs = st.executeQuery("select a from testing"); JDBC.assertFullResultSet(rs, new String[][]{ {"1"}, {"2"}, {"3"}, {"4"} }); rs = st.executeQuery("select b from testing"); JDBC.assertFullResultSet(rs, new String[][]{ {"1 2 3 4 5 6 7 8 9 0"}, {"a b c d e f g h i j"}, {"11 22 33 44 55 66 77"}, {"aa bb cc dd ee ff gg"} }); rs = st.executeQuery("select b from testing where a = 1"); JDBC.assertFullResultSet(rs, new String[][]{ {"1 2 3 4 5 6 7 8 9 0"}, }); st.close(); } /** * test 3: testing two column (1 long, 1 shor) table */ public void testTwoColumnsLongAndShort() throws SQLException { Statement st = createStatement(); st.execute("create table testing (a varchar(32384), b int)"); st.execute("insert into testing values (PADSTRING('1 2 3 4 5 6 7 8 9 0', 32384), 1)"); st.execute("insert into testing values (PADSTRING('a b c d e f g h i j', 32384), 2)"); st.execute("insert into testing values (PADSTRING('11 22 33 44 55 66 77', 32384), 3)"); st.execute("insert into testing values (PADSTRING('aa bb cc dd ee ff gg', 32384), 4)"); ResultSet rs = st.executeQuery("select * from testing"); JDBC.assertFullResultSet(rs, new String[][]{ {"1 2 3 4 5 6 7 8 9 0", "1"}, {"a b c d e f g h i j", "2"}, {"11 22 33 44 55 66 77", "3"}, {"aa bb cc dd ee ff gg", "4"} }); rs = st.executeQuery("select a from testing"); JDBC.assertFullResultSet(rs, new String[][]{ {"1 2 3 4 5 6 7 8 9 0"}, {"a b c d e f g h i j"}, {"11 22 33 44 55 66 77"}, {"aa bb cc dd ee ff gg"} }); rs = st.executeQuery("select b from testing"); JDBC.assertFullResultSet(rs, new String[][]{ {"1"}, {"2"}, {"3"}, {"4"} }); rs = st.executeQuery("select a from testing where b = 4"); JDBC.assertFullResultSet(rs, new String[][]{ {"aa bb cc dd ee ff gg"} }); st.close(); } /** * test 4: testing three column (1 short, 1 long, 1 short) table */ public void testThreeColumnsShortAndLongAndShort() throws SQLException { Statement st = createStatement(); st.execute("create table testing (z int, a varchar(32384), b int)"); st.execute("insert into testing values (0, PADSTRING('1 2 3 4 5 6 7 8 9 0',32384), 1)"); st.execute("insert into testing values (1, PADSTRING('a b c d e f g h i j',32384), 2)"); st.execute("insert into testing values (2, PADSTRING('11 22 33 44 55 66 77',32384), 3)"); st.execute("insert into testing values (4, PADSTRING('aa bb cc dd ee ff gg',32384), 4)"); ResultSet rs = st.executeQuery("select * from testing"); JDBC.assertFullResultSet(rs, new String[][]{ {"0", "1 2 3 4 5 6 7 8 9 0", "1"}, {"1", "a b c d e f g h i j", "2"}, {"2", "11 22 33 44 55 66 77", "3"}, {"4", "aa bb cc dd ee ff gg", "4"} }); rs = st.executeQuery("select a from testing"); JDBC.assertFullResultSet(rs, new String[][]{ {"1 2 3 4 5 6 7 8 9 0"}, {"a b c d e f g h i j"}, {"11 22 33 44 55 66 77"}, {"aa bb cc dd ee ff gg"} }); rs = st.executeQuery("select b from testing"); JDBC.assertFullResultSet(rs, new String[][]{ {"1"}, {"2"}, {"3"}, {"4"}, }); rs = st.executeQuery("select z from testing"); JDBC.assertFullResultSet(rs, new String[][]{ {"0"}, {"1"}, {"2"}, {"4"}, }); rs = st.executeQuery("select b from testing where z = b"); JDBC.assertFullResultSet(rs, new String[][]{ {"4"} }); try { st.executeUpdate("create index zz on testing (a)"); fail("try creating btree index on long column, should fail"); } catch (SQLException e) { assertSQLState("XSCB6", e); } st.execute("update testing set a = PADSTRING('update once', 32384)"); st.execute("update testing set a = PADSTRING('update twice', 32384)"); st.execute("update testing set a = PADSTRING('update three times', 32384)"); st.execute("update testing set a = PADSTRING('update four times', 32384)"); st.execute("update testing set a = PADSTRING('update five times', 32384)"); rs = st.executeQuery("select a from testing"); JDBC.assertFullResultSet(rs, new String[][]{ {"update five times"}, {"update five times"}, {"update five times"}, {"update five times"} }); st.close(); } /** * test 5: testing three columns (1 long, 1 short, 1 long) table */ public void testThreeColumnsLongAndShortAndLong() throws SQLException { Statement st = createStatement(); st.execute("create table testing (a varchar(32384), b int, c varchar(32084))"); st.execute("insert into testing values (PADSTRING('1 2 3 4 5 6 7 8 9 0',32384)," + " 1, PADSTRING('1 2 3 4 5 6 7 8 9 0',32084))"); st.execute("insert into testing values (PADSTRING('a b c d e f g h i j',32384)," + " 2, PADSTRING('a b c d e f g h i j',32084))"); st.execute("insert into testing values (PADSTRING('11 22 33 44 55 66 77',32384)," + " 3, PADSTRING('11 22 33 44 55 66 77',32084))"); st.execute("insert into testing values (PADSTRING('aa bb cc dd ee ff gg',32384)," + " 4, PADSTRING('aa bb cc dd ee ff gg',32084))"); ResultSet rs = st.executeQuery("select * from testing"); JDBC.assertFullResultSet(rs, new String[][]{ {"1 2 3 4 5 6 7 8 9 0", "1", "1 2 3 4 5 6 7 8 9 0"}, {"a b c d e f g h i j", "2", "a b c d e f g h i j"}, {"11 22 33 44 55 66 77", "3", "11 22 33 44 55 66 77"}, {"aa bb cc dd ee ff gg", "4", "aa bb cc dd ee ff gg"} }); rs = st.executeQuery("select a from testing"); JDBC.assertFullResultSet(rs, new String[][]{ {"1 2 3 4 5 6 7 8 9 0",}, {"a b c d e f g h i j",}, {"11 22 33 44 55 66 77",}, {"aa bb cc dd ee ff gg",} }); rs = st.executeQuery("select b from testing"); JDBC.assertFullResultSet(rs, new String[][]{ {"1"}, {"2"}, {"3"}, {"4"}, }); rs = st.executeQuery("select c from testing"); JDBC.assertFullResultSet(rs, new String[][]{ {"1 2 3 4 5 6 7 8 9 0"}, {"a b c d e f g h i j"}, {"11 22 33 44 55 66 77"}, {"aa bb cc dd ee ff gg"} }); rs = st.executeQuery("select * from testing where b = 4"); JDBC.assertFullResultSet(rs, new String[][]{ {"aa bb cc dd ee ff gg", "4", "aa bb cc dd ee ff gg"} }); try { st.executeUpdate("create index zz on testing (a)"); fail("try creating btree index, should fail on long columns"); } catch (SQLException e) { assertSQLState("XSCB6", e); } try { st.executeUpdate("create index zz on testing (c)"); fail("try creating btree index, should fail on long columns"); } catch (SQLException e) { assertSQLState("XSCB6", e); } st.executeUpdate("create index zz on testing (b)"); st.execute("update testing set c = PADSTRING('update 0', 32084)"); st.execute("update testing set c = PADSTRING('update 1', 32084)"); st.execute("update testing set c = PADSTRING('update 2', 32084)"); st.execute("update testing set c = PADSTRING('update 3', 32084)"); st.execute("update testing set c = PADSTRING('update 4', 32084)"); st.execute("update testing set c = PADSTRING('update 5', 32084)"); st.execute("update testing set c = PADSTRING('update 6', 32084)"); st.execute("update testing set c = PADSTRING('update 7', 32084)"); st.execute("update testing set c = PADSTRING('update 8', 32084)"); st.execute("update testing set c = PADSTRING('update 9', 32084)"); rs = st.executeQuery("select * from testing"); JDBC.assertFullResultSet(rs, new String[][]{ {"1 2 3 4 5 6 7 8 9 0", "1", "update 9"}, {"a b c d e f g h i j", "2", "update 9"}, {"11 22 33 44 55 66 77", "3", "update 9"}, {"aa bb cc dd ee ff gg", "4", "update 9"} }); st.close(); } /** * test 6: table with 5 columns (1 short, 1 long, 1 short, 1 long, 1 short) table */ public void testFiveColumnsSLSLS() throws SQLException { Statement st = createStatement(); st.execute("create table testing (a int, b clob(64768), c int, d varchar(32384), e int)"); st.execute("insert into testing values (0, PADSTRING('1 2 3 4 5 6 7 8 9 0', 64768)," + " 1, PADSTRING('1 2 3 4 5 6 7 8 9 0', 32384), 2)"); st.execute("insert into testing values (1, PADSTRING('a b c d e f g h i j', 64768)," + " 2, PADSTRING('a b c d e f g h i j', 32384), 3)"); st.execute("insert into testing values (2, PADSTRING('11 22 33 44 55 66 77', 64768)," + " 3, PADSTRING('11 22 33 44 55 66 77', 32384), 4)"); st.execute("insert into testing values (3, PADSTRING('aa bb cc dd ee ff gg', 64768)," + " 4, PADSTRING('aa bb cc dd ee ff gg',32384), 5)"); st.execute("insert into testing values (4, PADSTRING('1 2 3 4 5 6 7 8 9 0', 64768)," + " 5, PADSTRING('aa bb cc dd ee ff gg',32384), 6)"); st.execute("insert into testing values (5, PADSTRING('a b c d e f g h i j', 64768)," + " 6, PADSTRING('aa bb cc dd ee ff gg',32384), 7)"); st.execute("insert into testing values (6, PADSTRING('11 22 33 44 55 66 77', 64768)," + " 7, PADSTRING('aa bb cc dd ee ff gg',32384), 8)"); st.execute("insert into testing values (7, PADSTRING('aa bb cc dd ee ff gg', 64768)," + " 8, PADSTRING('aa bb cc dd ee ff gg',32384), 9)"); ResultSet rs = st.executeQuery("select * from testing"); JDBC.assertFullResultSet(rs, new String[][]{ {"0", "1 2 3 4 5 6 7 8 9 0", "1", "1 2 3 4 5 6 7 8 9 0", "2"}, {"1", "a b c d e f g h i j", "2", "a b c d e f g h i j", "3"}, {"2", "11 22 33 44 55 66 77", "3", "11 22 33 44 55 66 77", "4"}, {"3", "aa bb cc dd ee ff gg", "4", "aa bb cc dd ee ff gg", "5"}, {"4", "1 2 3 4 5 6 7 8 9 0", "5", "aa bb cc dd ee ff gg", "6"}, {"5", "a b c d e f g h i j", "6", "aa bb cc dd ee ff gg", "7"}, {"6", "11 22 33 44 55 66 77", "7", "aa bb cc dd ee ff gg", "8"}, {"7", "aa bb cc dd ee ff gg", "8", "aa bb cc dd ee ff gg", "9"} }); rs = st.executeQuery("select a from testing"); JDBC.assertFullResultSet(rs, new String[][]{ {"0"}, {"1"}, {"2"}, {"3"}, {"4"}, {"5"}, {"6"}, {"7"}, }); rs = st.executeQuery("select b from testing"); JDBC.assertFullResultSet(rs, new String[][]{ {"1 2 3 4 5 6 7 8 9 0"}, {"a b c d e f g h i j"}, {"11 22 33 44 55 66 77"}, {"aa bb cc dd ee ff gg"}, {"1 2 3 4 5 6 7 8 9 0"}, {"a b c d e f g h i j"}, {"11 22 33 44 55 66 77"}, {"aa bb cc dd ee ff gg"} }); rs = st.executeQuery("select a, c, d from testing"); JDBC.assertFullResultSet(rs, new String[][]{ {"0", "1", "1 2 3 4 5 6 7 8 9 0"}, {"1", "2", "a b c d e f g h i j"}, {"2", "3", "11 22 33 44 55 66 77"}, {"3", "4", "aa bb cc dd ee ff gg"}, {"4", "5", "aa bb cc dd ee ff gg"}, {"5", "6", "aa bb cc dd ee ff gg"}, {"6", "7", "aa bb cc dd ee ff gg"}, {"7", "8", "aa bb cc dd ee ff gg"} }); st.execute("update testing set b = PADSTRING('update 0', 64768)"); st.execute("update testing set b = PADSTRING('update 1', 64768)"); st.execute("update testing set b = PADSTRING('update 2', 64768)"); st.execute("update testing set b = PADSTRING('update 3', 64768)"); st.execute("update testing set b = PADSTRING('update 4', 64768)"); st.execute("update testing set b = PADSTRING('update 5', 64768)"); st.execute("update testing set b = PADSTRING('update 6', 64768)"); st.execute("update testing set b = PADSTRING('update 7', 64768)"); st.execute("update testing set b = PADSTRING('update 8', 64768)"); st.execute("update testing set b = PADSTRING('update 9', 64768)"); rs = st.executeQuery("select b from testing"); JDBC.assertFullResultSet(rs, new String[][]{ {"update 9"}, {"update 9"}, {"update 9"}, {"update 9"}, {"update 9"}, {"update 9"}, {"update 9"}, {"update 9"}, }); rs = st.executeQuery("select a, b, e from testing"); JDBC.assertFullResultSet(rs, new String[][]{ {"0", "update 9", "2"}, {"1", "update 9", "3"}, {"2", "update 9", "4"}, {"3", "update 9", "5"}, {"4", "update 9", "6"}, {"5", "update 9", "7"}, {"6", "update 9", "8"}, {"7", "update 9", "9"} }); st.close(); } /** * test 7: table with 5 columns, all long columns */ public void testFiveColumnsAllLong() throws SQLException { Statement st = createStatement(); st.execute("create table testing" + " (a clob(64768), b varchar(32384), c clob(64768), d varchar(32384), e clob(64768))"); for (int i = 0; i < 10; i++) { st.execute("insert into testing values (PADSTRING('a a a a a a a a a a',64768)," + " PADSTRING('b b b b b b b b b b',32384), PADSTRING('c c c c c c c c c c',64768)," + " PADSTRING('d d d d d d d d d d', 32384), PADSTRING('e e e e e e e e',64768))"); } ResultSet rs = st.executeQuery("select * from testing"); JDBC.assertFullResultSet(rs, new String[][]{ {"a a a a a a a a a a", "b b b b b b b b b b", "c c c c c c c c c c", "d d d d d d d d d d", "e e e e e e e e"}, {"a a a a a a a a a a", "b b b b b b b b b b", "c c c c c c c c c c", "d d d d d d d d d d", "e e e e e e e e"}, {"a a a a a a a a a a", "b b b b b b b b b b", "c c c c c c c c c c", "d d d d d d d d d d", "e e e e e e e e"}, {"a a a a a a a a a a", "b b b b b b b b b b", "c c c c c c c c c c", "d d d d d d d d d d", "e e e e e e e e"}, {"a a a a a a a a a a", "b b b b b b b b b b", "c c c c c c c c c c", "d d d d d d d d d d", "e e e e e e e e"}, {"a a a a a a a a a a", "b b b b b b b b b b", "c c c c c c c c c c", "d d d d d d d d d d", "e e e e e e e e"}, {"a a a a a a a a a a", "b b b b b b b b b b", "c c c c c c c c c c", "d d d d d d d d d d", "e e e e e e e e"}, {"a a a a a a a a a a", "b b b b b b b b b b", "c c c c c c c c c c", "d d d d d d d d d d", "e e e e e e e e"}, {"a a a a a a a a a a", "b b b b b b b b b b", "c c c c c c c c c c", "d d d d d d d d d d", "e e e e e e e e"}, {"a a a a a a a a a a", "b b b b b b b b b b", "c c c c c c c c c c", "d d d d d d d d d d", "e e e e e e e e"}, }); rs = st.executeQuery("select a from testing"); JDBC.assertFullResultSet(rs, new String[][]{ {"a a a a a a a a a a",}, {"a a a a a a a a a a",}, {"a a a a a a a a a a",}, {"a a a a a a a a a a",}, {"a a a a a a a a a a",}, {"a a a a a a a a a a",}, {"a a a a a a a a a a",}, {"a a a a a a a a a a",}, {"a a a a a a a a a a",}, {"a a a a a a a a a a",}, }); rs = st.executeQuery("select b from testing"); JDBC.assertFullResultSet(rs, new String[][]{ {"b b b b b b b b b b",}, {"b b b b b b b b b b",}, {"b b b b b b b b b b",}, {"b b b b b b b b b b",}, {"b b b b b b b b b b",}, {"b b b b b b b b b b",}, {"b b b b b b b b b b",}, {"b b b b b b b b b b",}, {"b b b b b b b b b b",}, {"b b b b b b b b b b",}, }); rs = st.executeQuery("select c from testing"); JDBC.assertFullResultSet(rs, new String[][]{ {"c c c c c c c c c c",}, {"c c c c c c c c c c",}, {"c c c c c c c c c c",}, {"c c c c c c c c c c",}, {"c c c c c c c c c c",}, {"c c c c c c c c c c",}, {"c c c c c c c c c c",}, {"c c c c c c c c c c",}, {"c c c c c c c c c c",}, {"c c c c c c c c c c",}, }); rs = st.executeQuery("select d from testing"); JDBC.assertFullResultSet(rs, new String[][]{ {"d d d d d d d d d d",}, {"d d d d d d d d d d",}, {"d d d d d d d d d d",}, {"d d d d d d d d d d",}, {"d d d d d d d d d d",}, {"d d d d d d d d d d",}, {"d d d d d d d d d d",}, {"d d d d d d d d d d",}, {"d d d d d d d d d d",}, {"d d d d d d d d d d",}, }); rs = st.executeQuery("select e from testing"); JDBC.assertFullResultSet(rs, new String[][]{ {"e e e e e e e e",}, {"e e e e e e e e",}, {"e e e e e e e e",}, {"e e e e e e e e",}, {"e e e e e e e e",}, {"e e e e e e e e",}, {"e e e e e e e e",}, {"e e e e e e e e",}, {"e e e e e e e e",}, {"e e e e e e e e",}, }); rs = st.executeQuery("select a, c, e from testing"); JDBC.assertFullResultSet(rs, new String[][]{ {"a a a a a a a a a a", "c c c c c c c c c c", "e e e e e e e e"}, {"a a a a a a a a a a", "c c c c c c c c c c", "e e e e e e e e"}, {"a a a a a a a a a a", "c c c c c c c c c c", "e e e e e e e e"}, {"a a a a a a a a a a", "c c c c c c c c c c", "e e e e e e e e"}, {"a a a a a a a a a a", "c c c c c c c c c c", "e e e e e e e e"}, {"a a a a a a a a a a", "c c c c c c c c c c", "e e e e e e e e"}, {"a a a a a a a a a a", "c c c c c c c c c c", "e e e e e e e e"}, {"a a a a a a a a a a", "c c c c c c c c c c", "e e e e e e e e"}, {"a a a a a a a a a a", "c c c c c c c c c c", "e e e e e e e e"}, {"a a a a a a a a a a", "c c c c c c c c c c", "e e e e e e e e"}, }); rs = st.executeQuery("select b, e from testing"); JDBC.assertFullResultSet(rs, new String[][]{ {"b b b b b b b b b b", "e e e e e e e e"}, {"b b b b b b b b b b", "e e e e e e e e"}, {"b b b b b b b b b b", "e e e e e e e e"}, {"b b b b b b b b b b", "e e e e e e e e"}, {"b b b b b b b b b b", "e e e e e e e e"}, {"b b b b b b b b b b", "e e e e e e e e"}, {"b b b b b b b b b b", "e e e e e e e e"}, {"b b b b b b b b b b", "e e e e e e e e"}, {"b b b b b b b b b b", "e e e e e e e e"}, {"b b b b b b b b b b", "e e e e e e e e"}, }); st.execute("update testing set a = PADSTRING('1 1 1 1 1 1 1 1 1 1', 64768)"); st.execute("update testing set e = PADSTRING('9 9 9 9 9 9 9 9 9 9',64768)"); rs = st.executeQuery("select a, e from testing"); JDBC.assertFullResultSet(rs, new String[][]{ {"1 1 1 1 1 1 1 1 1 1", "9 9 9 9 9 9 9 9 9 9"}, {"1 1 1 1 1 1 1 1 1 1", "9 9 9 9 9 9 9 9 9 9"}, {"1 1 1 1 1 1 1 1 1 1", "9 9 9 9 9 9 9 9 9 9"}, {"1 1 1 1 1 1 1 1 1 1", "9 9 9 9 9 9 9 9 9 9"}, {"1 1 1 1 1 1 1 1 1 1", "9 9 9 9 9 9 9 9 9 9"}, {"1 1 1 1 1 1 1 1 1 1", "9 9 9 9 9 9 9 9 9 9"}, {"1 1 1 1 1 1 1 1 1 1", "9 9 9 9 9 9 9 9 9 9"}, {"1 1 1 1 1 1 1 1 1 1", "9 9 9 9 9 9 9 9 9 9"}, {"1 1 1 1 1 1 1 1 1 1", "9 9 9 9 9 9 9 9 9 9"}, {"1 1 1 1 1 1 1 1 1 1", "9 9 9 9 9 9 9 9 9 9"}, }); rs = st.executeQuery("select a, c, b, e from testing"); JDBC.assertFullResultSet(rs, new String[][]{ {"1 1 1 1 1 1 1 1 1 1", "c c c c c c c c c c", "b b b b b b b b b b", "9 9 9 9 9 9 9 9 9 9"}, {"1 1 1 1 1 1 1 1 1 1", "c c c c c c c c c c", "b b b b b b b b b b", "9 9 9 9 9 9 9 9 9 9"}, {"1 1 1 1 1 1 1 1 1 1", "c c c c c c c c c c", "b b b b b b b b b b", "9 9 9 9 9 9 9 9 9 9"}, {"1 1 1 1 1 1 1 1 1 1", "c c c c c c c c c c", "b b b b b b b b b b", "9 9 9 9 9 9 9 9 9 9"}, {"1 1 1 1 1 1 1 1 1 1", "c c c c c c c c c c", "b b b b b b b b b b", "9 9 9 9 9 9 9 9 9 9"}, {"1 1 1 1 1 1 1 1 1 1", "c c c c c c c c c c", "b b b b b b b b b b", "9 9 9 9 9 9 9 9 9 9"}, {"1 1 1 1 1 1 1 1 1 1", "c c c c c c c c c c", "b b b b b b b b b b", "9 9 9 9 9 9 9 9 9 9"}, {"1 1 1 1 1 1 1 1 1 1", "c c c c c c c c c c", "b b b b b b b b b b", "9 9 9 9 9 9 9 9 9 9"}, {"1 1 1 1 1 1 1 1 1 1", "c c c c c c c c c c", "b b b b b b b b b b", "9 9 9 9 9 9 9 9 9 9"}, {"1 1 1 1 1 1 1 1 1 1", "c c c c c c c c c c", "b b b b b b b b b b", "9 9 9 9 9 9 9 9 9 9"}, }); rs = st.executeQuery("select e from testing"); JDBC.assertFullResultSet(rs, new String[][]{ {"9 9 9 9 9 9 9 9 9 9"}, {"9 9 9 9 9 9 9 9 9 9"}, {"9 9 9 9 9 9 9 9 9 9"}, {"9 9 9 9 9 9 9 9 9 9"}, {"9 9 9 9 9 9 9 9 9 9"}, {"9 9 9 9 9 9 9 9 9 9"}, {"9 9 9 9 9 9 9 9 9 9"}, {"9 9 9 9 9 9 9 9 9 9"}, {"9 9 9 9 9 9 9 9 9 9"}, {"9 9 9 9 9 9 9 9 9 9"}, }); st.close(); } }
agpl-3.0
splicemachine/spliceengine
hbase_sql/src/test/java/com/splicemachine/hbase/SnapshotIT.java
7058
/* * 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 - 2020 Splice Machine, Inc., * and are licensed to you under the GNU Affero General Public License. */ package com.splicemachine.hbase; import com.splicemachine.access.api.PartitionAdmin; import com.splicemachine.derby.test.framework.SpliceSchemaWatcher; import com.splicemachine.derby.test.framework.SpliceUnitTest; import com.splicemachine.derby.test.framework.SpliceWatcher; import com.splicemachine.derby.test.framework.TestConnection; import com.splicemachine.si.impl.driver.SIDriver; import com.splicemachine.test_tools.TableCreator; import org.junit.*; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import static com.splicemachine.test_tools.Rows.row; import static com.splicemachine.test_tools.Rows.rows; /** * Created by jyuan on 6/6/17. */ public class SnapshotIT extends SpliceUnitTest { private static final String SCHEMA = SnapshotIT.class.getSimpleName().toUpperCase(); private static final SpliceWatcher classWatcher = new SpliceWatcher(SCHEMA); @ClassRule public static SpliceSchemaWatcher spliceSchemaWatcher = new SpliceSchemaWatcher(SCHEMA); @Rule public SpliceWatcher methodWatcher = new SpliceWatcher(SCHEMA); @BeforeClass public static void createTables() throws Exception { TestConnection conn = classWatcher.getOrCreateConnection(); new TableCreator(conn) .withCreate("create table T (i int)") .withInsert("insert into T values(?)") .withRows(rows( row(1), row(2), row(3), row(4))) .withIndex("create index ti on t(i)") .create(); new TableCreator(conn) .withCreate("create table A (i int)") .withInsert("insert into A values(?)") .withRows(rows( row(1), row(2), row(3), row(4))) .withIndex("create index ai on a(i)") .create(); conn.execute("call syscs_util.snapshot_table('SNAPSHOTIT', 'T', 'EXIST')"); } @AfterClass public static void cleanup() throws Exception { try (TestConnection conn = classWatcher.getOrCreateConnection()) { conn.execute("call syscs_util.delete_snapshot('EXIST')"); try (PreparedStatement ps = conn.prepareStatement("select count(*) from sys.syssnapshots")) { try (ResultSet rs = ps.executeQuery()) { rs.next(); Assert.assertEquals(0, rs.getInt(1)); } } } } @Test public void testNonexistSnapshot() throws Exception { try { methodWatcher.execute("call syscs_util.restore_snapshot('nonexist')"); Assert.fail("Expected to fail"); } catch (SQLException e) { String sqlState = e.getSQLState(); Assert.assertEquals(sqlState, "SNA02"); } } @Test public void testExistSnapshot() throws Exception { try { methodWatcher.execute("call syscs_util.snapshot_schema('SNAPSHOTIT','EXIST')"); Assert.fail("Expected to fail"); } catch (SQLException e) { String sqlState = e.getSQLState(); Assert.assertEquals(sqlState, "SNA01"); } } @Test public void testSnapshotTable() throws Exception { methodWatcher.execute("call syscs_util.snapshot_table('SNAPSHOTIT', 'T', 'S1')"); ResultSet rs = methodWatcher.executeQuery("select count(*) from sys.syssnapshots where snapshotname='S1'"); rs.next(); Assert.assertEquals(2, rs.getInt(1)); methodWatcher.execute("insert into t select * from t"); rs = methodWatcher.executeQuery("select count(*) from t"); rs.next(); Assert.assertEquals(8, rs.getInt(1)); methodWatcher.execute("call syscs_util.restore_snapshot('S1')"); rs = methodWatcher.executeQuery("select count(*) from t"); rs.next(); Assert.assertEquals(4, rs.getInt(1)); methodWatcher.execute("call syscs_util.delete_snapshot('S1')"); rs = methodWatcher.executeQuery("select count(*) from sys.syssnapshots where snapshotname='S1'"); rs.next(); Assert.assertEquals(0, rs.getInt(1)); } @Test public void testSnapshotSchema() throws Exception { methodWatcher.execute("call syscs_util.snapshot_schema('SNAPSHOTIT', 'S2')"); ResultSet rs = methodWatcher.executeQuery("select count(*) from sys.syssnapshots where snapshotname='S2'"); rs.next(); Assert.assertEquals(4, rs.getInt(1)); methodWatcher.execute("insert into t select * from t"); rs = methodWatcher.executeQuery("select count(*) from t"); rs.next(); Assert.assertEquals(8, rs.getInt(1)); methodWatcher.execute("call syscs_util.restore_snapshot('S2')"); rs = methodWatcher.executeQuery("select count(*) from t"); rs.next(); Assert.assertEquals(4, rs.getInt(1)); methodWatcher.execute("call syscs_util.delete_snapshot('S2')"); rs = methodWatcher.executeQuery("select count(*) from sys.syssnapshots where snapshotname='S2'"); rs.next(); Assert.assertEquals(0, rs.getInt(1)); } }
agpl-3.0
opensourceBIM/BIMserver
PluginBase/generated/org/bimserver/models/ifc4/IfcFlowTerminal.java
1772
/** * 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.ifc4; /****************************************************************************** * 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 IfcFlowTerminal extends IfcDistributionFlowElement { } // IfcFlowTerminal
agpl-3.0
acontes/scheduling
src/scheduler/src/org/ow2/proactive/scheduler/job/InternalJob.java
62789
/* * ################################################################ * * ProActive Parallel Suite(TM): The Java(TM) library for * Parallel, Distributed, Multi-Core Computing for * Enterprise Grids & Clouds * * Copyright (C) 1997-2011 INRIA/University of * Nice-Sophia Antipolis/ActiveEon * Contact: proactive@ow2.org or contact@activeeon.com * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Affero General Public License * as published by the Free Software Foundation; version 3 of * the License. * * 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 * Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA * * If needed, contact us to obtain a release under GPL Version 2 or 3 * or a different license than the AGPL. * * Initial developer(s): The ProActive Team * http://proactive.inria.fr/team_members.htm * Contributor(s): ActiveEon Team - http://www.activeeon.com * * ################################################################ * $$ACTIVEEON_CONTRIBUTOR$$ */ package org.ow2.proactive.scheduler.job; import java.io.IOException; import java.io.ObjectInputStream; import java.io.ObjectOutputStream; import java.lang.reflect.Field; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.TreeMap; import javax.xml.bind.annotation.XmlTransient; import org.apache.log4j.Logger; import org.objectweb.proactive.extensions.dataspaces.core.naming.NamingService; import org.ow2.proactive.authentication.crypto.Credentials; import org.ow2.proactive.db.annotation.Alterable; import org.ow2.proactive.scheduler.common.NotificationData; import org.ow2.proactive.scheduler.common.SchedulerEvent; import org.ow2.proactive.scheduler.common.exception.ExecutableCreationException; import org.ow2.proactive.scheduler.common.exception.UnknownTaskException; import org.ow2.proactive.scheduler.common.job.JobId; import org.ow2.proactive.scheduler.common.job.JobInfo; import org.ow2.proactive.scheduler.common.job.JobPriority; import org.ow2.proactive.scheduler.common.job.JobState; import org.ow2.proactive.scheduler.common.job.JobStatus; import org.ow2.proactive.scheduler.common.task.TaskId; import org.ow2.proactive.scheduler.common.task.TaskInfo; import org.ow2.proactive.scheduler.common.task.TaskState; import org.ow2.proactive.scheduler.common.task.TaskStatus; import org.ow2.proactive.scheduler.common.task.flow.FlowAction; import org.ow2.proactive.scheduler.common.task.flow.FlowActionType; import org.ow2.proactive.scheduler.common.task.flow.FlowBlock; import org.ow2.proactive.scheduler.core.SchedulerFrontend; import org.ow2.proactive.scheduler.core.annotation.TransientInSerialization; import org.ow2.proactive.scheduler.core.properties.PASchedulerProperties; import org.ow2.proactive.scheduler.descriptor.JobDescriptor; import org.ow2.proactive.scheduler.descriptor.JobDescriptorImpl; import org.ow2.proactive.scheduler.descriptor.TaskDescriptor; import org.ow2.proactive.scheduler.job.JobInfoImpl.ReplicatedTask; import org.ow2.proactive.scheduler.task.ClientTaskState; import org.ow2.proactive.scheduler.task.TaskIdImpl; import org.ow2.proactive.scheduler.task.TaskResultImpl; import org.ow2.proactive.scheduler.task.internal.InternalTask; /** * Internal and global description of a job. * This class contains all informations about the job to launch. * It also provides method to manage the content regarding the scheduling process.<br/> * Specific internal job may extend this abstract class. * * @author The ProActive Team * @since ProActive Scheduling 0.9 */ public abstract class InternalJob extends JobState { public static final Logger logger = Logger.getLogger(InternalJob.class); /** Owner of the job */ private String owner = ""; /** List of every tasks in this job. */ protected Map<TaskId, InternalTask> tasks = new HashMap<TaskId, InternalTask>(); /** Informations (that can be modified) about job execution */ @Alterable protected JobInfoImpl jobInfo = new JobInfoImpl(); /** Job descriptor for dependences management */ @TransientInSerialization @XmlTransient private JobDescriptor jobDescriptor; /** DataSpace application manager for this job */ //Not DB managed, created once needed. @TransientInSerialization @XmlTransient private JobDataSpaceApplication jobDataSpaceApplication; /** Initial waiting time for a task before restarting in millisecond */ @TransientInSerialization private long restartWaitingTimer = PASchedulerProperties.REEXECUTION_INITIAL_WAITING_TIME.getValueAsInt(); /** used credentials to fork as user id. Can be null, or contain user/pwd[/key] */ @XmlTransient @TransientInSerialization private Credentials credentials = null; /** Hibernate default constructor */ public InternalJob() { } /** * Create a new Job with the given parameters. It provides methods to add or * remove tasks. * * @param name the current job name. * @param priority the priority of this job between 1 and 5. * @param cancelJobOnError true if the job has to run until its end or an user intervention. * @param description a short description of the job and what it will do. */ public InternalJob(String name, JobPriority priority, boolean cancelJobOnError, String description) { this.name = name; this.jobInfo.setPriority(priority); this.setCancelJobOnError(cancelJobOnError); this.description = description; } /** * This method will do two things :<br /> * First, it will update the job with the informations contained in the given taskInfo<br /> * Then, it will update the proper task using the same given taskInfo. * * @param info a taskInfo containing new information about the task. */ @Override public synchronized void update(TaskInfo info) { //ensure that is a JobInfoImpl //if not, we are in client side and client brings its own JobInfo Implementation if (!getId().equals(info.getJobId())) { throw new IllegalArgumentException( "This job info is not applicable for this job. (expected id is '" + getId() + "' but was '" + info.getJobId() + "'"); } jobInfo = (JobInfoImpl) info.getJobInfo(); try { tasks.get(info.getTaskId()).update(info); } catch (NullPointerException e) { throw new IllegalArgumentException("This task info is not applicable in this job. (task id '" + info.getTaskId() + "' not found)"); } } /** * To update the content of this job with a jobInfo. * * @param info the JobInfo to set */ @Override public synchronized void update(JobInfo info) { if (!getId().equals(info.getJobId())) { throw new IllegalArgumentException( "This job info is not applicable for this job. (expected id is '" + getId() + "' but was '" + info.getJobId() + "'"); } //update job info this.jobInfo = (JobInfoImpl) info; //update task status if needed if (this.jobInfo.getTaskStatusModify() != null) { for (TaskId id : tasks.keySet()) { tasks.get(id).setStatus(this.jobInfo.getTaskStatusModify().get(id)); } } //update task finished time if needed if (this.jobInfo.getTaskFinishedTimeModify() != null) { for (TaskId id : tasks.keySet()) { if (this.jobInfo.getTaskFinishedTimeModify().containsKey(id)) { //a null send to a long setter throws a NullPointerException so, here is the fix tasks.get(id).setFinishedTime(this.jobInfo.getTaskFinishedTimeModify().get(id)); } } } // update skipped tasks if (this.jobInfo.getTasksSkipped() != null) { for (TaskId id : tasks.keySet()) { if (this.jobInfo.getTasksSkipped().contains(id)) { InternalTask it = tasks.get(id); it.setStatus(TaskStatus.SKIPPED); } } } // replicated tasks have been added through FlowAction#REPLICATE if (this.jobInfo.getTasksReplicated() != null) { updateTasksReplicated(); } // replicated tasks have been added through FlowAction#LOOP if (this.jobInfo.getTasksLooped() != null) { updateTasksLooped(); } } /** * Updates this job when tasks were replicated due to a {@link FlowActionType#REPLICATE} action * <p> * The internal state of the job will change: new tasks will be added, * existing tasks will be modified. */ private void updateTasksReplicated() { // key: replicated task / value : id of the original task // originalId not used as key because tasks can be replicated multiple times Map<InternalTask, TaskId> newTasks = new TreeMap<InternalTask, TaskId>(); // create the new tasks for (ReplicatedTask it : this.jobInfo.getTasksReplicated()) { InternalTask original = this.tasks.get(it.originalId); InternalTask replicated = null; try { replicated = (InternalTask) original.replicate(); } catch (Exception e) { } replicated.setId(it.replicatedId); // for some reason the indices are embedded in the Readable name and not where they belong int dupId = InternalTask.getReplicationIndexFromName(it.replicatedId.getReadableName()); int itId = InternalTask.getIterationIndexFromName(it.replicatedId.getReadableName()); replicated.setReplicationIndex(dupId); replicated.setIterationIndex(itId); this.tasks.put(it.replicatedId, replicated); newTasks.put(replicated, it.originalId); } // recreate deps contained in the data struct for (ReplicatedTask it : this.jobInfo.getTasksReplicated()) { InternalTask newtask = this.tasks.get(it.replicatedId); for (TaskId depId : it.deps) { InternalTask dep = this.tasks.get(depId); newtask.addDependence(dep); } } // plug mergers List<InternalTask> toAdd = new ArrayList<InternalTask>(); for (InternalTask old : this.tasks.values()) { // task is not a replicated one, has dependencies if (!newTasks.containsValue(old.getId()) && old.hasDependences()) { for (InternalTask oldDep : old.getIDependences()) { // one of its dependencies is a replicated task if (newTasks.containsValue(oldDep.getId())) { // connect those replicated tasks to the merger for (Entry<InternalTask, TaskId> newTask : newTasks.entrySet()) { if (newTask.getValue().equals(oldDep.getId())) { toAdd.add(newTask.getKey()); } } } } // avoids concurrent modification for (InternalTask newDep : toAdd) { old.addDependence(newDep); } toAdd.clear(); } } } /** * Updates this job when tasks were replicated due to a {@link FlowActionType#LOOP} action * <p> * The internal state of the job will change: new tasks will be added, * existing tasks will be modified. */ private void updateTasksLooped() { Map<TaskId, InternalTask> newTasks = new TreeMap<TaskId, InternalTask>(); // create the new tasks for (ReplicatedTask it : this.jobInfo.getTasksLooped()) { InternalTask original = this.tasks.get(it.originalId); InternalTask replicated = null; try { replicated = (InternalTask) original.replicate(); } catch (Exception e) { } replicated.setId(it.replicatedId); // for some reason the indices are embedded in the Readable name and not where they belong int dupId = InternalTask.getReplicationIndexFromName(it.replicatedId.getReadableName()); int itId = InternalTask.getIterationIndexFromName(it.replicatedId.getReadableName()); replicated.setReplicationIndex(dupId); replicated.setIterationIndex(itId); this.tasks.put(it.replicatedId, replicated); newTasks.put(it.originalId, replicated); } InternalTask oldInit = null; // recreate deps contained in the data struct for (ReplicatedTask it : this.jobInfo.getTasksLooped()) { InternalTask newtask = this.tasks.get(it.replicatedId); for (TaskId depId : it.deps) { InternalTask dep = this.tasks.get(depId); if (!newTasks.containsValue(dep)) { oldInit = dep; } newtask.addDependence(dep); } } // find mergers InternalTask newInit = null; InternalTask merger = null; for (InternalTask old : this.tasks.values()) { // the merger is not a replicated task, nor has been replicated if (!newTasks.containsKey(old.getId()) && !newTasks.containsValue(old) && old.hasDependences()) { for (InternalTask oldDep : old.getIDependences()) { // merger's deps contains the initiator of the LOOP if (oldDep.equals(oldInit)) { merger = old; break; } } if (merger != null) { break; } } } // merger can be null if (merger != null) { // find new initiator Map<TaskId, InternalTask> newTasks2 = new HashMap<TaskId, InternalTask>(); for (InternalTask it : newTasks.values()) { newTasks2.put(it.getId(), it); } for (InternalTask it : newTasks.values()) { if (it.hasDependences()) { for (InternalTask dep : it.getIDependences()) { newTasks2.remove(dep.getId()); } } } for (InternalTask it : newTasks2.values()) { newInit = it; break; } merger.getIDependences().remove(oldInit); merger.addDependence(newInit); } } /** * @see org.ow2.proactive.scheduler.common.job.JobState#getJobInfo() */ @Override public JobInfo getJobInfo() { return jobInfo; } public void setJobInfo(JobInfoImpl jobInfo) { this.jobInfo = jobInfo; } /** * Append a task to this job. * * @param task the task to add. * @return true if the task has been correctly added to the job, false if * not. */ public boolean addTask(InternalTask task) { task.setJobId(getId()); int taskId = tasks.size(); task.setId(TaskIdImpl.createTaskId(getId(), task.getName(), taskId, true)); boolean result = (tasks.put(task.getId(), task) == null); if (result) { jobInfo.setTotalNumberOfTasks(jobInfo.getTotalNumberOfTasks() + 1); } return result; } /** * Start a new task will set some count and update dependencies if necessary. * * @param td the task which has just been started. */ public void startTask(InternalTask td) { setNumberOfPendingTasks(getNumberOfPendingTasks() - 1); setNumberOfRunningTasks(getNumberOfRunningTasks() + 1); if (getStatus() == JobStatus.STALLED) { setStatus(JobStatus.RUNNING); } getJobDescriptor().start(td.getId()); td.setStatus(TaskStatus.RUNNING); td.setStartTime(System.currentTimeMillis()); td.setFinishedTime(-1); td.setExecutionHostName(td.getExecuterInformations().getHostName() + " (" + td.getExecuterInformations().getNodeName() + ")"); } /** * Start dataspace configuration and application */ public void startDataSpaceApplication(NamingService namingService, String namingServiceURL) { if (jobDataSpaceApplication == null) { long appId = getJobInfo().getJobId().hashCode(); jobDataSpaceApplication = new JobDataSpaceApplication(appId, namingService, namingServiceURL); } jobDataSpaceApplication.startDataSpaceApplication(getInputSpace(), getOutputSpace(), getOwner(), getId()); } /** * Updates count for running to pending event. */ public void newWaitingTask() { setNumberOfPendingTasks(getNumberOfPendingTasks() + 1); setNumberOfRunningTasks(getNumberOfRunningTasks() - 1); if (getNumberOfRunningTasks() == 0 && getStatus() != JobStatus.PAUSED) { setStatus(JobStatus.STALLED); } } /** * Set this task in restart mode, it will set the task to pending status and change task count. * * @param task the task which has to be restarted. */ public void reStartTask(InternalTask task) { getJobDescriptor().reStart(task.getId()); task.setProgress(0); if (getStatus() == JobStatus.PAUSED) { task.setStatus(TaskStatus.PAUSED); HashMap<TaskId, TaskStatus> hts = new HashMap<TaskId, TaskStatus>(); hts.put(task.getId(), task.getStatus()); getJobDescriptor().update(hts); } else { task.setStatus(TaskStatus.PENDING); } } /** * Terminate a task, change status, managing dependences * * Also, apply a Control Flow Action if provided. * This may alter the number of tasks in the job, * events have to be sent accordingly. * * @param errorOccurred has an error occurred for this termination * @param taskId the task to terminate. * @param frontend Used to notify all listeners of the replication of tasks, triggered by the FlowAction * @param action a Control Flow Action that will potentially create new tasks inside the job * @return the taskDescriptor that has just been terminated. */ public InternalTask terminateTask(boolean errorOccurred, TaskId taskId, SchedulerFrontend frontend, FlowAction action, TaskResultImpl result) { final InternalTask descriptor = tasks.get(taskId); descriptor.setFinishedTime(System.currentTimeMillis()); descriptor.setStatus(errorOccurred ? TaskStatus.FAULTY : TaskStatus.FINISHED); descriptor.setExecutionDuration(result.getTaskDuration()); setNumberOfRunningTasks(getNumberOfRunningTasks() - 1); setNumberOfFinishedTasks(getNumberOfFinishedTasks() + 1); if ((getStatus() == JobStatus.RUNNING) && (getNumberOfRunningTasks() == 0)) { setStatus(JobStatus.STALLED); } boolean didAction = false; if (action != null) { InternalTask initiator = tasks.get(taskId); List<InternalTask> modifiedTasks = new ArrayList<InternalTask>(); switch (action.getType()) { /* * LOOP action * */ case LOOP: { { // find the target of the loop InternalTask target = null; if (action.getTarget().equals(initiator.getName())) { target = initiator; } else { target = findTaskUp(action.getTarget(), initiator); } TaskId targetId = target.getTaskInfo().getTaskId(); logger.info("Control Flow Action LOOP (init:" + initiator.getId() + ";target:" + target.getId() + ")"); // accumulates the tasks between the initiator and the target Map<TaskId, InternalTask> dup = new HashMap<TaskId, InternalTask>(); // replicate the tasks between the initiator and the target try { initiator.replicateTree(dup, targetId, true, initiator.getReplicationIndex(), initiator.getIterationIndex()); } catch (ExecutableCreationException e) { logger.error("", e); break; } ((JobInfoImpl) this.getJobInfo()).setNumberOfPendingTasks(this.getJobInfo() .getNumberOfPendingTasks() + dup.size()); // ensure naming unicity // time-consuming but safe for (InternalTask nt : dup.values()) { boolean ok; do { ok = true; for (InternalTask task : tasks.values()) { if (nt.getName().equals(task.getName())) { nt.setIterationIndex(nt.getIterationIndex() + 1); ok = false; } } } while (!ok); } // configure the new tasks InternalTask newTarget = null; InternalTask newInit = null; for (Entry<TaskId, InternalTask> it : dup.entrySet()) { InternalTask nt = it.getValue(); if (target.getId().equals(it.getKey())) { newTarget = nt; } if (initiator.getId().equals(it.getKey())) { newInit = nt; } nt.setJobInfo(getJobInfo()); this.addTask(nt); } modifiedTasks.addAll(dup.values()); // connect replicated tree newTarget.addDependence(initiator); modifiedTasks.add(newTarget); // connect mergers List<InternalTask> mergers = new ArrayList<InternalTask>(); for (InternalTask t : this.tasks.values()) { if (t.getIDependences() != null) { for (InternalTask p : t.getIDependences()) { if (p.getId().equals(initiator.getId())) { if (!t.equals(newTarget)) { mergers.add(t); } } } } } for (InternalTask t : mergers) { t.getIDependences().remove(initiator); t.addDependence(newInit); } modifiedTasks.addAll(mergers); // propagate the changes in the job descriptor getJobDescriptor().doLoop(taskId, dup, newTarget, newInit); this.jobInfo.setModifiedTasks(createClientTaskStates(modifiedTasks)); // notify frontend that tasks were added and modified frontend.jobStateUpdated(this.getOwner(), new NotificationData<JobInfo>( SchedulerEvent.TASK_REPLICATED, this.getJobInfo())); this.jobInfo.setModifiedTasks(null); didAction = true; break; } } /* * IF action * */ case IF: { // the targetIf from action.getTarget() is the selected branch; // the IF condition has already been evaluated prior to being put in a FlowAction // the targetElse from action.getTargetElse() is the branch that was NOT selected InternalTask targetIf = null; InternalTask targetElse = null; InternalTask targetJoin = null; // search for the targets as perfect matches of the unique name for (InternalTask it : tasks.values()) { // target is finished : probably looped if (it.getStatus().equals(TaskStatus.FINISHED) || it.getStatus().equals(TaskStatus.SKIPPED)) { continue; } if (action.getTarget().equals(it.getName())) { if (it.getIfBranch().equals(initiator)) { targetIf = it; } } else if (action.getTargetElse().equals(it.getName())) { if (it.getIfBranch().equals(initiator)) { targetElse = it; } } else if (action.getTargetContinuation().equals(it.getName())) { InternalTask up = findTaskUp(initiator.getName(), it); if (up != null && up.equals(initiator)) { targetJoin = it; } } } boolean searchIf = (targetIf == null); boolean searchElse = (targetElse == null); boolean searchJoin = (targetJoin == null); // search of a runnable perfect match for the targets failed; // the natural target was iterated, need to find the next iteration // which is the the one with the same dup index and base name, // but the highest iteration index for (InternalTask it : tasks.values()) { // does not share the same dup index : cannot be the same scope if (it.getReplicationIndex() != initiator.getReplicationIndex()) { continue; } if (it.getStatus().equals(TaskStatus.FINISHED) || it.getStatus().equals(TaskStatus.SKIPPED)) { continue; } String name = InternalTask.getInitialName(it.getName()); if (searchIf && InternalTask.getInitialName(action.getTarget()).equals(name)) { if (targetIf == null || targetIf.getIterationIndex() < it.getIterationIndex()) { targetIf = it; } } else if (searchElse && InternalTask.getInitialName(action.getTargetElse()).equals(name)) { if (targetElse == null || targetElse.getIterationIndex() < it.getIterationIndex()) { targetElse = it; } } else if (searchJoin && InternalTask.getInitialName(action.getTargetContinuation()).equals(name)) { if (targetJoin == null || targetJoin.getIterationIndex() < it.getIterationIndex()) { targetJoin = it; } } } logger.info("Control Flow Action IF: " + targetIf.getId() + " join: " + ((targetJoin == null) ? "null" : targetJoin.getId())); // these 2 tasks delimit the Task Block formed by the IF branch InternalTask branchStart = targetIf; InternalTask branchEnd = null; String match = targetIf.getMatchingBlock(); if (match != null) { for (InternalTask t : tasks.values()) { if (match.equals(t.getName()) && !(t.getStatus().equals(TaskStatus.FINISHED) || t.getStatus().equals( TaskStatus.SKIPPED))) { branchEnd = t; } } } // no matching block: there is no block, the branch is a single task if (branchEnd == null) { branchEnd = targetIf; } // plug the branch branchStart.addDependence(initiator); modifiedTasks.add(branchStart); if (targetJoin != null) { targetJoin.addDependence(branchEnd); modifiedTasks.add(targetJoin); } // the other branch will not be executed // first, find the concerned tasks List<InternalTask> elseTasks = new ArrayList<InternalTask>(); // elseTasks.add(targetElse); for (InternalTask t : this.tasks.values()) { if (t.dependsOn(targetElse)) { elseTasks.add(t); } } // even though the targetElse is not going to be executed, a // dependency on initiator still makes sense and would help // reconstruct the job graph on the client targetElse.addDependence(initiator); modifiedTasks.add(targetElse); List<TaskId> tev = new ArrayList<TaskId>(elseTasks.size()); for (InternalTask it : elseTasks) { it.setFinishedTime(descriptor.getFinishedTime() + 1); it.setStatus(TaskStatus.SKIPPED); it.setExecutionDuration(0); setNumberOfPendingTasks(getNumberOfPendingTasks() - 1); setNumberOfFinishedTasks(getNumberOfFinishedTasks() + 1); tev.add(it.getId()); logger.info("Task " + it.getId() + " will not be executed"); } // plug the branch in the descriptor TaskId joinId = null; if (targetJoin != null) { joinId = targetJoin.getId(); } getJobDescriptor().doIf(initiator.getId(), branchStart.getId(), branchEnd.getId(), joinId, targetElse.getId(), elseTasks); this.jobInfo.setTasksSkipped(tev); this.jobInfo.setModifiedTasks(createClientTaskStates(modifiedTasks)); // notify frontend that tasks were modified if (frontend != null) { frontend.jobStateUpdated(this.getOwner(), new NotificationData<JobInfo>( SchedulerEvent.TASK_SKIPPED, this.getJobInfo())); } this.jobInfo.setTasksSkipped(null); this.jobInfo.setModifiedTasks(null); // no jump is performed ; now that the tasks have been plugged // the flow can continue its normal operation getJobDescriptor().terminate(taskId); didAction = true; break; } /* * REPLICATE action * */ case REPLICATE: { int runs = action.getDupNumber(); if (runs < 1) { runs = 1; } logger.info("Control Flow Action REPLICATE (runs:" + runs + ")"); List<InternalTask> toReplicate = new ArrayList<InternalTask>(); // find the tasks that need to be replicated for (InternalTask ti : tasks.values()) { List<InternalTask> tl = ti.getIDependences(); if (tl != null) { for (InternalTask ts : tl) { if (ts.getId().equals(initiator.getId()) && !toReplicate.contains(ti)) { // ti needs to be replicated toReplicate.add(ti); } } } } // for each initial task to replicate for (InternalTask todup : toReplicate) { // determine the target of the replication whether it is a block or a single task InternalTask target = null; // target is a task block start : replication of the block if (todup.getFlowBlock().equals(FlowBlock.START)) { String tg = todup.getMatchingBlock(); for (InternalTask t : tasks.values()) { if (tg.equals(t.getName()) && !(t.getStatus().equals(TaskStatus.FINISHED) || t.getStatus().equals( TaskStatus.SKIPPED)) && t.dependsOn(todup)) { target = t; break; } } if (target == null) { logger.error("REPLICATE: could not find matching block '" + tg + "'"); continue; } } // target is not a block : replication of the task else { target = todup; } // for each number of parallel run for (int i = 1; i < runs; i++) { // accumulates the tasks between the initiator and the target Map<TaskId, InternalTask> dup = new HashMap<TaskId, InternalTask>(); // replicate the tasks between the initiator and the target try { target.replicateTree(dup, todup.getId(), false, initiator .getReplicationIndex() * runs, 0); } catch (Exception e) { logger.error("REPLICATE: could not replicate tree", e); break; } ((JobInfoImpl) this.getJobInfo()).setNumberOfPendingTasks(this.getJobInfo() .getNumberOfPendingTasks() + dup.size()); // pointers to the new replicated tasks corresponding the begin and // the end of the block ; can be the same InternalTask newTarget = null; InternalTask newEnd = null; // configure the new tasks for (Entry<TaskId, InternalTask> it : dup.entrySet()) { InternalTask nt = it.getValue(); nt.setJobInfo(getJobInfo()); int dupIndex = getNextReplicationIndex(InternalTask.getInitialName(nt .getName()), nt.getIterationIndex()); this.addTask(nt); nt.setReplicationIndex(dupIndex); } modifiedTasks.addAll(dup.values()); // find the beginning and the ending of the replicated block for (Entry<TaskId, InternalTask> it : dup.entrySet()) { InternalTask nt = it.getValue(); // connect the first task of the replicated block to the initiator if (todup.getId().equals(it.getKey())) { newTarget = nt; newTarget.addDependence(initiator); // no need to add newTarget to modifiedTasks // because newTarget is among dup.values(), and we // have added them all } // connect the last task of the block with the merge task(s) if (target.getId().equals(it.getKey())) { newEnd = nt; List<InternalTask> toAdd = new ArrayList<InternalTask>(); // find the merge tasks ; can be multiple for (InternalTask t : tasks.values()) { List<InternalTask> pdeps = t.getIDependences(); if (pdeps != null) { for (InternalTask parent : pdeps) { if (parent.getId().equals(target.getId())) { toAdd.add(t); } } } } // connect the merge tasks for (InternalTask t : toAdd) { t.addDependence(newEnd); modifiedTasks.add(t); } } } // propagate the changes on the JobDescriptor getJobDescriptor().doReplicate(taskId, dup, newTarget, target.getId(), newEnd.getId()); } } // notify frontend that tasks were added to the job this.jobInfo.setModifiedTasks(createClientTaskStates(modifiedTasks)); if (frontend != null) { frontend.jobStateUpdated(this.getOwner(), new NotificationData<JobInfo>( SchedulerEvent.TASK_REPLICATED, this.getJobInfo())); } this.jobInfo.setModifiedTasks(null); // no jump is performed ; now that the tasks have been replicated and // configured, the flow can continue its normal operation getJobDescriptor().terminate(taskId); didAction = true; break; } /* * CONTINUE action : * - continue taskflow as if no action was provided */ case CONTINUE: logger.debug("Task flow Action CONTINUE on task " + initiator.getId().getReadableName()); break; } /** System.out.println("******** task dump ** " + this.getJobInfo().getJobId() + " " + initiator.getName() + " does " + action.getType() + " " + ((action.getTarget() == null) ? "." : action.getTarget()) + " " + ((action.getTargetElse() == null) ? "." : action.getTargetElse()) + " " + ((action.getTargetJoin() == null) ? "." : action.getTargetJoin())); for (InternalTask it : this.tasks.values()) { System.out.print(it.getName() + " "); if (it.getIDependences() != null) { System.out.print("deps "); for (InternalTask parent : it.getIDependences()) { System.out.print(parent.getName() + " "); } } if (it.getIfBranch() != null) { System.out.print("if " + it.getIfBranch().getName() + " "); } if (it.getJoinedBranches() != null && it.getJoinedBranches().size() == 2) { System.out.print("join " + it.getJoinedBranches().get(0).getName() + " " + it.getJoinedBranches().get(1).getName()); } System.out.println(); } System.out.println("******** task dump ** " + this.getJobInfo().getJobId()); System.out.println(); **/ } //terminate this task if (!didAction) { getJobDescriptor().terminate(taskId); } //creating list of status for the jobDescriptor HashMap<TaskId, TaskStatus> hts = new HashMap<TaskId, TaskStatus>(); for (InternalTask td : tasks.values()) { hts.put(td.getId(), td.getStatus()); } //updating job descriptor for eligible task getJobDescriptor().update(hts); return descriptor; } private static List<ClientTaskState> createClientTaskStates(List<InternalTask> tasks) { List<ClientTaskState> newTasks = new ArrayList<ClientTaskState>(); for (InternalTask task : tasks) { newTasks.add(new ClientTaskState(task)); } return newTasks; } private int getNextReplicationIndex(String baseName, int iteration) { int rep = 0; for (InternalTask it : this.tasks.values()) { String name = InternalTask.getInitialName(it.getName()); if (baseName.equals(name) && iteration == it.getIterationIndex()) { rep = Math.max(rep, it.getReplicationIndex() + 1); } } return rep; } /** * Walk up <code>down</code>'s dependences until * a task <code>name</code> is met * * also walks weak references created by {@link FlowActionType#IF} * * @return the task names <code>name</code>, or null */ private InternalTask findTaskUp(String name, InternalTask down) { InternalTask ret = null; List<InternalTask> ideps = new ArrayList<InternalTask>(); if (down.getIDependences() != null) { ideps.addAll(down.getIDependences()); } if (down.getJoinedBranches() != null) { ideps.addAll(down.getJoinedBranches()); } if (down.getIfBranch() != null) { ideps.add(down.getIfBranch()); } for (InternalTask up : ideps) { if (up.getName().equals(name)) { ret = up; } else { InternalTask r = findTaskUp(name, up); if (r != null) { ret = r; } } } return ret; } /** * Simulate that a task have been started and terminated. * Used only by the recovery method in scheduler core. * * @param id the id of the task to start and terminate. */ public void simulateStartAndTerminate(TaskId id) { getJobDescriptor().start(id); getJobDescriptor().terminate(id); } /** * Failed this job due to the given task failure or job has been killed * * @param taskId the task that has been the cause to failure. Can be null if the job has been killed * @param jobStatus type of the failure on this job. (failed/canceled/killed) */ public void failed(TaskId taskId, JobStatus jobStatus) { if (jobStatus != JobStatus.KILLED) { InternalTask descriptor = tasks.get(taskId); if (descriptor.getStartTime() > 0) { descriptor.setFinishedTime(System.currentTimeMillis()); setNumberOfFinishedTasks(getNumberOfFinishedTasks() + 1); } descriptor.setStatus((jobStatus == JobStatus.FAILED) ? TaskStatus.FAILED : TaskStatus.FAULTY); //terminate this job descriptor getJobDescriptor().failed(); } //set the new status of the job setFinishedTime(System.currentTimeMillis()); setNumberOfPendingTasks(0); setNumberOfRunningTasks(0); setStatus(jobStatus); //creating list of status HashMap<TaskId, TaskStatus> hts = new HashMap<TaskId, TaskStatus>(); HashMap<TaskId, Long> htl = new HashMap<TaskId, Long>(); for (InternalTask td : tasks.values()) { if (!td.getId().equals(taskId)) { if (td.getStatus() == TaskStatus.RUNNING) { td.setStatus(TaskStatus.ABORTED); td.setFinishedTime(System.currentTimeMillis()); } else if (td.getStatus() == TaskStatus.WAITING_ON_ERROR || td.getStatus() == TaskStatus.WAITING_ON_FAILURE) { td.setStatus(TaskStatus.NOT_RESTARTED); } else if (td.getStatus() != TaskStatus.FINISHED && td.getStatus() != TaskStatus.FAILED && td.getStatus() != TaskStatus.FAULTY && td.getStatus() != TaskStatus.SKIPPED) { td.setStatus(TaskStatus.NOT_STARTED); } } htl.put(td.getId(), td.getFinishedTime()); hts.put(td.getId(), td.getStatus()); } setTaskStatusModify(hts); setTaskFinishedTimeModify(htl); if (jobDataSpaceApplication != null) { jobDataSpaceApplication.terminateDataSpaceApplication(); } } /** * Get a task descriptor that is in the running task queue. * * @param id the id of the task descriptor to retrieve. * @return the task descriptor associated to this id, or null if not running. */ public TaskDescriptor getRunningTaskDescriptor(TaskId id) { return getJobDescriptor().GetRunningTaskDescriptor(id); } /** * Set all properties following a job submitting. */ public void submitAction() { setSubmittedTime(System.currentTimeMillis()); setStatus(JobStatus.PENDING); } /** * Prepare tasks in order to be ready to be scheduled. * The task may have a consistent id and job info. */ public synchronized void prepareTasks() { //get tasks ArrayList<InternalTask> sorted = getITasks(); //sort task according to the ID Collections.sort(sorted); tasks.clear(); //re-init taskId int id = 0; for (InternalTask td : sorted) { TaskId newId = TaskIdImpl.createTaskId(getId(), td.getName(), id++, true); td.setId(newId); td.setJobInfo(getJobInfo()); tasks.put(newId, td); } } /** * Set all properties in order to start the job. * After this method and for better performances you may have to * set the taskStatusModify to "null" : setTaskStatusModify(null); */ public void start() { setStartTime(System.currentTimeMillis()); setNumberOfPendingTasks(getTotalNumberOfTasks()); setNumberOfRunningTasks(0); setStatus(JobStatus.RUNNING); HashMap<TaskId, TaskStatus> taskStatus = new HashMap<TaskId, TaskStatus>(); for (InternalTask td : getITasks()) { td.setStatus(TaskStatus.PENDING); taskStatus.put(td.getId(), TaskStatus.PENDING); } setTaskStatusModify(taskStatus); } /** * Set all properties in order to terminate the job. */ public void terminate() { setStatus(JobStatus.FINISHED); setFinishedTime(System.currentTimeMillis()); if (jobDataSpaceApplication != null) { if (!logger.isDebugEnabled()) { jobDataSpaceApplication.terminateDataSpaceApplication(); } } } /** * Paused every running and submitted tasks in this pending job. * After this method and for better performances you may have to * set the taskStatusModify to "null" : setTaskStatusModify(null); * * @return true if the job has correctly been paused, false if not. */ public boolean setPaused() { if (jobInfo.getStatus() == JobStatus.PAUSED) { return false; } jobInfo.setStatus(JobStatus.PAUSED); HashMap<TaskId, TaskStatus> hts = new HashMap<TaskId, TaskStatus>(); for (InternalTask td : tasks.values()) { if ((td.getStatus() != TaskStatus.FINISHED) && (td.getStatus() != TaskStatus.RUNNING) && (td.getStatus() != TaskStatus.SKIPPED) && (td.getStatus() != TaskStatus.FAULTY)) { td.setStatus(TaskStatus.PAUSED); } hts.put(td.getId(), td.getStatus()); } getJobDescriptor().update(hts); setTaskStatusModify(hts); return true; } /** * Status of every paused tasks becomes pending or submitted in this pending job. * After this method and for better performances you may have to * set the taskStatusModify to "null" : setTaskStatusModify(null); * * @return true if the job has correctly been unpaused, false if not. */ public boolean setUnPause() { if (jobInfo.getStatus() != JobStatus.PAUSED) { return false; } if ((getNumberOfPendingTasks() + getNumberOfRunningTasks() + getNumberOfFinishedTasks()) == 0) { jobInfo.setStatus(JobStatus.PENDING); } else if (getNumberOfRunningTasks() == 0) { jobInfo.setStatus(JobStatus.STALLED); } else { jobInfo.setStatus(JobStatus.RUNNING); } HashMap<TaskId, TaskStatus> hts = new HashMap<TaskId, TaskStatus>(); for (InternalTask td : tasks.values()) { if (jobInfo.getStatus() == JobStatus.PENDING) { td.setStatus(TaskStatus.SUBMITTED); } else if ((jobInfo.getStatus() == JobStatus.RUNNING) || (jobInfo.getStatus() == JobStatus.STALLED)) { if ((td.getStatus() != TaskStatus.FINISHED) && (td.getStatus() != TaskStatus.RUNNING) && (td.getStatus() != TaskStatus.SKIPPED) && (td.getStatus() != TaskStatus.FAULTY)) { td.setStatus(TaskStatus.PENDING); } } hts.put(td.getId(), td.getStatus()); } getJobDescriptor().update(hts); setTaskStatusModify(hts); return true; } /** * @see org.ow2.proactive.scheduler.common.job.Job#setPriority(org.ow2.proactive.scheduler.common.job.JobPriority) */ @Override public void setPriority(JobPriority priority) { jobInfo.setPriority(priority); } /** * @see org.ow2.proactive.scheduler.common.job.JobState#getTasks() */ @Override public ArrayList<TaskState> getTasks() { return new ArrayList<TaskState>(tasks.values()); } public void setTasks(Collection<InternalTask> tasksList) { tasks = new HashMap<TaskId, InternalTask>(tasksList.size()); for (InternalTask task : tasksList) { tasks.put(task.getId(), task); } } /** * @see org.ow2.proactive.scheduler.common.job.JobState#getHMTasks() */ @Override public Map<TaskId, TaskState> getHMTasks() { Map<TaskId, TaskState> tmp = new HashMap<TaskId, TaskState>(); for (Entry<TaskId, InternalTask> e : tasks.entrySet()) { tmp.put(e.getKey(), e.getValue()); } return tmp; } /** * To get the tasks as an array list. * * @return the tasks */ public ArrayList<InternalTask> getITasks() { return new ArrayList<InternalTask>(tasks.values()); } /** * To get the tasks as a hash map. * * @return the tasks */ public Map<TaskId, InternalTask> getIHMTasks() { return tasks; } /** * To set the taskStatusModify * * @param taskStatusModify the taskStatusModify to set */ public void setTaskStatusModify(Map<TaskId, TaskStatus> taskStatusModify) { jobInfo.setTaskStatusModify(taskStatusModify); } /** * To set the taskFinishedTimeModify * * @param taskFinishedTimeModify the taskFinishedTimeModify to set */ public void setTaskFinishedTimeModify(Map<TaskId, Long> taskFinishedTimeModify) { jobInfo.setTaskFinishedTimeModify(taskFinishedTimeModify); } /** * To set the tasksReplicated * * @param d tasksReplicated */ public void setReplicatedTasksModify(List<ReplicatedTask> d) { jobInfo.setTasksReplicated(d); } /** * To set the tasksLooped * * @param d tasksLooped */ public void setLoopedTasksModify(List<ReplicatedTask> d) { jobInfo.setTasksLooped(d); } /** * To set the tasksSkipped * * @param d tasksSkipped */ public void setSkippedTasksModify(List<TaskId> d) { jobInfo.setTasksSkipped(d); } /** * To set the id * * @param id the id to set */ public void setId(JobId id) { jobInfo.setJobId(id); } /** * To set the finishedTime * * @param finishedTime * the finishedTime to set */ public void setFinishedTime(long finishedTime) { jobInfo.setFinishedTime(finishedTime); } /** * To set the startTime * * @param startTime * the startTime to set */ public void setStartTime(long startTime) { jobInfo.setStartTime(startTime); } /** * To set the submittedTime * * @param submittedTime * the submittedTime to set */ public void setSubmittedTime(long submittedTime) { jobInfo.setSubmittedTime(submittedTime); } /** * To set the removedTime * * @param removedTime * the removedTime to set */ public void setRemovedTime(long removedTime) { jobInfo.setRemovedTime(removedTime); } /** * To set the numberOfFinishedTasks * * @param numberOfFinishedTasks the numberOfFinishedTasks to set */ public void setNumberOfFinishedTasks(int numberOfFinishedTasks) { jobInfo.setNumberOfFinishedTasks(numberOfFinishedTasks); } /** * To set the numberOfPendingTasks * * @param numberOfPendingTasks the numberOfPendingTasks to set */ public void setNumberOfPendingTasks(int numberOfPendingTasks) { jobInfo.setNumberOfPendingTasks(numberOfPendingTasks); } /** * To set the numberOfRunningTasks * * @param numberOfRunningTasks the numberOfRunningTasks to set */ public void setNumberOfRunningTasks(int numberOfRunningTasks) { jobInfo.setNumberOfRunningTasks(numberOfRunningTasks); } /** * To get the jobDescriptor * * @return the jobDescriptor */ @XmlTransient public JobDescriptorImpl getJobDescriptor() { if (jobDescriptor == null) { jobDescriptor = new JobDescriptorImpl(this); } return (JobDescriptorImpl) jobDescriptor; } /** * Set the job Descriptor * * @param jobD the JobDescriptor to set. */ public void setJobDescriptor(JobDescriptor jobD) { this.jobDescriptor = jobD; } /** * @param status the status to set */ public void setStatus(JobStatus status) { jobInfo.setStatus(status); } /** * @see org.ow2.proactive.scheduler.common.job.JobState#getOwner() */ @Override public String getOwner() { return owner; } /** * To set the owner of this job. * * @param owner the owner to set. */ public void setOwner(String owner) { this.owner = owner; } /** * Get the credentials for this job * * @return the credentials for this job */ public Credentials getCredentials() { return credentials; } /** * Set the credentials value to the given credentials value * * @param credentials the credentials to set */ public void setCredentials(Credentials credentials) { this.credentials = credentials; } /** * Get the next restart waiting time in millis. * * @return the next restart waiting time in millis. */ public long getNextWaitingTime(int executionNumber) { if (executionNumber <= 0) { //execution number is 0 or less, restart with the minimal amount of time return restartWaitingTimer; } else if (executionNumber > 10) { //execution timer exceed 10, restart after 60 seconds return 60 * 1000; } else { //else restart according to this function return (getNextWaitingTime(executionNumber - 1) + executionNumber * 1000); } } /** * Set this job to the state toBeRemoved. */ public void setToBeRemoved() { jobInfo.setToBeRemoved(); } /** * @see java.lang.Object#equals(java.lang.Object) */ @Override public boolean equals(Object o) { if (o instanceof InternalJob) { return getId().equals(((InternalJob) o).getId()); } return false; } /** * Get the jobDataSpaceApplication * * @return the jobDataSpaceApplication */ public JobDataSpaceApplication getJobDataSpaceApplication() { return jobDataSpaceApplication; } private transient Map<String, InternalTask> tasknameITaskMapping = null; /** * Return the internal task associated with the given task name for this job. * * @param taskName the task name to find * @return the internal task associated with the given name. * @throws UnknownTaskException if the given taskName does not exist. */ public InternalTask getTask(String taskName) throws UnknownTaskException { if (tasknameITaskMapping == null) { tasknameITaskMapping = new HashMap<String, InternalTask>(tasks.size()); for (InternalTask it : tasks.values()) { tasknameITaskMapping.put(it.getId().getReadableName(), it); } } if (tasknameITaskMapping.containsKey(taskName)) { return tasknameITaskMapping.get(taskName); } else { throw new UnknownTaskException("'" + taskName + "' does not exist in this job."); } } //******************************************************************** //************************* SERIALIZATION **************************** //******************************************************************** /** * <b>IMPORTANT : </b><br /> * Using hibernate does not allow to have java transient fields that is inserted in database anyway.<br /> * Hibernate defined @Transient annotation meaning the field won't be inserted in database. * If the java transient modifier is set for a field, so the hibernate @Transient annotation becomes * useless and the field won't be inserted in DB anyway.<br /> * For performance reason, some field must be java transient but not hibernate transient. * These fields are annotated with @TransientInSerialization. * The @TransientInSerialization describe the fields that won't be serialized by java since the two following * methods describe the serialization process. */ private void writeObject(ObjectOutputStream out) throws IOException { try { Map<String, Object> toSerialize = new HashMap<String, Object>(); Field[] fields = InternalJob.class.getDeclaredFields(); for (Field f : fields) { if (!f.isAnnotationPresent(TransientInSerialization.class) && !Modifier.isStatic(f.getModifiers())) { toSerialize.put(f.getName(), f.get(this)); } } out.writeObject(toSerialize); } catch (Exception e) { throw new RuntimeException(e); } } @SuppressWarnings("unchecked") private void readObject(ObjectInputStream in) throws IOException, ClassNotFoundException { try { Map<String, Object> map = (Map<String, Object>) in.readObject(); for (Entry<String, Object> e : map.entrySet()) { InternalJob.class.getDeclaredField(e.getKey()).set(this, e.getValue()); } } catch (Exception e) { throw new RuntimeException(e); } } }
agpl-3.0
bluestreak01/questdb
core/src/test/java/io/questdb/mp/SOUnboundedCountDownLatchTest.java
5187
/******************************************************************************* * ___ _ ____ ____ * / _ \ _ _ ___ ___| |_| _ \| __ ) * | | | | | | |/ _ \/ __| __| | | | _ \ * | |_| | |_| | __/\__ \ |_| |_| | |_) | * \__\_\\__,_|\___||___/\__|____/|____/ * * Copyright (c) 2014-2019 Appsicle * Copyright (c) 2019-2022 QuestDB * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * ******************************************************************************/ package io.questdb.mp; import io.questdb.log.Log; import io.questdb.log.LogFactory; import io.questdb.std.datetime.millitime.Dates; import org.junit.Assert; import org.junit.Test; import java.util.concurrent.BrokenBarrierException; import java.util.concurrent.CyclicBarrier; import java.util.concurrent.atomic.AtomicInteger; public class SOUnboundedCountDownLatchTest { private static final Log LOG = LogFactory.getLog(SOUnboundedCountDownLatchTest.class); @Test public void testUnboundedLatch() throws BrokenBarrierException, InterruptedException { SPSequence pubSeq = new SPSequence(1024); SCSequence subSeq = new SCSequence(); // this latch does not require initial count. Instead it is able to wait // for a specific target count. This is useful when it is hard to // determine work item count upfront. final SOUnboundedCountDownLatch latch = new SOUnboundedCountDownLatch(); final AtomicInteger dc = new AtomicInteger(); pubSeq.then(subSeq).then(pubSeq); int count = 1_000_000; doTest(pubSeq, subSeq, latch, dc, count, 0); LOG.info().$("waiting on [count=").$(count).$(']').$(); latch.await(count); LOG.info().$("section 1 done").$(); Assert.assertEquals(count, dc.get()); dc.set(0); latch.reset(); doTest(pubSeq, subSeq, latch, dc, count, count); LOG.info().$("waiting on [count=").$(count).$(']').$(); latch.await(count); LOG.info().$("section 2 done").$(); Assert.assertEquals(count, dc.get()); } private void doTest(SPSequence pubSeq, SCSequence subSeq, SOUnboundedCountDownLatch latch, AtomicInteger dc, int count, int s) throws BrokenBarrierException, InterruptedException { final CyclicBarrier barrier = new CyclicBarrier(2); AtomicInteger errors = new AtomicInteger(); LOG.info().$("starting thread").$(); new Thread() { int doneCount = 0; long time = System.currentTimeMillis(); @Override public void run() { try { LOG.info().$("thread is running").$(); barrier.await(); LOG.info().$("thread is away").$(); long last = s - 1; while (doneCount < count) { long c = subSeq.next(); if (c > -1) { subSeq.done(c); doneCount++; dc.incrementAndGet(); latch.countDown(); Assert.assertEquals(last + 1, c); last = c; } else if (c == -1) { Thread.yield(); } if (System.currentTimeMillis() - time > Dates.MINUTE_MILLIS) { LOG.error() .$("so_latch_state [doneCount=").$(doneCount) .$(", count=").$(count) .$(", seq.current").$(subSeq.current()) .$(", seq.cache=").$(pubSeq.cache) .$(", latch.count=").$(latch.getCount()) .$(']').$(); time = System.currentTimeMillis(); } } } catch (Exception e) { errors.incrementAndGet(); } LOG.info().$("thread ended").$(); } }.start(); LOG.info().$("about to start publishing").$(); barrier.await(); LOG.info().$("publishing").$(); for (int i = 0; i < count; ) { Assert.assertEquals(0, errors.get()); long c = pubSeq.next(); if (c > -1) { i++; pubSeq.done(c); } else if (c == -1) { Thread.yield(); } } LOG.info().$("all published").$(); } }
agpl-3.0
CodeSphere/termitaria
TermitariaCM/src/ro/cs/cm/web/controller/form/ProjectController.java
33545
/******************************************************************************* * This file is part of Termitaria, a project management tool * Copyright (C) 2008-2013 CodeSphere S.R.L., www.codesphere.ro * * Termitaria 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 Termitaria. If not, see <http://www.gnu.org/licenses/> . ******************************************************************************/ package ro.cs.cm.web.controller.form; import java.lang.reflect.Field; import java.net.URLEncoder; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Locale; import java.util.Map; import java.util.Set; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.json.JSONArray; import org.json.JSONObject; import org.springframework.beans.propertyeditors.CustomCollectionEditor; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.validation.BindException; import org.springframework.validation.Errors; import org.springframework.web.bind.ServletRequestDataBinder; import org.springframework.web.bind.ServletRequestUtils; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.support.RequestContextUtils; import ro.cs.cm.business.BLAudit; import ro.cs.cm.business.BLClient; import ro.cs.cm.business.BLPerson; import ro.cs.cm.business.BLProject; import ro.cs.cm.business.BLProjectTeam; import ro.cs.cm.business.BLUser; import ro.cs.cm.common.IConstant; import ro.cs.cm.common.PermissionConstant; import ro.cs.cm.entity.Client; import ro.cs.cm.entity.Project; import ro.cs.cm.entity.ProjectProjectTeam; import ro.cs.cm.entity.ProjectTeam; import ro.cs.cm.entity.TeamMember; import ro.cs.cm.exception.BusinessException; import ro.cs.cm.om.Person; import ro.cs.cm.web.controller.root.ControllerUtils; import ro.cs.cm.web.controller.root.RootSimpleFormController; import ro.cs.cm.web.security.UserAuth; import ro.cs.cm.ws.client.om.entity.UserSimple; public class ProjectController extends RootSimpleFormController { private static final String SUCCESS_VIEW = "Project"; private static final String FORM_VIEW = "Project"; //------------------------MESSAGE KEY-------------------------------------------------------------- private static final String ROOT_KEY = "project."; private final String ADD_SUCCESS = ROOT_KEY.concat("add.success"); private final String ADD_ERROR = ROOT_KEY.concat("add.error"); private final String GET_ERROR = ROOT_KEY.concat("get.error"); private final String UPDATE_SUCCESS = ROOT_KEY.concat("update.success"); private final String UPDATE_ERROR = ROOT_KEY.concat("update.error"); private final String GENERAL_ERROR = ROOT_KEY.concat("general.error"); private String GET_PERSONS_FROM_ORG_ERROR = ROOT_KEY.concat("get.persons.by.organisation.error"); private String GET_CLIENTS_FROM_ORG_ERROR = ROOT_KEY.concat("get.clients.by.organisation.error"); private String GET_CLIENT_ERROR = "client.get.error"; //------------------------ATTRIBUTES--------------------------------------------------------------- private final String PROJECT_ID = "projectId"; private final String CLIENT_ID = "clientId"; private final String CMD_ADD_PROJECT_FROM_CLIENT_FORM = "ADD_PROJECT_FROM_CLIENT_FORM"; //------------------------OTHER PARAMETERS--------------------------------------------------------- private static final String JSON_PERSONS = "JSON_PERSONS"; private static final String JSON_CLIENTS = "JSON_CLIENTS"; private final String MODEL_MANAGER_NAME = "MANAGER_NAME"; private final String MODEL_CLIENT_NAME = "CLIENT_NAME"; private final String STATUS = "STATUS"; private final String STATUS_PROJECT_TEAM = "STATUS_PROJECT_TEAM"; private final String ORGANIZATION_ID = "ORGANIZATION_ID"; private final String ALL_PERSONS = "ALL_PERSONS"; private final String PROJECT_TEAM_MANAGERID = "PROJECT_TEAM_MANAGERID"; private static final String MEMBERS = "members"; private static final String NUMBER_OF_MEMBERS = "nrOfMembers"; private static final String USER_ID = "USER_ID"; //--------------------BACK PARAMETERS------------------------------------------------------------- private static final String BACK_URL = "BACK_URL"; private static final String NEXT_BACK_URL = "NEXT_BACK_URL"; private static final String ENCODE_BACK_URL = "ENCODE_BACK_URL"; public ProjectController() { setCommandName("projectProjectTeamBean"); setCommandClass(ProjectProjectTeam.class); setFormView(FORM_VIEW); setSuccessView(SUCCESS_VIEW); } /** * Bindings for request parameters * * @author Adelina */ protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception { logger.debug("start - initBinder"); binder.registerCustomEditor(Set.class, "projectTeam.persons", new CustomCollectionEditor(Set.class){ protected Object convertElement(Object element){ if(element != null){ Integer personId = new Integer((String)element); logger.debug("person : convertElement for Id " + personId); Person person = null; try{ person = BLPerson.getInstance().get(personId); } catch(BusinessException e){ logger.debug("There was an error"); } logger.debug("start - initBinder"); return person; } logger.debug("start - initBinder"); return null; } }); } /** * It runs at every cycle * * @author Adelina */ @Override protected Object formBackingObject(HttpServletRequest request) throws Exception { logger.debug("formBackingObject - START"); // used as a container for info/error messages ArrayList<String> infoMessages = new ArrayList<String>(); ArrayList<String> errorMessages = new ArrayList<String>(); // locale Locale locale = RequestContextUtils.getLocale(request); // backing object ProjectProjectTeam projectProjectTeam = new ProjectProjectTeam(); try{ // backing object id Integer projectId = -1; String pid = ServletRequestUtils.getStringParameter(request, PROJECT_ID); if(pid != null) { projectId = Integer.parseInt(pid); } request.setAttribute(PROJECT_ID, projectId); logger.debug("projectId = ".concat(String.valueOf(projectId))); // redirecting regarding the operation String action = ServletRequestUtils.getStringParameter(request, IConstant.REQ_ACTION); logger.debug("action = ".concat(action)); if(action != null) { // check if i have to edit a project if(IConstant.CMD_GET.equals(action)) { logger.debug("formBackingObject: Get"); projectProjectTeam.setProject(handleGet(projectId, request, errorMessages, infoMessages, locale)); projectProjectTeam.setProjectTeam(handleGetProjectTeam(projectId, request, errorMessages, infoMessages, locale)); } else if(IConstant.CMD_ADD.equals(action)) { // or add a new project logger.debug("formBackingObject: New"); projectProjectTeam.setProject(new Project()); projectProjectTeam.setProjectTeam(new ProjectTeam()); } else if(CMD_ADD_PROJECT_FROM_CLIENT_FORM.equals(action)) { logger.debug("formBackingObject : New from Client"); Integer clientId = ServletRequestUtils.getIntParameter(request, CLIENT_ID); request.setAttribute(CLIENT_ID, clientId); Project project = new Project(); project.setClientId(clientId); projectProjectTeam.setProject(project); projectProjectTeam.setProjectTeam(new ProjectTeam()); } } } catch (Exception e) { logger.error("formBackingObject", e); errorMessages.add(messageSource.getMessage(GET_ERROR, new Object[] {null, ControllerUtils.getInstance().getFormattedCurrentTime()}, locale)); } setMessages(request, infoMessages); setErrors(request, errorMessages); logger.debug("formBackingObject END command ".concat(projectProjectTeam.toString())); return projectProjectTeam; } /** * It runs on every submit (request Method = POST) * It detects the case by action parameter and dispatch to and appropriate handler. * * @author Adelina */ @Override protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception { logger.debug("onSubmit - START"); // for model and view ModelAndView mav = new ModelAndView(); //for locale Locale locale = RequestContextUtils.getLocale(request); //used as a container for info/error messages ArrayList<String> infoMessages = new ArrayList<String>(); ArrayList<String> errorMessages = new ArrayList<String>(); // the command class ProjectProjectTeam projectProjectTeam = (ProjectProjectTeam) command; Project project = projectProjectTeam.getProject(); ProjectTeam projectTeam = projectProjectTeam.getProjectTeam(); projectTeam.setProjectId(project.getProjectId()); // redirecting regarding the operation String action = ServletRequestUtils.getStringParameter(request, IConstant.REQ_ACTION); logger.debug("action = ".concat(action)); if(action != null) { if(IConstant.CMD_SAVE.equals(action)) { if(project.getProjectId() > 0) { project = handleUpdate(request, response, project, errors, errorMessages, infoMessages, locale); handleUpdateProjectTeam(request, response, projectTeam, project, errors, errorMessages, infoMessages, locale); } else { project = handleAdd(request, response, project, errors, errorMessages, infoMessages, locale); request.setAttribute(PROJECT_ID, project.getProjectId()); handleAddProjectTeam(request, response, projectTeam, project, errors, errorMessages, infoMessages, locale); } mav = new ModelAndView(getSuccessView()); mav.addObject(getCommandName(), projectProjectTeam); } } //Publish Info/Error messages setMessages(request, infoMessages); setErrors(request, errorMessages); //Add referenceData objects to model mav.addAllObjects(referenceData(request, command, errors)); logger.debug("onSubmit - END"); return mav; } /** * Adds a project * * @author Adelina * * @param request * @param response * @param command * @param errors * @param errorMessages * @param infoMessages * @param locale * @return * @throws Exception */ private Project handleAdd(HttpServletRequest request, HttpServletResponse response, Project project, BindException errors, ArrayList<String> errorMessages, ArrayList<String> infoMessages, Locale locale) throws Exception { logger.debug("handleAdd - START"); UserAuth userAuth = (UserAuth) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); try{ // adding the project to the database project = BLProject.getInstance().addAll(project); String projectName = ControllerUtils.getInstance().tokenizeField(project.getName(), IConstant.NR_CHARS_PER_LINE_MESSAGE); infoMessages.add(messageSource.getMessage(ADD_SUCCESS, new Object[] {projectName}, locale)); //add the new audit event only if the user is not AdminIT try { if (!userAuth.isAdminIT()){ BLAudit.getInstance().add(IConstant.AUDIT_EVENT_PROJECT_ADD_TYPE, userAuth.getFirstName(), userAuth.getLastName(), messageSource.getMessage(IConstant.AUDIT_EVENT_PROJECT_ADD_MESSAGE, new Object[] {project.getName()}, new Locale("en")), messageSource.getMessage(IConstant.AUDIT_EVENT_PROJECT_ADD_MESSAGE, new Object[] {project.getName()}, new Locale("ro")), ControllerUtils.getInstance().getOrganisationIdFromSession(request), userAuth.getPersonId()); } } catch (Exception exc) { logger.error("", exc); } } catch (BusinessException be) { logger.error("", be); errorMessages.add(messageSource.getMessage(ADD_ERROR, new Object[] {be.getCode(), ControllerUtils.getInstance().getFormattedCurrentTime()}, RequestContextUtils .getLocale(request))); } catch (Exception e){ logger.error("", e); errorMessages.add(messageSource.getMessage(GENERAL_ERROR, new Object[] {null, ControllerUtils.getInstance().getFormattedCurrentTime()}, RequestContextUtils .getLocale(request))); } logger.debug("handleAdd - END"); return project; } /** * Adds a project team * * @author Adelina * * @param request * @param response * @param command * @param errors * @param errorMessages * @param infoMessages * @param locale * @return * @throws Exception */ private void handleAddProjectTeam(HttpServletRequest request, HttpServletResponse response, ProjectTeam projectTeam, Project project, BindException errors, ArrayList<String> errorMessages, ArrayList<String> infoMessages, Locale locale) throws Exception { logger.debug("handleAdd - START"); try{ projectTeam.setStatus(IConstant.NOM_PROJECT_TEAM_STATUS_ACTIVATED); projectTeam.setProjectId(project.getProjectId()); Set<Person> persons = projectTeam.getPersons(); if(persons == null || persons.size() == 0) { persons = new HashSet<Person>(); } persons.add(project.getManager()); projectTeam.setPersons(persons); String jsonString = ServletRequestUtils.getStringParameter(request, MEMBERS); logger.debug("jsonString = " + jsonString); Integer nrOfMembers = ServletRequestUtils.getIntParameter(request, NUMBER_OF_MEMBERS); logger.debug("nrOfMembers = " + nrOfMembers); if(jsonString == "") { jsonString="{}"; } JSONObject JObject = new JSONObject(jsonString); List<TeamMember> externalMembers = new ArrayList<TeamMember>(); if(nrOfMembers > 0) { for(int i = 0; i < nrOfMembers; i++) { JSONArray object = (JSONArray)JObject.get("members"); TeamMember member = new TeamMember(); Class clazz = member.getClass(); //get all object fields Field[] fields = clazz.getDeclaredFields(); Integer nrOfFields = fields.length; member.setFirstName((String)(object.getJSONObject(i).get(fields[1].getName()))); member.setLastName((String)(object.getJSONObject(i).get(fields[2].getName()))); member.setEmail((String)(object.getJSONObject(i).get(fields[3].getName()))); member.setAddress((String)(object.getJSONObject(i).get(fields[4].getName()))); member.setPhone((String)(object.getJSONObject(i).get(fields[5].getName()))); member.setObservation((String)(object.getJSONObject(i).get(fields[6].getName()))); member.setDescription((String)(object.getJSONObject(i).get(fields[7].getName()))); member.setPersonId(new Integer(0)); member.setStatus((byte)1); logger.debug("team member = " + member); logger.debug("isExternal = " + member.getIdExternal()); externalMembers.add(member); } } // adding the project team to the database BLProjectTeam.getInstance().add(projectTeam, externalMembers); } catch (BusinessException be) { logger.error("", be); errorMessages.add(messageSource.getMessage(ADD_ERROR, new Object[] {be.getCode(), ControllerUtils.getInstance().getFormattedCurrentTime()}, RequestContextUtils .getLocale(request))); } catch (Exception e){ logger.error("", e); errorMessages.add(messageSource.getMessage(GENERAL_ERROR, new Object[] {null, ControllerUtils.getInstance().getFormattedCurrentTime()}, RequestContextUtils .getLocale(request))); } logger.debug("handleAdd - END"); } /** * Updates a project * * @author Adelina * * @param request * @param response * @param command * @param errors * @param errorMessages * @param infoMessages * @param locale * @return * @throws Exception */ private Project handleUpdate(HttpServletRequest request, HttpServletResponse response, Project project, BindException errors, ArrayList<String> errorMessages, ArrayList<String> infoMessages, Locale locale) throws Exception { logger.debug("handleUpdate - START"); try{ UserAuth userAuth = (UserAuth) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); if(project.isProjectNoClient()) { project.setClientId(new Integer(-1)); } // updating the project to the database project = BLProject.getInstance().updateAll(project); if(project.getClientId() != null && project.getClientId() == -1) { project.setProjectNoClient(true); } else { project.setProjectNoClient(false); } String projectName = ControllerUtils.getInstance().tokenizeField(project.getName(), IConstant.NR_CHARS_PER_LINE_MESSAGE); infoMessages.add(messageSource.getMessage(UPDATE_SUCCESS, new Object[] {projectName}, locale)); //add the new audit event only if the user is not AdminIT try { if (!userAuth.isAdminIT()){ BLAudit.getInstance().add(IConstant.AUDIT_EVENT_PROJECT_UPDATE_TYPE, userAuth.getFirstName(), userAuth.getLastName(), messageSource.getMessage(IConstant.AUDIT_EVENT_PROJECT_UPDATE_MESSAGE, new Object[] {project.getName()}, new Locale("en")), messageSource.getMessage(IConstant.AUDIT_EVENT_PROJECT_UPDATE_MESSAGE, new Object[] {project.getName()}, new Locale("ro")), ControllerUtils.getInstance().getOrganisationIdFromSession(request), userAuth.getPersonId()); } } catch (Exception exc) { logger.error("", exc); } } catch (BusinessException be) { logger.error("", be); errorMessages.add(messageSource.getMessage(UPDATE_ERROR, new Object[] {be.getCode(), ControllerUtils.getInstance().getFormattedCurrentTime()}, RequestContextUtils .getLocale(request))); } catch (Exception e){ logger.error("", e); errorMessages.add(messageSource.getMessage(GENERAL_ERROR, new Object[] {null, ControllerUtils.getInstance().getFormattedCurrentTime()}, RequestContextUtils .getLocale(request))); } logger.debug("handleUpdate - END"); return project; } /** * Updates a project team * * @author Adelina * * @param request * @param response * @param command * @param errors * @param errorMessages * @param infoMessages * @param locale * @return * @throws Exception */ private void handleUpdateProjectTeam(HttpServletRequest request, HttpServletResponse response, ProjectTeam projectTeam, Project project, BindException errors, ArrayList<String> errorMessages, ArrayList<String> infoMessages, Locale locale) throws Exception { logger.debug("handleUpdate - START"); try{ Set<Person> persons = projectTeam.getPersons(); persons.add(project.getManager()); projectTeam.setPersons(persons); String jsonString = ServletRequestUtils.getStringParameter(request, MEMBERS); logger.debug("jsonString = " + jsonString); Integer nrOfMembers = ServletRequestUtils.getIntParameter(request, NUMBER_OF_MEMBERS); logger.debug("nrOfMembers = " + nrOfMembers); if(jsonString == "") { jsonString="{}"; } JSONObject JObject = new JSONObject(jsonString); List<TeamMember> externalMembers = new ArrayList<TeamMember>(); if(nrOfMembers > 0) { for(int i = 0; i < nrOfMembers; i++) { JSONArray object = (JSONArray)JObject.get("members"); TeamMember member = new TeamMember(); Class clazz = member.getClass(); //get all object fields Field[] fields = clazz.getDeclaredFields(); Integer nrOfFields = fields.length; String memberId = (String)(object.getJSONObject(i).get(fields[0].getName())); logger.debug("memberId = " + memberId); member.setMemberId(Integer.valueOf(memberId)); member.setFirstName((String)(object.getJSONObject(i).get(fields[1].getName()))); member.setLastName((String)(object.getJSONObject(i).get(fields[2].getName()))); member.setEmail((String)(object.getJSONObject(i).get(fields[3].getName()))); member.setAddress((String)(object.getJSONObject(i).get(fields[4].getName()))); member.setPhone((String)(object.getJSONObject(i).get(fields[5].getName()))); member.setObservation((String)(object.getJSONObject(i).get(fields[6].getName()))); member.setDescription((String)(object.getJSONObject(i).get(fields[7].getName()))); member.setPersonId(new Integer(0)); member.setStatus((byte)1); member.setProjectTeamId(projectTeam.getProjectTeamId()); logger.debug("team member = " + member); logger.debug("isExternal = " + member.getIdExternal()); externalMembers.add(member); } } logger.debug("externalMembers = " + externalMembers); // updating the project team to the database BLProjectTeam.getInstance().update(projectTeam, externalMembers); } catch (BusinessException be) { logger.error("", be); errorMessages.add(messageSource.getMessage(UPDATE_ERROR, new Object[] {be.getCode(), ControllerUtils.getInstance().getFormattedCurrentTime()}, RequestContextUtils .getLocale(request))); } catch (Exception e){ logger.error("", e); errorMessages.add(messageSource.getMessage(GENERAL_ERROR, new Object[] {null, ControllerUtils.getInstance().getFormattedCurrentTime()}, RequestContextUtils .getLocale(request))); } logger.debug("handleUpdate - END"); } /** * Gets a project * * @author Adelina * * @param projectId * @param request * @param errorMessages * @param infoMessages * @param locale * @return */ private Project handleGet(Integer projectId, HttpServletRequest request, ArrayList<String> errorMessages, ArrayList<String> infoMessages, Locale locale) { logger.debug("handleGet - START"); Project project = null; try{ // call the get method from the business layer project = BLProject.getInstance().getWithAll(projectId); Person manager = project.getManager(); logger.debug("manager = " + manager); // setting a blank manager if it hasn't any if(manager == null) { project.setManager(new Person()); } if(project.getClientId() != null && project.getClientId() == -1) { project.setProjectNoClient(true); } else { project.setProjectNoClient(false); } } catch (BusinessException be) { logger.error("", be); errorMessages.add(messageSource.getMessage(GET_ERROR, new Object[] {be.getCode(), ControllerUtils.getInstance().getFormattedCurrentTime()}, RequestContextUtils .getLocale(request))); } catch (Exception e){ logger.error("", e); errorMessages.add(messageSource.getMessage(GENERAL_ERROR, new Object[] {null, ControllerUtils.getInstance().getFormattedCurrentTime()}, RequestContextUtils .getLocale(request))); } logger.debug("handleGet - END"); return project; } /** * Gets a project team * * @author Adelina * * @param projectId * @param request * @param errorMessages * @param infoMessages * @param locale * @return */ private ProjectTeam handleGetProjectTeam(Integer projectId, HttpServletRequest request, ArrayList<String> errorMessages, ArrayList<String> infoMessages, Locale locale) { logger.debug("handleGet - START"); ProjectTeam projectTeam = null; try{ // call the get method from the business layer projectTeam = BLProjectTeam.getInstance().get(projectId, false); logger.debug("projectTeam = " + projectTeam); } catch (BusinessException be) { logger.error("", be); errorMessages.add(messageSource.getMessage(GET_ERROR, new Object[] {be.getCode(), ControllerUtils.getInstance().getFormattedCurrentTime()}, RequestContextUtils .getLocale(request))); } catch (Exception e){ logger.error("", e); errorMessages.add(messageSource.getMessage(GENERAL_ERROR, new Object[] {null, ControllerUtils.getInstance().getFormattedCurrentTime()}, RequestContextUtils .getLocale(request))); } logger.debug("handleGet - END"); return projectTeam; } /*/* (non-Javadoc) * @see ro.cs.om.web.controller.root.RootSimpleFormController#referenceData(javax.servlet.http.HttpServletRequest, java.lang.Object, org.springframework.validation.Errors) */ @SuppressWarnings("unchecked") protected Map referenceData(HttpServletRequest request, Object command, Errors errors) throws Exception { logger.debug("referenceData - START"); //used as a container for error messages ArrayList<String> errorMessages = new ArrayList<String>(); Map map = new HashMap(); // the command class ProjectProjectTeam projectProjectTeam = (ProjectProjectTeam) command; // put the projectId attribute on request Integer projectId = (Integer)request.getAttribute(PROJECT_ID); request.setAttribute(PROJECT_ID, projectId); // adding to model the action from the request String action = ServletRequestUtils.getStringParameter(request, IConstant.REQ_ACTION); map.put(IConstant.REQ_ACTION, action); // put the back url String backUrl = ServletRequestUtils.getStringParameter(request, BACK_URL); String servletPath = request.getServletPath(); String nextBackUrl = URLEncoder.encode(servletPath.substring(1, servletPath.length()).concat("?").concat(request.getQueryString()), "UTF-8"); map.put(BACK_URL, backUrl); map.put(NEXT_BACK_URL, nextBackUrl); map.put(ENCODE_BACK_URL, URLEncoder.encode(backUrl, "UTF-8")); // the id of the organization Integer organizationId = (Integer)request.getSession().getAttribute(IConstant.SESS_ORGANISATION_ID); map.put(ORGANIZATION_ID, organizationId); UserAuth userAuth = (UserAuth) SecurityContextHolder.getContext().getAuthentication().getPrincipal(); map.put(USER_ID, userAuth.getPersonId()); // if we have the permission to see all the projects by different managers // choose for a project manager for the project if(userAuth.hasAuthority(PermissionConstant.getInstance().getCM_ProjectAdvancedAdd())){ // list the persons for the organization that is project manager List<UserSimple> usersPM = new ArrayList<UserSimple>(); try{ usersPM = BLUser.getInstance().getUsersSimpleByOrganizationId(organizationId, true); } catch (BusinessException be) { logger.error("", be); errorMessages.add(messageSource.getMessage(GET_PERSONS_FROM_ORG_ERROR, new Object[] {be.getCode(), ControllerUtils.getInstance().getFormattedCurrentTime()}, RequestContextUtils .getLocale(request))); } catch (Exception e){ logger.error("", e); errorMessages.add(messageSource.getMessage(GENERAL_ERROR, new Object[] {null, ControllerUtils.getInstance().getFormattedCurrentTime()}, RequestContextUtils .getLocale(request))); } map.put(JSON_PERSONS, ControllerUtils.getInstance(). getPersonsFirstNameLastNameFromOrgAsJSON(usersPM, RequestContextUtils.getLocale(request), errorMessages, messageSource)); } else { if(projectProjectTeam.getProject().getProjectId() <= 0) { projectProjectTeam.getProject().setManagerId(userAuth.getPersonId()); projectProjectTeam.getProject().setManager(BLPerson.getInstance().get(userAuth.getPersonId())); } } // manager name logger.debug("manager name"); if(projectProjectTeam.getProject().getManagerId() != null) { logger.debug("project.getManagerId()" + projectProjectTeam.getProject().getManagerId()); Person manager = projectProjectTeam.getProject().getManager(); logger.debug("manager = " + manager); if(manager != null && manager.getPersonId() > 0) { map.put(MODEL_MANAGER_NAME, manager.getFirstName().concat(" ").concat(manager.getLastName())); } } // get the clients for the certain organization List<Client> clients = new ArrayList<Client>(); try{ clients = BLClient.getInstance().getClientsByOrganizationId(organizationId); } catch (BusinessException be) { logger.error("", be); errorMessages.add(messageSource.getMessage(GET_CLIENTS_FROM_ORG_ERROR, new Object[] {be.getCode(), ControllerUtils.getInstance().getFormattedCurrentTime()}, RequestContextUtils .getLocale(request))); } catch (Exception e){ logger.error("", e); errorMessages.add(messageSource.getMessage(GENERAL_ERROR, new Object[] {null, ControllerUtils.getInstance().getFormattedCurrentTime()}, RequestContextUtils .getLocale(request))); } map.put(JSON_CLIENTS, ControllerUtils.getInstance(). getClientsFromOrgAsJSON(clients, RequestContextUtils.getLocale(request), errorMessages, messageSource, false)); // client name logger.debug("client name"); Integer clientId = projectProjectTeam.getProject().getClientId(); logger.debug("clientId = " + clientId); if(clientId != null){ if(clientId > 0) { logger.debug("project.getClientId() = " + projectProjectTeam.getProject().getClientId()); Client client = new Client(); try{ client = BLClient.getInstance().get(projectProjectTeam.getProject().getClientId()); } catch (BusinessException be) { logger.error("", be); errorMessages.add(messageSource.getMessage(GET_CLIENT_ERROR, new Object[] {be.getCode(), ControllerUtils.getInstance().getFormattedCurrentTime()}, RequestContextUtils .getLocale(request))); } catch (Exception e){ logger.error("", e); errorMessages.add(messageSource.getMessage(GENERAL_ERROR, new Object[] {null, ControllerUtils.getInstance().getFormattedCurrentTime()}, RequestContextUtils .getLocale(request))); } logger.debug("client = " + client); if(client != null && client.getClientId() > 0) { if(client.getType() == IConstant.NOM_CLIENT_TYPE_FIRM) { map.put(MODEL_CLIENT_NAME, client.getC_name()); } else { map.put(MODEL_CLIENT_NAME, client.getP_firstName().concat(" ").concat(client.getP_lastName())); } } } } //Adding to model the status of the issue map.put(STATUS, projectProjectTeam.getProject().getStatus()); // list with all the persons from the organization List<UserSimple> users = new ArrayList<UserSimple>(); try { users = BLUser.getInstance().getUsersSimpleByOrganizationId(organizationId, true); } catch (BusinessException be) { logger.error("", be); errorMessages.add(messageSource.getMessage(GET_PERSONS_FROM_ORG_ERROR, new Object[] {be.getCode(), ControllerUtils.getInstance().getFormattedCurrentTime()}, RequestContextUtils .getLocale(request))); } catch (Exception e){ logger.error("", e); errorMessages.add(messageSource.getMessage(GENERAL_ERROR, new Object[] {null, ControllerUtils.getInstance().getFormattedCurrentTime()}, RequestContextUtils .getLocale(request))); } logger.debug("users by organizationId = " + users); projectId = projectProjectTeam.getProjectTeam().getProjectId(); logger.debug("projectTeam projectId = " + projectId); if(projectId != null) { Project project = BLProject.getInstance().getWithManger(projectId); map.put(CLIENT_ID, project.getClientId()); // adding to model the id of the manager of the project map.put(PROJECT_TEAM_MANAGERID, project.getManagerId()) ; List<UserSimple> newUsers = new ArrayList<UserSimple>(); for(TeamMember member : projectProjectTeam.getProjectTeam().getTeamMembers()) { if(member.getStatus() != IConstant.NOM_TEAM_MEMBER_STATUS_DELETED) { UserSimple userSimple = new UserSimple(); userSimple.setUserId(member.getPersonId()); newUsers.add(userSimple); } } users.removeAll(newUsers); logger.debug("newUsers = " + newUsers); logger.debug("users = " + users); map.put(STATUS_PROJECT_TEAM, projectProjectTeam.getProjectTeam().getStatus()); } else { map.put(PROJECT_TEAM_MANAGERID, new Integer(0)); map.put(STATUS_PROJECT_TEAM, new Integer(1)); } if(users != null) { map.put(ALL_PERSONS, users); } else { map.put(ALL_PERSONS, new HashSet<Person>()); } setErrors(request, errorMessages); logger.debug("referenceData - END"); return map; } }
agpl-3.0
ua-eas/ua-kfs-5.3
work/src/org/kuali/kfs/module/purap/document/validation/PurchasingAccountsPayableItemPreCalculationRule.java
1538
/* * The Kuali Financial System, a comprehensive financial management system for higher education. * * Copyright 2005-2014 The Kuali Foundation * * 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.kuali.kfs.module.purap.document.validation; import org.kuali.kfs.module.purap.businessobject.PurApItem; /** * Continue Purap Rule Interface * Defines a rule which gets invoked immediately before continuing to the next step during creation of a Transactional document. */ public interface PurchasingAccountsPayableItemPreCalculationRule { /** * Checks the rules that says percent must be 100% or * item total should be equal to the amount of accounts for that item. * * @param item the item to check * @return true if the business rules pass */ public boolean checkPercentOrTotalAmountsEqual(PurApItem item); }
agpl-3.0
EhsanTang/ApiManager
api/src/main/java/cn/crap/utils/SafetyUtil.java
710
package cn.crap.utils; import cn.crap.enu.MyError; import cn.crap.framework.MyException; /** * 安全校验代码 * * @author Ehsan * @date 2018/6/30 14:42 */ public class SafetyUtil { private static final String illegalWord = "'|exec|insert|delete|update|*|master|truncate|declare|;|,"; private static final String[] illegalWords = illegalWord.split("\\|"); public static void checkSqlParam(String param) throws MyException{ if (param == null) { return; } for (String str : illegalWords){ if (param.indexOf(str) >= 0){ throw new MyException(MyError.E000070, "参数包含非法字符:" + str); } } } }
agpl-3.0
JanMarvin/rstudio
src/gwt/src/org/rstudio/studio/client/panmirror/PanmirrorWidget.java
24358
/* * PanmirrorEditorWidget.java * * Copyright (C) 2020 by RStudio, PBC * * Unless you have received this program directly from RStudio pursuant * to the terms of a commercial license agreement with RStudio, then * 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.panmirror; import java.util.ArrayList; import java.util.List; import org.rstudio.core.client.CommandWithArg; import org.rstudio.core.client.DebouncedCommand; import org.rstudio.core.client.ExternalJavaScriptLoader; import org.rstudio.core.client.HandlerRegistrations; import org.rstudio.core.client.events.MouseDragHandler; import org.rstudio.core.client.jsinterop.JsVoidFunction; import org.rstudio.core.client.promise.PromiseWithProgress; import org.rstudio.core.client.theme.res.ThemeResources; import org.rstudio.core.client.widget.DockPanelSidebarDragHandler; import org.rstudio.core.client.widget.HasFindReplace; import org.rstudio.core.client.widget.IsHideableWidget; import org.rstudio.studio.client.RStudioGinjector; import org.rstudio.studio.client.application.events.ChangeFontSizeEvent; import org.rstudio.studio.client.application.events.EventBus; import org.rstudio.studio.client.palette.model.CommandPaletteEntrySource; import org.rstudio.studio.client.palette.model.CommandPaletteItem; import org.rstudio.studio.client.panmirror.command.PanmirrorMenuItem; import org.rstudio.studio.client.panmirror.command.PanmirrorToolbar; import org.rstudio.studio.client.panmirror.command.PanmirrorToolbarCommands; import org.rstudio.studio.client.panmirror.command.PanmirrorToolbarMenu; import org.rstudio.studio.client.panmirror.events.PanmirrorOutlineNavigationEvent; import org.rstudio.studio.client.panmirror.events.PanmirrorOutlineVisibleEvent; import org.rstudio.studio.client.panmirror.events.PanmirrorBlurEvent; import org.rstudio.studio.client.panmirror.events.PanmirrorFindReplaceVisibleEvent; import org.rstudio.studio.client.panmirror.events.PanmirrorFindReplaceVisibleEvent.Handler; import org.rstudio.studio.client.panmirror.events.PanmirrorOutlineWidthEvent; import org.rstudio.studio.client.panmirror.events.PanmirrorStateChangeEvent; import org.rstudio.studio.client.panmirror.events.PanmirrorUpdatedEvent; import org.rstudio.studio.client.panmirror.events.PanmirrorNavigationEvent; import org.rstudio.studio.client.panmirror.events.PanmirrorFocusEvent; import org.rstudio.studio.client.panmirror.findreplace.PanmirrorFindReplace; import org.rstudio.studio.client.panmirror.findreplace.PanmirrorFindReplaceWidget; import org.rstudio.studio.client.panmirror.format.PanmirrorFormat; import org.rstudio.studio.client.panmirror.location.PanmirrorEditingLocation; import org.rstudio.studio.client.panmirror.location.PanmirrorEditingOutlineLocation; import org.rstudio.studio.client.panmirror.outline.PanmirrorOutlineItem; import org.rstudio.studio.client.panmirror.outline.PanmirrorOutlineWidget; import org.rstudio.studio.client.panmirror.pandoc.PanmirrorPandocFormat; import org.rstudio.studio.client.panmirror.spelling.PanmirrorSpellingDoc; import org.rstudio.studio.client.panmirror.theme.PanmirrorTheme; import org.rstudio.studio.client.panmirror.theme.PanmirrorThemeCreator; import org.rstudio.studio.client.panmirror.uitools.PanmirrorPandocFormatConfig; import org.rstudio.studio.client.panmirror.uitools.PanmirrorUITools; import org.rstudio.studio.client.panmirror.uitools.PanmirrorUIToolsFormat; import org.rstudio.studio.client.workbench.prefs.model.UserPrefs; import org.rstudio.studio.client.workbench.prefs.model.UserState; import org.rstudio.studio.client.workbench.views.source.editors.text.events.EditorThemeChangedEvent; import org.rstudio.studio.client.workbench.views.source.editors.text.themes.AceTheme; import com.google.gwt.dom.client.Style; import com.google.gwt.event.shared.GwtEvent; import com.google.gwt.event.shared.HandlerManager; import com.google.gwt.event.shared.HandlerRegistration; import com.google.gwt.layout.client.Layout.AnimationCallback; import com.google.gwt.layout.client.Layout.Layer; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.ui.DockLayoutPanel; import com.google.gwt.user.client.ui.HTML; import com.google.gwt.user.client.ui.RequiresResize; import com.google.gwt.user.client.ui.PopupPanel.PositionCallback; import com.google.inject.Inject; import elemental2.core.JsObject; import elemental2.promise.Promise; import elemental2.promise.Promise.PromiseExecutorCallbackFn.RejectCallbackFn; import elemental2.promise.Promise.PromiseExecutorCallbackFn.ResolveCallbackFn; import jsinterop.annotations.JsOverlay; import jsinterop.annotations.JsPackage; import jsinterop.annotations.JsType; import jsinterop.base.Js; public class PanmirrorWidget extends DockLayoutPanel implements IsHideableWidget, RequiresResize, CommandPaletteEntrySource, PanmirrorUpdatedEvent.HasPanmirrorUpdatedHandlers, PanmirrorStateChangeEvent.HasPanmirrorStateChangeHandlers, PanmirrorOutlineVisibleEvent.HasPanmirrorOutlineVisibleHandlers, PanmirrorOutlineWidthEvent.HasPanmirrorOutlineWidthHandlers, PanmirrorFindReplaceVisibleEvent.HasPanmirrorFindReplaceVisibleHandlers, PanmirrorNavigationEvent.HasPanmirrorNavigationHandlers, PanmirrorBlurEvent.HasPanmirrorBlurHandlers, PanmirrorFocusEvent.HasPanmirrorFocusHandlers { public static class Options { public boolean toolbar = true; public boolean outline = false; public double outlineWidth = 190; public boolean border = false; } public static interface FormatSource { PanmirrorFormat getFormat(PanmirrorUIToolsFormat formatTools); } public static void create(PanmirrorContext context, FormatSource formatSource, PanmirrorOptions options, Options widgetOptions, int progressDelay, CommandWithArg<PanmirrorWidget> completed) { PanmirrorWidget editorWidget = new PanmirrorWidget(widgetOptions); Panmirror.load(() -> { // get format (now that we have uiTools available) PanmirrorFormat format = formatSource.getFormat(new PanmirrorUITools().format); // create the editor new PromiseWithProgress<PanmirrorEditor>( PanmirrorEditor.create(editorWidget.editorParent_.getElement(), context, format, options), null, progressDelay, editor -> { editorWidget.attachEditor(editor); completed.execute(editorWidget); } ); }); } private PanmirrorWidget(Options options) { super(Style.Unit.PX); setSize("100%", "100%"); // styles if (options.border) this.addStyleName(ThemeResources.INSTANCE.themeStyles().borderedIFrame()); // toolbar toolbar_ = new PanmirrorToolbar(); addNorth(toolbar_, toolbar_.getHeight()); setWidgetHidden(toolbar_, !options.toolbar); // find replace findReplace_ = new PanmirrorFindReplaceWidget(new PanmirrorFindReplaceWidget.Container() { @Override public boolean isFindReplaceShowing() { return findReplaceShowing_; } @Override public void showFindReplace(boolean show) { findReplaceShowing_ = show; setWidgetHidden(findReplace_, !findReplaceShowing_); toolbar_.setFindReplaceLatched(findReplaceShowing_); PanmirrorFindReplaceVisibleEvent.fire(PanmirrorWidget.this, findReplaceShowing_); if (findReplaceShowing_) findReplace_.performFind(); else editor_.getFindReplace().clear(); } @Override public PanmirrorFindReplace getFindReplace() { return editor_.getFindReplace(); } }); addNorth(findReplace_, findReplace_.getHeight()); setWidgetHidden(findReplace_, true); // outline outline_ = new PanmirrorOutlineWidget(); addEast(outline_, options.outlineWidth); setWidgetSize(outline_, options.outline ? options.outlineWidth : 0); MouseDragHandler.addHandler( outline_.getResizer(), new DockPanelSidebarDragHandler(this, outline_) { @Override public void onResized(boolean visible) { // hide if we snapped to 0 width if (!visible) showOutline(false, 0); // notify editor for layout PanmirrorWidget.this.onResize(); } @Override public void onPreferredWidth(double width) { PanmirrorOutlineWidthEvent.fire(PanmirrorWidget.this, width); } @Override public void onPreferredVisibility(boolean visible) { PanmirrorOutlineVisibleEvent.fire(PanmirrorWidget.this, visible); } } ); RStudioGinjector.INSTANCE.injectMembers(this); // editor editorParent_ = new HTML(); add(editorParent_); } @Inject public void initialize(UserPrefs userPrefs, UserState userState, EventBus events) { userPrefs_ = userPrefs; userState_ = userState; events_ = events; } public boolean isEditorAttached() { return super.isAttached() && editor_ != null; } private void attachEditor(PanmirrorEditor editor) { editor_ = editor; // initialize css syncEditorTheme(); syncContentWidth(); commands_ = new PanmirrorToolbarCommands(editor.commands()); toolbar_.init(commands_, editor_.getMenus(), null); outline_.addPanmirrorOutlineNavigationHandler(new PanmirrorOutlineNavigationEvent.Handler() { @Override public void onPanmirrorOutlineNavigation(PanmirrorOutlineNavigationEvent event) { editor_.navigate(PanmirrorNavigationType.Id, event.getId(), true); } }); editorEventUnsubscribe_.add(editor_.subscribe(PanmirrorEvent.Update, (data) -> { fireEvent(new PanmirrorUpdatedEvent()); })); // don't update outline eagerly (wait for 500ms delay in typing) DebouncedCommand updateOutineOnIdle = new DebouncedCommand(500) { @Override protected void execute() { updateOutline(); } }; // don't sync ui eagerly (wait for 300ms delay in typing) DebouncedCommand syncUI = new DebouncedCommand(300) { @Override protected void execute() { if (editor_ != null) { // sync toolbar commands if (toolbar_ != null) toolbar_.sync(false); // sync outline selection outline_.updateSelection(editor_.getSelection()); } } }; editorEventUnsubscribe_.add(editor_.subscribe(PanmirrorEvent.StateChange, (data) -> { // sync ui (debounced) syncUI.nudge(); // fire to clients fireEvent(new PanmirrorStateChangeEvent()); })); editorEventUnsubscribe_.add(editor_.subscribe(PanmirrorEvent.OutlineChange, (data) -> { // sync outline updateOutineOnIdle.nudge(); })); editorEventUnsubscribe_.add(editor_.subscribe(PanmirrorEvent.Navigate, (data) -> { PanmirrorNavigation nav = Js.uncheckedCast(data); fireEvent(new PanmirrorNavigationEvent(nav)); })); editorEventUnsubscribe_.add(editor_.subscribe(PanmirrorEvent.Blur, (data) -> { fireEvent(new PanmirrorBlurEvent()); })); editorEventUnsubscribe_.add(editor_.subscribe(PanmirrorEvent.Focus, (data) -> { fireEvent(new PanmirrorFocusEvent()); })); registrations_.add(events_.addHandler(EditorThemeChangedEvent.TYPE, (EditorThemeChangedEvent event) -> { new Timer() { @Override public void run() { toolbar_.sync(true); syncEditorTheme(event.getTheme()); } }.schedule(500); })); registrations_.add(events_.addHandler(ChangeFontSizeEvent.TYPE, (event) -> { syncEditorTheme(); })); registrations_.add( userPrefs_.visualMarkdownEditingMaxContentWidth().addValueChangeHandler((event) -> { syncContentWidth(); })); registrations_.add( userPrefs_.visualMarkdownEditingFontSizePoints().addValueChangeHandler((event) -> { syncEditorTheme(); }) ); } public void destroy() { // detach registrations (outline events) registrations_.removeHandler(); if (editor_ != null) { // unsubscribe from editor events for (JsVoidFunction unsubscribe : editorEventUnsubscribe_) unsubscribe.call(); editorEventUnsubscribe_.clear(); // destroy editor editor_.destroy(); editor_ = null; } } public void setTitle(String title) { editor_.setTitle(title); } public String getTitle() { return editor_.getTitle(); } public void setMarkdown(String code, PanmirrorWriterOptions options, boolean emitUpdate, int progressDelay, CommandWithArg<JsObject> completed) { new PromiseWithProgress<JsObject>( editor_.setMarkdown(code, options, emitUpdate), null, progressDelay, completed ); } public void getMarkdown(PanmirrorWriterOptions options, int progressDelay, CommandWithArg<JsObject> completed) { new PromiseWithProgress<JsObject>( editor_.getMarkdown(options), null, progressDelay, completed ); } public void getCanonical(String code, PanmirrorWriterOptions options, int progressDelay, CommandWithArg<String> completed) { new PromiseWithProgress<String>( editor_.getCanonical(code, options), null, progressDelay, completed ); } public boolean isInitialDoc() { return editor_.isInitialDoc(); } public HasFindReplace getFindReplace() { return findReplace_; } public PanmirrorSpellingDoc getSpellingDoc() { return editor_.getSpellingDoc(); } public void spellingInvalidateAllWords() { if (editor_ != null) editor_.spellingInvalidateAllWords(); } public void spellingInvalidateWord(String word) { if (editor_ != null) editor_.spellingInvalidateWord(word); } public void showOutline(boolean show, double width) { showOutline(show, width, false); } public void showOutline(boolean show, double width, boolean animate) { // update outline if we are showing if (show) updateOutline(); boolean visible = getWidgetSize(outline_) > 0; if (show != visible) { setWidgetSize(outline_, show ? width : 0); outline_.setAriaVisible(show); if (animate) { int duration = (userPrefs_.reducedMotion().getValue() ? 0 : 500); animate(duration, new AnimationCallback() { @Override public void onAnimationComplete() { resizeEditor(); } @Override public void onLayout(Layer layer, double progress) { resizeEditor(); } }); } else { forceLayout(); resizeEditor(); } } } public void showToolbar(boolean show) { setWidgetHidden(toolbar_, !show); } public void insertChunk(String chunkPlaceholder, int rowOffset, int colOffset) { editor_.insertChunk(chunkPlaceholder, rowOffset, colOffset); } public boolean execCommand(String id) { return commands_.exec(id); } public void navigate(String type, String location, boolean recordCurrent) { // perform navigation editor_.navigate(type, location, recordCurrent); } public void setKeybindings(PanmirrorKeybindings keybindings) { editor_.setKeybindings(keybindings); commands_ = new PanmirrorToolbarCommands(editor_.commands()); toolbar_.init(commands_, editor_.getMenus(), null); } public String getHTML() { return editor_.getHTML(); } public PanmirrorFormat getEditorFormat() { return editor_.getEditorFormat(); } public PanmirrorPandocFormat getPandocFormat() { return editor_.getPandocFormat(); } public PanmirrorPandocFormatConfig getPandocFormatConfig(boolean isRmd) { return editor_.getPandocFormatConfig(isRmd); } public String getSelectedText() { return editor_.getSelectedText(); } public void replaceSelection(String value) { editor_.replaceSelection(value); } public PanmirrorSelection getSelection() { return editor_.getSelection(); } public PanmirrorEditingLocation getEditingLocation() { return editor_.getEditingLocation(); } public PanmirrorEditingOutlineLocation getEditingOutlineLocation() { return editor_.getEditingOutlineLocation(); } public PanmirrorOutlineItem[] getOutline() { return editor_.getOutline(); } public void setEditingLocation( PanmirrorEditingOutlineLocation outlineLocation, PanmirrorEditingLocation previousLocation) { editor_.setEditingLocation(outlineLocation, previousLocation); } public void focus() { editor_.focus(); } public void blur() { editor_.blur(); } public Promise<Boolean> showContextMenu(PanmirrorMenuItem[] items, int clientX, int clientY) { return new Promise<Boolean>((ResolveCallbackFn<Boolean> resolve, RejectCallbackFn reject) -> { final PanmirrorToolbarMenu menu = new PanmirrorToolbarMenu(commands_); menu.addCloseHandler((event) -> { resolve.onInvoke(true); }); menu.addItems(items); menu.setPopupPositionAndShow(new PositionCallback() { @Override public void setPosition(int offsetWidth, int offsetHeight) { menu.setPopupPosition(clientX, clientY); } }); }); } public String getYamlFrontMatter() { return editor_.getYamlFrontMatter(); } public void applyYamlFrontMatter(String yaml) { editor_.applyYamlFrontMatter(yaml); } public void activateDevTools() { ProseMirrorDevTools.load(() -> { editor_.enableDevTools(ProseMirrorDevTools.applyDevTools); }); } public boolean devToolsLoaded() { return ProseMirrorDevTools.isLoaded(); } @Override public HandlerRegistration addPanmirrorUpdatedHandler(PanmirrorUpdatedEvent.Handler handler) { return handlers_.addHandler(PanmirrorUpdatedEvent.getType(), handler); } @Override public HandlerRegistration addPanmirrorStateChangeHandler(PanmirrorStateChangeEvent.Handler handler) { return handlers_.addHandler(PanmirrorStateChangeEvent.getType(), handler); } @Override public HandlerRegistration addPanmirrorOutlineWidthHandler(PanmirrorOutlineWidthEvent.Handler handler) { return handlers_.addHandler(PanmirrorOutlineWidthEvent.getType(), handler); } @Override public HandlerRegistration addPanmirrorOutlineVisibleHandler(PanmirrorOutlineVisibleEvent.Handler handler) { return handlers_.addHandler(PanmirrorOutlineVisibleEvent.getType(), handler); } @Override public HandlerRegistration addPanmirrorFindReplaceVisibleHandler(Handler handler) { return handlers_.addHandler(PanmirrorFindReplaceVisibleEvent.getType(), handler); } @Override public HandlerRegistration addPanmirrorNavigationHandler(PanmirrorNavigationEvent.Handler handler) { return handlers_.addHandler(PanmirrorNavigationEvent.getType(), handler); } @Override public HandlerRegistration addPanmirrorBlurHandler(org.rstudio.studio.client.panmirror.events.PanmirrorBlurEvent.Handler handler) { return handlers_.addHandler(PanmirrorBlurEvent.getType(), handler); } @Override public HandlerRegistration addPanmirrorFocusHandler(org.rstudio.studio.client.panmirror.events.PanmirrorFocusEvent.Handler handler) { return handlers_.addHandler(PanmirrorFocusEvent.getType(), handler); } @Override public void fireEvent(GwtEvent<?> event) { handlers_.fireEvent(event); } @Override public void onResize() { if (toolbar_ != null) { toolbar_.onResize(); } if (findReplace_ != null) { findReplace_.onResize(); } if (editor_ != null) { resizeEditor(); } } @Override public List<CommandPaletteItem> getCommandPaletteItems() { return commands_.getCommandPaletteItems(); } private void updateOutline() { if (editor_ != null) // would be null during teardown of tab { PanmirrorOutlineItem[] outline = editor_.getOutline(); outline_.updateOutline(outline); outline_.updateSelection(editor_.getSelection()); } } private void resizeEditor() { editor_.resize(); } private void syncEditorTheme() { syncEditorTheme(userState_.theme().getGlobalValue().cast()); } private void syncEditorTheme(AceTheme theme) { PanmirrorTheme panmirrorTheme = PanmirrorThemeCreator.themeFromEditorTheme(theme, userPrefs_); editor_.applyTheme(panmirrorTheme);; } private void syncContentWidth() { int contentWidth = userPrefs_.visualMarkdownEditingMaxContentWidth().getValue(); editor_.setMaxContentWidth(contentWidth, 20); } private UserPrefs userPrefs_ = null; private UserState userState_ = null; private EventBus events_ = null; private PanmirrorToolbar toolbar_ = null; private boolean findReplaceShowing_ = false; private PanmirrorFindReplaceWidget findReplace_ = null; private PanmirrorOutlineWidget outline_ = null; private HTML editorParent_ = null; private PanmirrorEditor editor_ = null; private PanmirrorToolbarCommands commands_ = null; private final HandlerManager handlers_ = new HandlerManager(this); private final HandlerRegistrations registrations_ = new HandlerRegistrations(); private final ArrayList<JsVoidFunction> editorEventUnsubscribe_ = new ArrayList<JsVoidFunction>(); } @JsType(isNative = true, namespace = JsPackage.GLOBAL) class ProseMirrorDevTools { @JsOverlay public static void load(ExternalJavaScriptLoader.Callback onLoaded) { devtoolsLoader_.addCallback(onLoaded); } @JsOverlay public static boolean isLoaded() { return devtoolsLoader_.isLoaded(); } public static JsObject applyDevTools; @JsOverlay private static final ExternalJavaScriptLoader devtoolsLoader_ = new ExternalJavaScriptLoader("js/panmirror/prosemirror-dev-tools.min.js"); }
agpl-3.0
joshzamor/open-lmis
modules/distribution/src/main/java/org/openlmis/distribution/serializer/StatusDeSerializer.java
1664
/* * This program is part of the OpenLMIS logistics management information system platform software. * Copyright © 2013 VillageReach * * 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. For additional information contact info@OpenLMIS.org. */ package org.openlmis.distribution.serializer; import org.codehaus.jackson.JsonNode; import org.codehaus.jackson.JsonParser; import org.codehaus.jackson.ObjectCodec; import org.codehaus.jackson.map.DeserializationContext; import org.codehaus.jackson.map.JsonDeserializer; import org.openlmis.distribution.domain.DistributionStatus; import java.io.IOException; /** * StatusDeSerializer class represents the deserializer for DistributionStatus. */ public class StatusDeSerializer extends JsonDeserializer<DistributionStatus> { @Override public DistributionStatus deserialize(JsonParser jsonParser, DeserializationContext ctxt) throws IOException { ObjectCodec oc = jsonParser.getCodec(); JsonNode node = oc.readTree(jsonParser); return DistributionStatus.valueOf(node.get("name").getTextValue()); } }
agpl-3.0
GrowthcraftCE/Growthcraft-1.11
src/main/java/growthcraft/bees/api/BeesRegistry.java
6135
package growthcraft.bees.api; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Nonnull; import javax.annotation.Nullable; import growthcraft.bees.GrowthcraftBees; import growthcraft.core.api.item.ItemKey; import growthcraft.core.api.utils.BlockKey; import net.minecraft.block.Block; import net.minecraft.block.state.IBlockState; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; public class BeesRegistry { private static final BeesRegistry INSTANCE = new BeesRegistry(); private final List<ItemKey> beesList = new ArrayList<ItemKey>(); private final Map<ItemKey, ItemStack> emptyToFullHoneyComb = new HashMap<ItemKey, ItemStack>(); private final Map<ItemKey, ItemStack> fullToEmptyHoneyComb = new HashMap<ItemKey, ItemStack>(); private final Map<BlockKey, IFlowerBlockEntry> flowerEntries = new HashMap<BlockKey, IFlowerBlockEntry>(); public static final BeesRegistry instance() { return INSTANCE; } private ItemKey stackToKey(@Nonnull ItemStack itemstack) { return new ItemKey(itemstack); } /////////////////////////////////////////////////////////////////////// // BEES /////////////////////////////////////////////////////////////// /////////////////////////////////////////////////////////////////////// /** * addBee() * Adds a custom bee the mod. * NOTE: This is not meta-sensitive. * * @param bee - The Item/Block to be registered. */ public void addBee(@Nonnull Item bee, int meta) { GrowthcraftBees.logger.debug("Adding Bee {%s}:%d", bee, meta); beesList.add(new ItemKey(bee, meta)); } public void addBee(@Nonnull Block bee, int meta) { addBee(Item.getItemFromBlock(bee), meta); } public void addBee(@Nonnull IBlockState beeState) { Block block = beeState.getBlock(); addBee(Item.getItemFromBlock(block), block.getMetaFromState(beeState)); } public void addBee(@Nonnull ItemStack stack) { final ItemKey key = stackToKey(stack); GrowthcraftBees.logger.debug("Adding Bee {%s}", key); beesList.add(key); } public void addBee(@Nonnull Item bee) { addBee(bee, ItemKey.WILDCARD_VALUE); } public void addBee(@Nonnull Block bee) { addBee(Item.getItemFromBlock(bee), ItemKey.WILDCARD_VALUE); } protected void addHoneyCombMapping(@Nonnull ItemStack empty, @Nonnull ItemStack full) { GrowthcraftBees.logger.debug("Adding Honey Comb mapping {%s} - {%s}", empty, full); emptyToFullHoneyComb.put(stackToKey(empty), full); fullToEmptyHoneyComb.put(stackToKey(full), empty); } public void addHoneyComb(@Nonnull ItemStack empty, @Nonnull ItemStack full) { addHoneyCombMapping(empty, full); } public ItemStack getFilledHoneyComb(@Nonnull ItemStack itemstack) { return emptyToFullHoneyComb.get(stackToKey(itemstack)); } public ItemStack getEmptyHoneyComb(@Nonnull ItemStack itemstack) { return fullToEmptyHoneyComb.get(stackToKey(itemstack)); } protected boolean isItemFilledHoneyComb(@Nonnull ItemKey key) { return fullToEmptyHoneyComb.containsKey(key); } public boolean isItemFilledHoneyComb(@Nonnull ItemStack itemstack) { return isItemFilledHoneyComb(stackToKey(itemstack)); } protected boolean isItemEmptyHoneyComb(@Nonnull ItemKey key) { return emptyToFullHoneyComb.containsKey(key); } public boolean isItemEmptyHoneyComb(@Nonnull ItemStack itemstack) { return isItemEmptyHoneyComb(stackToKey(itemstack)); } public boolean isItemHoneyComb(@Nonnull ItemStack itemstack) { final ItemKey key = stackToKey(itemstack); return isItemFilledHoneyComb(key) || isItemEmptyHoneyComb(key); } public void addFlower(@Nonnull BlockKey key, @Nonnull IFlowerBlockEntry entry) { GrowthcraftBees.logger.debug("Adding Flower {%s}:{%s}", key, entry); flowerEntries.put(key, entry); } public void addFlower(@Nonnull IFlowerBlockEntry entry) { addFlower(new BlockKey(entry.getBlockState()), entry); } /** * Adds a custom flower the mod. * NOTE: This is meta-sensitive. * * @param flower - Block to be registered. * @param meta - Metadata of the block to be registered. */ public void addFlower(@Nonnull Block flower, int meta) { addFlower(new BlockKey(flower, meta), new GenericFlowerBlockEntry(flower, meta)); } /** * Flower wildcard * * @param flower - Block to be registered. */ public void addFlower(@Nonnull Block flower) { addFlower(flower, ItemKey.WILDCARD_VALUE); } /** * Adds a custom flower the mod. * NOTE: This is meta-sensitive. * * @param flower - Block to be registered. * @param meta - Metadata of the block to be registered. */ public void addFlower(@Nonnull IBlockState flower) { addFlower(new BlockKey(flower), new GenericFlowerBlockEntry(flower)); } /** * @param itemstack - an itemstack to check * @return Does the provided itemstack contain any known bees? */ public boolean isItemBee(@Nullable ItemStack itemstack) { if (itemstack == null) return false; final Item item = itemstack.getItem(); final int meta = itemstack.getItemDamage(); for (ItemKey key : beesList) { if (item == key.item) { if (key.meta == ItemKey.WILDCARD_VALUE || key.meta == meta) { return true; } } } return false; } public IFlowerBlockEntry getFlowerBlockEntry(@Nonnull BlockKey key) { return flowerEntries.get(key); } public IFlowerBlockEntry getFlowerBlockEntry(@Nullable Block block, int meta) { if (block == null) return null; final IFlowerBlockEntry entry = getFlowerBlockEntry(new BlockKey(block, meta)); if (entry != null) return entry; return getFlowerBlockEntry(new BlockKey(block, ItemKey.WILDCARD_VALUE)); } public IFlowerBlockEntry getFlowerBlockEntry(@Nullable IBlockState blockState) { if( blockState == null ) return null; Block block = blockState.getBlock(); return getFlowerBlockEntry(block, block.getMetaFromState(blockState)); } public boolean isBlockFlower(@Nullable IBlockState blockState) { return flowerEntries.containsKey(new BlockKey(blockState)) || flowerEntries.containsKey(new BlockKey(blockState.getBlock(), ItemKey.WILDCARD_VALUE)); } }
agpl-3.0
aborg0/rapidminer-studio
src/main/java/com/rapidminer/operator/annotation/PolynomialFunction.java
4278
/** * Copyright (C) 2001-2019 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.rapidminer.operator.annotation; import java.text.DecimalFormat; import java.text.NumberFormat; /** * Only highest order terms taken into account. Functions can be of the form * * c * log(n)^d1 * n^d2 * log(m)^*d3 * m^d4 * * * @author Simon Fischer */ public class PolynomialFunction { private double coefficient; private double degreeExamples; private double degreeAttributes; private double logDegreeExamples; private double logDegreeAttributes; public PolynomialFunction(double coefficient, double degreeExamples, double degreeAttributes) { this(coefficient, degreeExamples, 0, degreeAttributes, 0); } public PolynomialFunction(double coefficient, double degreeExamples, double logDegreeExamples, double degreeAttributes, double logDegreeAttributes) { super(); this.coefficient = coefficient; this.degreeAttributes = degreeAttributes; this.degreeExamples = degreeExamples; this.logDegreeAttributes = logDegreeAttributes; this.logDegreeExamples = logDegreeExamples; } public static PolynomialFunction makeLinearFunction(double coefficient) { return new PolynomialFunction(coefficient, 1, 1); } public long evaluate(int numExamples, int numAttributes) { return (long) (coefficient * Math.pow(numExamples, degreeExamples) * Math.pow(Math.log(numExamples), logDegreeExamples) * Math.pow(numAttributes, degreeAttributes) * Math.pow( Math.log(numAttributes), logDegreeAttributes)); } @Override public String toString() { // this is true for both 0.0 and -0.0 because primitive compare is defined that way if (coefficient == 0.0d) { return "n/a"; } NumberFormat formatter = new DecimalFormat("#.##"); StringBuffer resourceString = new StringBuffer(); resourceString.append("f() = "); resourceString.append(formatter.format(coefficient)); if (degreeExamples > 0 || degreeAttributes > 0) { resourceString.append(" * ("); } if (degreeExamples > 0) { if (logDegreeExamples > 0) { resourceString.append("log"); resourceString.append(formatter.format(logDegreeExamples)); if (degreeExamples > 1) { resourceString.append("(examples^"); resourceString.append(formatter.format(degreeExamples)); } else { resourceString.append("(examples"); } resourceString.append(')'); } else { if (degreeExamples > 1) { resourceString.append("examples^"); resourceString.append(formatter.format(degreeExamples)); } else { resourceString.append("examples"); } } if (degreeAttributes > 0) { resourceString.append(" * "); } } if (degreeAttributes > 0) { if (logDegreeAttributes > 0) { resourceString.append("log"); resourceString.append(formatter.format(logDegreeAttributes)); if (degreeAttributes > 1) { resourceString.append("(attributes^"); resourceString.append(formatter.format(degreeAttributes)); } else { resourceString.append("(attributes"); } resourceString.append(')'); } else { if (degreeAttributes > 1) { resourceString.append("attributes^"); resourceString.append(formatter.format(degreeAttributes)); } else { resourceString.append("attributes"); } } } if (degreeExamples > 0 || degreeAttributes > 0) { resourceString.append(')'); } return resourceString.toString(); } }
agpl-3.0
dice-group/LIMES
limes-core/src/test/java/org/aksw/limes/core/measures/measure/pointsets/sumofmin/NaiveSumOfMinTest.java
4004
/* * LIMES Core Library - LIMES – Link Discovery Framework for Metric Spaces. * Copyright © 2011 Data Science Group (DICE) (ngonga@uni-paderborn.de) * * 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.aksw.limes.core.measures.measure.pointsets.sumofmin; import org.aksw.limes.core.datastrutures.Point; import org.aksw.limes.core.measures.mapper.pointsets.Polygon; import org.junit.Test; import java.util.Arrays; import java.util.HashSet; import java.util.Set; /** * @author Mohamed Sherif (sherif@informatik.uni-leipzig.de) */ public class NaiveSumOfMinTest { @Test public void test() { // Malta in DBpedia Point maltaDbpediaP1 = new Point("MaltaDbpediaP1", Arrays.asList(new Double[]{14.4625, 35.8967})); Point maltaDbpediaP2 = new Point("MaltaDbpediaP2", Arrays.asList(new Double[]{14.4625, 35.8833})); Point maltaDbpediaP3 = new Point("MaltaDbpediaP3", Arrays.asList(new Double[]{14.5, 35.8833})); Point maltaDbpediaP4 = new Point("MaltaDbpediaP4", Arrays.asList(new Double[]{14.5, 35.8967})); Polygon maltaDbpediaPoly1 = new Polygon("maltaDbpediaPoly1", Arrays.asList(new Point[]{maltaDbpediaP1, maltaDbpediaP2, maltaDbpediaP3, maltaDbpediaP4})); Set<Polygon> maltaDbpedia = new HashSet<Polygon>(); maltaDbpedia.add(maltaDbpediaPoly1); // Malta in Nuts Point maltaNutsP1 = new Point("MaltaNutsP1", Arrays.asList(new Double[]{14.342771550000066, 35.931038250000043})); Point maltaNutsP2 = new Point("MaltaNutsP2", Arrays.asList(new Double[]{14.328761050000054, 35.990215250000048})); Point maltaNutsP3 = new Point("MaltaNutsP3", Arrays.asList(new Double[]{14.389599050000101, 35.957935750000019})); Point maltaNutsP4 = new Point("MaltaNutsP4", Arrays.asList(new Double[]{14.56211105, 35.819926750000036})); Point maltaNutsP5 = new Point("MaltaNutsP5", Arrays.asList(new Double[]{14.416516550000068, 35.828308250000049})); Point maltaNutsP6 = new Point("maltaNutsP6", Arrays.asList(new Double[]{14.212639050000092, 36.07996375})); Point maltaNutsP7 = new Point("maltaNutsP7", Arrays.asList(new Double[]{14.336017550000065, 36.032375750000057})); Point maltaNutsP8 = new Point("maltaNutsP8", Arrays.asList(new Double[]{14.218683050000095, 36.021091250000026})); Point maltaNutsP9 = new Point("maltaNutsP9", Arrays.asList(new Double[]{14.18619805000003, 36.036388750000029})); Polygon maltaNutsPoly1 = new Polygon("maltaNutsPoly1", Arrays.asList(new Point[]{maltaNutsP1, maltaNutsP2, maltaNutsP3, maltaNutsP4, maltaNutsP5, maltaNutsP6, maltaNutsP7, maltaNutsP8, maltaNutsP9})); Set<Polygon> maltaNuts = new HashSet<Polygon>(); maltaNuts.add(maltaNutsPoly1); // Malta in LGD Point maltaLgdP1 = new Point("maltaLgdP1", Arrays.asList(new Double[]{14.504285, 35.8953019})); Polygon maltaLgdPoly1 = new Polygon("maltaLgdPoly1", Arrays.asList(new Point[]{maltaLgdP1})); Set<Polygon> maltaLgd = new HashSet<Polygon>(); maltaLgd.add(maltaLgdPoly1); NaiveSumOfMinMeasure som = new NaiveSumOfMinMeasure(); System.out.println(som.run(maltaNuts, maltaDbpedia, Double.MAX_VALUE)); } }
agpl-3.0
razalhague/mairion
src/main/java/org/penny_craal/mairion/model/GoalType.java
222
package org.penny_craal.mairion.model; /** * Describes the different types of goals Mairion can handle. */ public enum GoalType { /** * @see ConsiderGoal */ consider, /** * @see MinimumGoal */ minimum, ; }
agpl-3.0
rosenpin/Gadgetbridge
app/src/main/java/nodomain/freeyourgadget/gadgetbridge/util/Prefs.java
6672
/* Copyright (C) 2016-2017 Carsten Pfeiffer, JohnnySun This file is part of Gadgetbridge. Gadgetbridge 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. Gadgetbridge 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 nodomain.freeyourgadget.gadgetbridge.util; import android.content.SharedPreferences; import android.util.Log; import java.util.HashSet; import java.util.Set; /** * Wraps SharedPreferences to avoid ClassCastExceptions and others. */ public class Prefs { private static final String TAG = "Prefs"; // DO NOT use slf4j logger here, this would break its configuration via GBApplication // private static final Logger LOG = LoggerFactory.getLogger(Prefs.class); private final SharedPreferences preferences; public Prefs(SharedPreferences preferences) { this.preferences = preferences; } public String getString(String key, String defaultValue) { String value = preferences.getString(key, defaultValue); if (value == null || "".equals(value)) { return defaultValue; } return value; } public Set<String> getStringSet(String key, Set<String> defaultValue) { Set<String> value = preferences.getStringSet(key, defaultValue); if (value == null || value.isEmpty()) { return defaultValue; } return value; } /** * Returns the preference saved under the given key as an integer value. * Note that it is irrelevant whether the preference value was actually * saved as an integer value or a string value. * @param key the preference key * @param defaultValue the default value to return if the preference value is unset * @return the saved preference value or the given defaultValue */ public int getInt(String key, int defaultValue) { try { return preferences.getInt(key, defaultValue); } catch (Exception ex) { try { String value = preferences.getString(key, String.valueOf(defaultValue)); if ("".equals(value)) { return defaultValue; } return Integer.parseInt(value); } catch (Exception ex2) { logReadError(key, ex); return defaultValue; } } } /** * Returns the preference saved under the given key as a long value. * Note that it is irrelevant whether the preference value was actually * saved as a long value or a string value. * @param key the preference key * @param defaultValue the default value to return if the preference value is unset * @return the saved preference value or the given defaultValue */ public long getLong(String key, long defaultValue) { try { return preferences.getLong(key, defaultValue); } catch (Exception ex) { try { String value = preferences.getString(key, String.valueOf(defaultValue)); if ("".equals(value)) { return defaultValue; } return Long.parseLong(value); } catch (Exception ex2) { logReadError(key, ex); return defaultValue; } } } /** * Returns the preference saved under the given key as a float value. * Note that it is irrelevant whether the preference value was actually * saved as a float value or a string value. * @param key the preference key * @param defaultValue the default value to return if the preference value is unset * @return the saved preference value or the given defaultValue */ public float getFloat(String key, float defaultValue) { try { return preferences.getFloat(key, defaultValue); } catch (Exception ex) { try { String value = preferences.getString(key, String.valueOf(defaultValue)); if ("".equals(value)) { return defaultValue; } return Float.parseFloat(value); } catch (Exception ex2) { logReadError(key, ex); return defaultValue; } } } /** * Returns the preference saved under the given key as a boolean value. * Note that it is irrelevant whether the preference value was actually * saved as a boolean value or a string value. * @param key the preference key * @param defaultValue the default value to return if the preference value is unset * @return the saved preference value or the given defaultValue */ public boolean getBoolean(String key, boolean defaultValue) { try { return preferences.getBoolean(key, defaultValue); } catch (Exception ex) { try { String value = preferences.getString(key, String.valueOf(defaultValue)); if ("".equals(value)) { return defaultValue; } return Boolean.parseBoolean(value); } catch (Exception ex2) { logReadError(key, ex); return defaultValue; } } } private void logReadError(String key, Exception ex) { Log.e(TAG, "Error reading preference value: " + key + "; returning default value", ex); // log the first exception } /** * Access to the underlying SharedPreferences, typically only used for editing values. * @return the underlying SharedPreferences object. */ public SharedPreferences getPreferences() { return preferences; } /** * Ugly workaround for Set<String> preferences not consistently applying. * @param editor * @param preference * @param value */ public static void putStringSet(SharedPreferences.Editor editor, String preference, HashSet<String> value) { editor.putStringSet(preference, null); editor.commit(); editor.putStringSet(preference, new HashSet<>(value)); } }
agpl-3.0
torakiki/sejda
sejda-core/src/test/java/org/sejda/core/service/AlternateMixTaskTest.java
6549
/* * Created on 25/dic/2010 * Copyright 2010 by Andrea Vacondio (andrea.vacondio@gmail.com). * * This file is part of the Sejda source code * * 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.sejda.core.service; import java.io.IOException; import org.junit.Ignore; import org.junit.Test; import org.sejda.model.input.PdfMixInput; import org.sejda.model.output.ExistingOutputPolicy; import org.sejda.model.parameter.AlternateMixMultipleInputParameters; import org.sejda.model.pdf.PdfVersion; import org.sejda.model.pdf.page.PageRange; import org.sejda.sambox.pdmodel.PDPage; import static org.sejda.TestUtils.encryptedAtRest; /** * Abstract test unit for the alternate mix task * * @author Andrea Vacondio * */ @Ignore public abstract class AlternateMixTaskTest extends BaseTaskTest<AlternateMixMultipleInputParameters> { private void setUpParameters(AlternateMixMultipleInputParameters parameters) { parameters.setExistingOutputPolicy(ExistingOutputPolicy.OVERWRITE); parameters.setCompress(true); parameters.setVersion(PdfVersion.VERSION_1_5); } @Test public void threeDocsMerge() throws IOException { AlternateMixMultipleInputParameters params = new AlternateMixMultipleInputParameters(); params.addInput(new PdfMixInput(shortInput(), true, 1)); params.addInput(new PdfMixInput(stronglyEncryptedInput(), true, 3)); params.addInput(new PdfMixInput(largeOutlineInput())); setUpParameters(params); testContext.pdfOutputTo(params); execute(params); testContext.assertTaskCompleted(); testContext.assertCreator().assertPages(13).assertVersion(PdfVersion.VERSION_1_5).forPdfOutput(d -> { assertHeaderContains(d.getPage(0), "Pagina 4 di 4"); assertHeaderContains(d.getPage(5), "Pagina 3 di 4"); assertHeaderContains(d.getPage(8), "Pagina 2 di 4"); assertHeaderContains(d.getPage(10), "Pagina 1 di 4"); }); } @Test public void threeDocsMergeWithPageSelection() throws IOException { AlternateMixMultipleInputParameters params = new AlternateMixMultipleInputParameters(); PdfMixInput first = new PdfMixInput(shortInput(), true, 1); first.addPageRange(new PageRange(1, 2)); params.addInput(first); PdfMixInput second = new PdfMixInput(stronglyEncryptedInput(), false, 2); params.addInput(second); PdfMixInput third = new PdfMixInput(largeInput(), false, 6); third.addPageRange(new PageRange(5, 10)); third.addPageRange(new PageRange(22, 23)); params.addInput(third); setUpParameters(params); testContext.pdfOutputTo(params); execute(params); testContext.assertTaskCompleted(); testContext.assertCreator().assertPages(14).assertVersion(PdfVersion.VERSION_1_5).forPdfOutput(d -> { assertHeaderContains(d.getPage(0), "Pagina 2 di 4"); assertHeaderContains(d.getPage(9), "Pagina 1 di 4"); }); } @Test public void withStandardInput() throws IOException { AlternateMixMultipleInputParameters parameters = new AlternateMixMultipleInputParameters(); parameters.addInput(new PdfMixInput(shortInput())); parameters.addInput(new PdfMixInput(shortInput(), true, 3)); setUpParameters(parameters); testContext.pdfOutputTo(parameters); execute(parameters); testContext.assertTaskCompleted(); testContext.assertCreator().assertPages(8).assertVersion(PdfVersion.VERSION_1_5); } @Test public void withEncryptedInput() throws IOException { AlternateMixMultipleInputParameters parameters = new AlternateMixMultipleInputParameters(); parameters.addInput(new PdfMixInput(encryptedInput())); parameters.addInput(new PdfMixInput(stronglyEncryptedInput(), true, 3)); setUpParameters(parameters); testContext.pdfOutputTo(parameters); execute(parameters); testContext.assertTaskCompleted(); testContext.assertCreator().assertPages(8).assertVersion(PdfVersion.VERSION_1_5); } @Test public void atRestEncryptionTest() throws IOException { AlternateMixMultipleInputParameters params = new AlternateMixMultipleInputParameters(); params.addInput(new PdfMixInput(encryptedAtRest(shortInput()))); params.addInput(new PdfMixInput(encryptedAtRest(stronglyEncryptedInput()))); setUpParameters(params); testContext.pdfOutputTo(params); execute(params); testContext.assertTaskCompleted(); testContext.assertPages(8); } @Test public void repeatForeverExplicitlyMarkedInputs() throws IOException { AlternateMixMultipleInputParameters params = new AlternateMixMultipleInputParameters(); params.addInput(new PdfMixInput(shortInput())); params.addInput(new PdfMixInput(customInput("pdf/one_page.pdf"))); for(PdfMixInput input :params.getInputList()) { input.setRepeatForever(true); } setUpParameters(params); testContext.pdfOutputTo(params); execute(params); testContext.assertTaskCompleted(); testContext.assertPages(8).forPdfOutput(d -> { assertHeaderContains(d.getPage(0), "Pagina 1 di 4"); assertPageTextContains(d.getPage(1), "First page"); assertHeaderContains(d.getPage(2), "Pagina 2 di 4"); assertPageTextContains(d.getPage(3), "First page"); assertHeaderContains(d.getPage(4), "Pagina 3 di 4"); assertPageTextContains(d.getPage(5), "First page"); assertHeaderContains(d.getPage(6), "Pagina 4 di 4"); assertPageTextContains(d.getPage(7), "First page"); }); } protected abstract void assertHeaderContains(PDPage page, String expectedText); }
agpl-3.0
MinecraftCloudSystem/MCS-Daemon
src/main/java/net/mcsproject/daemon/utils/Logging.java
1296
/* * MCS - Minecraft Cloud System * Copyright (C) 2016 * * 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 net.mcsproject.daemon.utils; import org.apache.logging.log4j.Level; import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.core.LoggerContext; import org.apache.logging.log4j.core.config.Configuration; public class Logging { public static void enableDebug() { LoggerContext ctx = (LoggerContext) LogManager.getContext(false); Configuration conf = ctx.getConfiguration(); conf.getLoggerConfig(LogManager.ROOT_LOGGER_NAME).setLevel(Level.DEBUG); ctx.updateLoggers(conf); } }
agpl-3.0
shenan4321/BIMplatform
generated/cn/dlb/bim/models/ifc4/IfcAdvancedFace.java
1065
/** * 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; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Ifc Advanced Face</b></em>'. * <!-- end-user-doc --> * * * @see cn.dlb.bim.models.ifc4.Ifc4Package#getIfcAdvancedFace() * @model * @generated */ public interface IfcAdvancedFace extends IfcFaceSurface { } // IfcAdvancedFace
agpl-3.0
malikov/platform-android
ushahidi/src/test/java/com/ushahidi/android/data/repository/DeploymentDataRepositoryTest.java
5500
package com.ushahidi.android.data.repository; import com.ushahidi.android.data.BaseTestCase; import com.ushahidi.android.data.entity.DeploymentEntity; import com.ushahidi.android.data.entity.mapper.DeploymentEntityDataMapper; import com.ushahidi.android.data.repository.datasource.deployment.DeploymentDataSource; import com.ushahidi.android.data.repository.datasource.deployment.DeploymentDataSourceFactory; import com.ushahidi.android.domain.entity.Deployment; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; import org.mockito.Mock; import org.mockito.MockitoAnnotations; import java.util.ArrayList; import java.util.List; import rx.Observable; import static org.mockito.BDDMockito.given; import static org.mockito.Mockito.verify; /** * Test suite for {@link DeploymentDataRepository} * * @author Ushahidi Team <team@ushahidi.com> */ public class DeploymentDataRepositoryTest extends BaseTestCase { @Rule public ExpectedException expectedException = ExpectedException.none(); private DeploymentDataRepository mDeploymentDataRepository; @Mock private DeploymentDataSourceFactory mMockDeploymentDataSourceFactory; @Mock private DeploymentEntityDataMapper mMockDeploymentEntityMapper; @Mock private DeploymentDataSource mMockDataSource; @Mock private Deployment mMockDeployment; @Mock private DeploymentEntity mMockDeploymentEntity; @Before public void setUp() throws Exception { MockitoAnnotations.initMocks(this); clearSingleton(DeploymentDataRepository.class); mDeploymentDataRepository = new DeploymentDataRepository(mMockDeploymentDataSourceFactory, mMockDeploymentEntityMapper); given(mMockDeploymentDataSourceFactory.createDatabaseDataSource()).willReturn( mMockDataSource); } @Test public void shouldSuccessfullyAddADeployment() { given(mMockDataSource.addDeploymentEntity(mMockDeploymentEntity)) .willReturn(Observable.just(1l)); given(mMockDeploymentEntityMapper.map(mMockDeployment)).willReturn(mMockDeploymentEntity); mDeploymentDataRepository.addEntity(mMockDeployment); verify(mMockDeploymentDataSourceFactory).createDatabaseDataSource(); verify(mMockDataSource).addDeploymentEntity(mMockDeploymentEntity); } @Test public void shouldSuccessfullyUpdateADeployment() { given(mMockDataSource.updateDeploymentEntity(mMockDeploymentEntity)).willReturn( Observable.just(1l)); given(mMockDeploymentEntityMapper.map(mMockDeployment)).willReturn(mMockDeploymentEntity); mDeploymentDataRepository.updateEntity(mMockDeployment); verify(mMockDeploymentDataSourceFactory).createDatabaseDataSource(); verify(mMockDataSource).updateDeploymentEntity(mMockDeploymentEntity); } @Test public void shouldSuccessfullyDeleteADeployment() { given(mMockDataSource.deleteDeploymentEntity(1l)).willReturn( Observable.just(1l)); mDeploymentDataRepository.deleteEntity(1l); verify(mMockDeploymentDataSourceFactory).createDatabaseDataSource(); verify(mMockDataSource).deleteDeploymentEntity(1l); } @Test public void shouldSuccessfullyGetADeployment() { given(mMockDataSource.getDeploymentEntity(1l)).willReturn( Observable.just(mMockDeploymentEntity)); given(mMockDeploymentEntityMapper.map(mMockDeployment)).willReturn(mMockDeploymentEntity); mDeploymentDataRepository.getEntity(1l); verify(mMockDeploymentDataSourceFactory).createDatabaseDataSource(); verify(mMockDataSource).getDeploymentEntity(1l); } @Test public void shouldSuccessfullyGetAListOfDeployments() { List<DeploymentEntity> deploymentEntities = new ArrayList<>(); deploymentEntities.add(new DeploymentEntity()); List<Deployment> deployments = new ArrayList<>(); deployments.add(new Deployment()); given(mMockDataSource.getDeploymentEntityList()).willReturn( Observable.just(deploymentEntities)); given(mMockDeploymentEntityMapper.map(deploymentEntities)).willReturn(deployments); mDeploymentDataRepository.getEntities(); verify(mMockDeploymentDataSourceFactory).createDatabaseDataSource(); verify(mMockDataSource).getDeploymentEntityList(); } @Test public void shouldSuccessfullyGetADeploymentByItsStatus() { DeploymentEntity deploymentEntity = new DeploymentEntity(); deploymentEntity.setStatus(DeploymentEntity.Status.ACTIVATED); Deployment deployment = new Deployment(); deployment.setStatus(Deployment.Status.ACTIVATED); given(mMockDataSource.getByStatus(DeploymentEntity.Status.ACTIVATED)).willReturn( Observable.just(deploymentEntity)); given(mMockDeploymentEntityMapper.map(Deployment.Status.ACTIVATED)) .willReturn(DeploymentEntity.Status.ACTIVATED); given(mMockDeploymentEntityMapper.map(deployment)).willReturn(deploymentEntity); mDeploymentDataRepository.getByStatus(Deployment.Status.ACTIVATED); verify(mMockDeploymentDataSourceFactory).createDatabaseDataSource(); verify(mMockDeploymentEntityMapper).map(Deployment.Status.ACTIVATED); verify(mMockDataSource).getByStatus(DeploymentEntity.Status.ACTIVATED); } }
agpl-3.0
GJKrupa/wwa
src/main/java/uk/me/krupa/wwa/fgs/card/CardDtoConverterImpl.java
1105
package uk.me.krupa.wwa.fgs.card; import org.dozer.Mapper; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Scope; import org.springframework.stereotype.Service; import uk.me.krupa.wwa.dto.summary.CardSetSummary; import uk.me.krupa.wwa.entity.cards.CardSet; import java.util.Collection; import java.util.Collections; import java.util.LinkedList; import java.util.List; /** * Created by krupagj on 03/07/2014. */ @Service("cardDtoConverter") @Scope("singleton") public class CardDtoConverterImpl implements CardDtoConverter { @Autowired private Mapper mapper; @Override public CardSetSummary toSummary(CardSet cardSet) { CardSetSummary summary = mapper.map(cardSet, CardSetSummary.class); return summary; } @Override public List<CardSetSummary> toSummaries(Collection<CardSet> cardSets) { LinkedList<CardSetSummary> summaries = new LinkedList<>(); cardSets.stream().map(g -> toSummary(g)).forEach(summaries::add); return Collections.unmodifiableList(summaries); } }
agpl-3.0
GrowthcraftCE/Growthcraft-1.11
src/main/java/growthcraft/cellar/client/gui/GuiFruitPress.java
2690
package growthcraft.cellar.client.gui; import net.minecraftforge.fml.relauncher.SideOnly; import java.util.List; import growthcraft.cellar.GrowthcraftCellar; import growthcraft.cellar.GrowthcraftCellarConfig; import growthcraft.cellar.Reference; import growthcraft.cellar.common.inventory.ContainerFruitPress; import growthcraft.cellar.common.tileentity.TileEntityFruitPress; import growthcraft.cellar.network.PacketClearTankButton; import growthcraft.core.client.gui.widget.GuiButtonDiscard; import growthcraft.core.client.gui.widget.WidgetDeviceProgressIcon; import growthcraft.core.client.gui.widget.WidgetFluidTank; import net.minecraft.client.gui.GuiButton; import net.minecraft.client.resources.I18n; import net.minecraft.entity.player.InventoryPlayer; import net.minecraft.util.ResourceLocation; import net.minecraftforge.fml.relauncher.Side; @SideOnly(Side.CLIENT) public class GuiFruitPress extends GuiCellar<ContainerFruitPress, TileEntityFruitPress> { // INITIALIZE public static final ResourceLocation FRUIT_PRESS_TEXTURE = new ResourceLocation(Reference.MODID, "textures/guis/fruitpress_gui.png"); private GuiButtonDiscard discardButton; public GuiFruitPress(InventoryPlayer inv, TileEntityFruitPress fruitPress) { super(FRUIT_PRESS_TEXTURE, new ContainerFruitPress(inv, fruitPress), fruitPress); } @Override @SuppressWarnings({"rawtypes", "unchecked"}) public void initGui() { super.initGui(); widgets.add(new WidgetFluidTank(widgets, 0, 89, 17, 16, 52)); widgets.add(new WidgetDeviceProgressIcon(widgets, 63, 34, 25, 16) .setProgressDirection(WidgetDeviceProgressIcon.ProgressDirection.LEFT_TO_RIGHT) .setTextureRect(176, 0, 25, 16)); if (GrowthcraftCellarConfig.enableDiscardButton) { this.discardButton = new GuiButtonDiscard(guiResource, 1, guiLeft + 108, guiTop + 54); buttonList.add(discardButton); discardButton.enabled = false; } addTooltipIndex("fluidtank.primary", 89, 17, 16, 52); if (discardButton != null) addTooltipIndex("discard.fluidtank.primary", 108, 54, 16, 16); } @Override public void updateScreen() { super.updateScreen(); if (discardButton != null) discardButton.enabled = tileEntity.isFluidTankFilled(0); } protected void actionPerformed(GuiButton butn) { GrowthcraftCellar.packetPipeline.sendToServer(new PacketClearTankButton(tileEntity.getPos())); } @Override public void addTooltips(String handle, List<String> tooltip) { switch (handle) { case "fluidtank.primary": addFluidTooltips(tileEntity.getFluidStack(0), tooltip); break; case "discard.fluidtank.primary": tooltip.add(I18n.format("gui.grc.discard")); break; default: break; } } }
agpl-3.0
rkfg/jbot
src/main/java/me/rkfg/xmpp/bot/plugins/game/item/IWeapon.java
1482
package me.rkfg.xmpp.bot.plugins.game.item; import static me.rkfg.xmpp.bot.plugins.game.misc.Attrs.*; import java.util.Optional; import me.rkfg.xmpp.bot.plugins.game.IGameObject; import me.rkfg.xmpp.bot.plugins.game.World; import me.rkfg.xmpp.bot.plugins.game.misc.TypedAttribute; import me.rkfg.xmpp.bot.plugins.game.repository.IContentRepository; public interface IWeapon extends IStatsItem { @Override default Optional<TypedAttribute<ISlot>> getFittingSlot() { return Optional.of(WEAPON_SLOT); } default Integer getAttack() { return getAttribute(ATK).orElse(0); } default Integer getDefence() { return getAttribute(DEF).orElse(0); } default Integer getStrength() { return getAttribute(STR).orElse(0); } @SuppressWarnings("unchecked") @Override default <T extends IGameObject> Optional<T> as(TypedAttribute<T> type) { if (type == WEAPON_OBJ || type == STATS_OBJ || type == MUTABLESTATS_OBJ) { return Optional.of((T) this); } return Optional.empty(); } @Override default String getStatsStr() { return String.format(" [оружие] А:%d/З:%d/С:%d", getAttack(), getDefence(), getStrength()); } @Override default Type getItemType() { return Type.WEAPON; } @Override default Optional<IContentRepository> getContentRepository() { return Optional.of(World.THIS.getWeaponRepository()); } }
agpl-3.0
aborg0/rapidminer-vega
src/com/rapidminer/operator/learner/functions/PolynomialRegression.java
9593
/* * 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.learner.functions; import java.util.List; import com.rapidminer.example.Attribute; import com.rapidminer.example.Example; import com.rapidminer.example.ExampleSet; import com.rapidminer.operator.Model; import com.rapidminer.operator.OperatorCapability; import com.rapidminer.operator.OperatorDescription; import com.rapidminer.operator.OperatorException; import com.rapidminer.operator.learner.AbstractLearner; import com.rapidminer.operator.learner.PredictionModel; import com.rapidminer.operator.performance.EstimatedPerformance; import com.rapidminer.operator.performance.PerformanceVector; import com.rapidminer.parameter.ParameterType; import com.rapidminer.parameter.ParameterTypeDouble; import com.rapidminer.parameter.ParameterTypeInt; import com.rapidminer.tools.LoggingHandler; import com.rapidminer.tools.RandomGenerator; import com.rapidminer.tools.math.optimization.ec.es.ESOptimization; import com.rapidminer.tools.math.optimization.ec.es.Individual; import com.rapidminer.tools.math.optimization.ec.es.OptimizationValueType; /** * <p>This regression learning operator fits a polynomial of all attributes to * the given data set. If the data set contains a label Y and three attributes * X1, X2, and X3 a function of the form<br /> * <br /> * <code>Y = w0 + w1 * X1 ^ d1 + w2 * X2 ^ d2 + w3 * X3 ^ d3</code><br /> * <br /> * will be fitted to the training data.</p> * * @author Ingo Mierswa */ public class PolynomialRegression extends AbstractLearner { public static final String PARAMETER_MAX_ITERATIONS = "max_iterations"; public static final String PARAMETER_REPLICATION_FACTOR = "replication_factor"; public static final String PARAMETER_MAX_DEGREE = "max_degree"; public static final String PARAMETER_MIN_COEFFICIENT = "min_coefficient"; public static final String PARAMETER_MAX_COEFFICIENT = "max_coefficient"; private static class RegressionOptimization extends ESOptimization { private int replicationFactor; private ExampleSet exampleSet; private Attribute label; public RegressionOptimization(ExampleSet exampleSet, int replicationFactor, int maxIterations, int maxDegree, double minCoefficient, double maxCoefficient, RandomGenerator random, LoggingHandler logging) { super(getMinVector(exampleSet, replicationFactor, minCoefficient), getMaxVector(exampleSet, replicationFactor, maxDegree, maxCoefficient), 1, exampleSet.getAttributes().size() * 2 * replicationFactor + 1, ESOptimization.INIT_TYPE_RANDOM, maxIterations, maxIterations, ESOptimization.TOURNAMENT_SELECTION, 1.0, true, ESOptimization.GAUSSIAN_MUTATION, 0.01d, 0.0d, false, false, random, logging); this.replicationFactor = replicationFactor; this.exampleSet = exampleSet; this.label = exampleSet.getAttributes().getLabel(); int index = 0; for (int a = 0; a < exampleSet.getAttributes().size(); a++) { for (int f = 0; f < replicationFactor; f++) { setValueType(index++, OptimizationValueType.VALUE_TYPE_DOUBLE); setValueType(index++, OptimizationValueType.VALUE_TYPE_INT); } } setValueType(exampleSet.getAttributes().size() * replicationFactor * 2, OptimizationValueType.VALUE_TYPE_DOUBLE); } private static double[] getMinVector(ExampleSet exampleSet, int replicationFactor, double minCoefficient) { double[] result = new double[exampleSet.getAttributes().size() * replicationFactor * 2 + 1]; int index = 0; for (int a = 0; a < exampleSet.getAttributes().size(); a++) { for (int f = 0; f < replicationFactor; f++) { result[index++] = minCoefficient; result[index++] = 1; } } result[result.length - 1] = minCoefficient; return result; } private static double[] getMaxVector(ExampleSet exampleSet, int replicationFactor, double maxDegree, double maxCoefficient) { double[] result = new double[exampleSet.getAttributes().size() * replicationFactor * 2 + 1]; int index = 0; for (int a = 0; a < exampleSet.getAttributes().size(); a++) { for (int f = 0; f < replicationFactor; f++) { result[index++] = maxCoefficient; result[index++] = maxDegree; } } result[result.length - 1] = maxCoefficient; return result; } @Override public PerformanceVector evaluateIndividual(Individual individual) throws OperatorException { double[] values = individual.getValues(); double[][] coefficients = getCoefficients(values); double[][] degrees = getDegrees(values); double offset = getOffset(values); double error = 0.0d; for (Example example : exampleSet) { double prediction = PolynomialRegressionModel.calculatePrediction(example, coefficients, degrees, offset); double diff = Math.abs(example.getValue(label) - prediction); error += diff * diff; } error = Math.sqrt(error); PerformanceVector performanceVector = new PerformanceVector(); performanceVector.addCriterion(new EstimatedPerformance("Polynomial Regression Error", error, 1, true)); return performanceVector; } public double[][] getCoefficients(double[] values) { int attSize = exampleSet.getAttributes().size(); double[][] coefficients = new double[replicationFactor][attSize]; for (int f = 0; f < replicationFactor; f++) { for (int a = 0; a < attSize; a++) { coefficients[f][a] = values[(f * attSize * 2) + a * 2]; } } return coefficients; } public double[][] getDegrees(double[] values) { int attSize = exampleSet.getAttributes().size(); double[][] degrees = new double[replicationFactor][attSize]; for (int f = 0; f < replicationFactor; f++) { for (int a = 0; a < attSize; a++) { degrees[f][a] = values[(f * attSize * 2) + a * 2 + 1]; } } return degrees; } public double getOffset(double[] values) { return values[values.length - 1]; } } public PolynomialRegression(OperatorDescription description) { super(description); } public Model learn(ExampleSet exampleSet) throws OperatorException { RegressionOptimization optimization = new RegressionOptimization(exampleSet, getParameterAsInt(PARAMETER_REPLICATION_FACTOR), getParameterAsInt(PARAMETER_MAX_ITERATIONS), getParameterAsInt(PARAMETER_MAX_DEGREE), getParameterAsDouble(PARAMETER_MIN_COEFFICIENT), getParameterAsDouble(PARAMETER_MAX_COEFFICIENT), RandomGenerator.getRandomGenerator(this), this); optimization.optimize(); double[] values = optimization.getBestValuesEver(); double[][] coefficients = optimization.getCoefficients(values); double[][] degrees = optimization.getDegrees(values); double offset = optimization.getOffset(values); return new PolynomialRegressionModel(exampleSet, coefficients, degrees, offset); } @Override public Class<? extends PredictionModel> getModelClass() { return PolynomialRegressionModel.class; } public boolean supportsCapability(OperatorCapability lc) { if (lc.equals(OperatorCapability.NUMERICAL_ATTRIBUTES)) return true; if (lc.equals(OperatorCapability.NUMERICAL_LABEL)) return true; if (lc == OperatorCapability.WEIGHTED_EXAMPLES) return true; return false; } @Override public List<ParameterType> getParameterTypes() { List<ParameterType> types = super.getParameterTypes(); ParameterType type = new ParameterTypeInt(PARAMETER_MAX_ITERATIONS, "The maximum number of iterations used for model fitting.", 1, Integer.MAX_VALUE, 5000); type.setExpert(false); types.add(type); type = new ParameterTypeInt(PARAMETER_REPLICATION_FACTOR, "The amount of times each input variable is replicated, i.e. how many different degrees and coefficients can be applied to each variable", 1, Integer.MAX_VALUE, 1); type.setExpert(false); types.add(type); type = new ParameterTypeInt(PARAMETER_MAX_DEGREE, "The maximal degree used for the final polynomial.", 1, Integer.MAX_VALUE, 5); type.setExpert(false); types.add(type); type = new ParameterTypeDouble(PARAMETER_MIN_COEFFICIENT, "The minimum number used for the coefficients and the offset.", Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, -100); type.setExpert(false); types.add(type); type = new ParameterTypeDouble(PARAMETER_MAX_COEFFICIENT, "The maximum number used for the coefficients and the offset.", Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY, 100); type.setExpert(false); types.add(type); types.addAll(RandomGenerator.getRandomGeneratorParameters(this)); return types; } }
agpl-3.0
ungerik/ephesoft
Ephesoft_Community_Release_4.0.2.0/source/dcma-data-access/src/main/java/com/ephesoft/dcma/da/domain/Plugin.java
5312
/********************************************************************************* * 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.da.domain; import java.io.Serializable; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.JoinColumn; import javax.persistence.OneToMany; import javax.persistence.Table; import org.hibernate.annotations.Cascade; import org.hibernate.annotations.CascadeType; import org.hibernate.annotations.NaturalId; import com.ephesoft.dcma.core.model.common.AbstractChangeableEntity; @Entity @Table(name = "plugin") @org.hibernate.annotations.Cache(usage = org.hibernate.annotations.CacheConcurrencyStrategy.READ_WRITE) public class Plugin extends AbstractChangeableEntity implements Serializable { private static final long serialVersionUID = 5694761325202724778L; @Column(name = "plugin_name") @NaturalId private String pluginName; @Column(name = "plugin_desc") private String description; @Column(name = "plugin_version") private String version; @Column(name = "workflow_name") private String workflowName; @Column(name = "script_name") private String scriptName; @Column(name = "plugin_info") private String information; @Column(name = "is_deleted") private Boolean isDeleted; @OneToMany @JoinColumn(name = "plugin_id") @Cascade( {CascadeType.DELETE, CascadeType.SAVE_UPDATE, CascadeType.DELETE_ORPHAN, CascadeType.MERGE, CascadeType.EVICT}) private List<Dependency> dependencies; public String getPluginName() { return pluginName; } public void setPluginName(String pluginName) { this.pluginName = pluginName; } public String getVersion() { return version; } public void setVersion(String version) { this.version = version; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getWorkflowName() { return workflowName; } public void setWorkflowName(String workflowName) { this.workflowName = workflowName; } /** * @return the scriptName */ public String getScriptName() { return scriptName; } /** * @param scriptName the scriptName to set */ public void setScriptName(String scriptName) { this.scriptName = scriptName; } /** * @return the information */ public String getInformation() { return information; } /** * @param information the information to set */ public void setInformation(String information) { this.information = information; } /** * @return the dependencies */ public List<Dependency> getDependencies() { return dependencies; } /** * @param dependencies the dependencies to set */ public void setDependencies(List<Dependency> dependencies) { this.dependencies = dependencies; } public Dependency getDependencyById(Long identifier) { Dependency dependency = null; for (Dependency dependencyObject : dependencies) { if (dependencyObject.getId() == identifier) { dependency = dependencyObject; break; } } return dependency; } /** * @return the deleted */ public Boolean isDeleted() { if (this.isDeleted == null) { this.isDeleted = Boolean.FALSE; } return isDeleted; } /** * @param deleted the deleted to set */ public void setDeleted(Boolean isDeleted) { if (isDeleted == null) { isDeleted = Boolean.FALSE; } this.isDeleted = isDeleted; } }
agpl-3.0
lp0/cursus-ui
src/main/java/uk/uuid/lp0/cursus/ui/menu/ClassPopupMenu.java
1444
/* cursus - Race series management program Copyright 2011, 2014 Simon Arlott 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 uk.uuid.lp0.cursus.ui.menu; import javax.swing.JPopupMenu; import javax.swing.JSeparator; import uk.uuid.lp0.cursus.ui.actions.DeleteClassAction; import uk.uuid.lp0.cursus.ui.actions.EditClassAction; import uk.uuid.lp0.cursus.ui.actions.NewClassAction; import uk.uuid.lp0.cursus.ui.component.DatabaseWindow; import uk.uuid.lp0.cursus.ui.series.SeriesClassesTab; import uk.uuid.cursus.db.data.Class; public class ClassPopupMenu extends JPopupMenu { public ClassPopupMenu(DatabaseWindow win, SeriesClassesTab tab, Class clazz) { add(new EditClassAction(win, tab, clazz)); add(new DeleteClassAction(win, tab, clazz)); add(new JSeparator()); add(new NewClassAction(win, tab, clazz.getSeries())); } }
agpl-3.0
PureSolTechnologies/parsers
parsers/src/main/java/com/puresoltechnologies/parsers/grammar/production/FinishTerminal.java
608
package com.puresoltechnologies.parsers.grammar.production; /** * This singleton class represents the finishing terminal at the end of the * parsing process. * * @author Rick-Rainer Ludwig * */ public class FinishTerminal { public static final String FINISH_CONSTRUCTION_NAME = "_FINISH_"; private static Terminal instance = null; public static Terminal getInstance() { if (instance == null) { createInstance(); } return instance; } private static synchronized void createInstance() { if (instance == null) { instance = new Terminal(FINISH_CONSTRUCTION_NAME, null); } } }
agpl-3.0
phenotips/phenotips
components/family-studies/api/src/main/java/org/phenotips/studies/family/FamilyTools.java
6895
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * 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.phenotips.studies.family; import org.phenotips.data.Patient; import org.phenotips.studies.family.exceptions.PTException; import org.xwiki.component.annotation.Role; import org.xwiki.security.authorization.Right; /** * TODO: instead of interface make a SecureFamilyRepository extending FamilyRepository (similar to * PatientRepository/SecurepatientRepository) Utility methods for manipulating families using the permissions of the * current user. * * @version $Id$ * @since 1.3 */ @Role public interface FamilyTools { /** * Creates an empty family. * * @return Family object corresponding to the newly created family. */ Family createFamily(); /** * Checks if a family with the given identifier exists, but does not check access rights. * * @param familyId family internal identifier * @return true if familyId is an identifier of an existing family */ boolean familyExists(String familyId); /** * Returns family object, or null if doesn't exist or current user has no rights. * * @param familyId a PhenotTips family ID * @return Family object of the family with the given id, or null if familyId is not valid or current user does not * have permissions to view the family. */ Family getFamilyById(String familyId); /** * Returns family pedigree. Essentially this is a shortcut for getFamilyById().getPedigree() with a check that * family is not null. * * @param familyId must be a valid family id * @return pedigree object or null if no such family, no pedigree or no view rights for the family. */ Pedigree getPedigreeForFamily(String familyId); /** * Returns a family ID the patient belongs to. * * @param patientId id of the patient * @return Id of the, or null if patient does not belong to the family or current user has no view rights for the * patient. */ Family getFamilyForPatient(String patientId); /** * Returns patient's pedigree, which is the pedigree of a family that patient belongs to. * * @param patientId id of the patient * @return Id of the, or null if patient does not belong to the family or current user has no view rights for the * patient. */ Pedigree getPedigreeForPatient(String patientId); /** * Removes a patient from the family, modifying both the family and patient records to reflect the change. * * @param patientId of the patient to delete * @return true if patient was removed. false if not, for example, if the patient is not associated with a family, * or if current user has no delete rights */ boolean removeMember(String patientId); /** * Adds a patient to the family, modifying both the family and patient records to reflect the change. * * @param patientId of the patient to add * @param familyId of the family to add patient to * @return true if patient was added. false if not, for example, if the patient is already in a family, * or if current user has no edit rights */ boolean addMember(String patientId, String familyId); /** * Delete family, modifying the both the family and patient records to reflect the change. For the patients which * current user can not edit, uses admin user. * * @param familyId of the family to delete * @param deleteAllMembers indicator whether to delete all family member documents as well * @return true if successful; false if deletion failed or current user has not enough rights */ boolean deleteFamily(String familyId, boolean deleteAllMembers); /** * Similar to deleteFamily, but does not delete the family document (unlinkes all patients from the family). It is * supposed to be used in the event handler for xwiki remove action, when the document will be removed by the * framework itself. * * @param family the family * @return true if successful */ boolean forceRemoveAllMembers(Family family); /** * Checks if the current user can delete the family (or the family and all the members). * * @param familyId of the family to delete * @param deleteAllMembers indicator whether to check delete permissions on all family member documents as well * @return true if successful */ boolean currentUserCanDeleteFamily(String familyId, boolean deleteAllMembers); /** * Checks if the current user has the given right (VIEW/EDIT/DELETE) for the given family. * * @param familyId the id of the family to check access rights for * @param right the right to check for * @return true if familyId is a valid family id and the right is given, false otherwise */ boolean currentUserHasAccessRight(String familyId, Right right); /** * Checks of the given user can add the given patient to the given family. * * @param family the family * @param patient patient to check * @param throwException when true, an exception with details is thrown additionis not possible * @return true if given user has enough rights to add the patient to the family, and if the patient is not in * another family already * @throws PTException when throwException is true and the return value would be false. The exception may help the * caller deduct the reason the addition can not be performed */ boolean canAddToFamily(Family family, Patient patient, boolean throwException) throws PTException; /** * Sets the pedigree for the family, and updates all the corresponding other documents. TODO: it is questionable * where this method should be located, given new entities API. * * @param family the family * @param pedigree to set * @throws PTException when the family could not be correctly and fully updated using the given pedigree */ void setPedigree(Family family, Pedigree pedigree) throws PTException; }
agpl-3.0
o2oa/o2oa
o2server/x_organization_assemble_personal/src/main/java/com/x/organization/assemble/personal/jaxrs/reset/ExceptionCredentialEmpty.java
348
package com.x.organization.assemble.personal.jaxrs.reset; import com.x.base.core.project.exception.LanguagePromptException; public class ExceptionCredentialEmpty extends LanguagePromptException { private static final long serialVersionUID = 1859164370743532895L; public ExceptionCredentialEmpty() { super("用户标识不能为空."); } }
agpl-3.0
hobrasoft-cz/PDFMU
src/main/java/cz/hobrasoft/pdfmu/operation/OperationInspect.java
13022
/* * Copyright (C) 2016 Hobrasoft s.r.o. * * 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 cz.hobrasoft.pdfmu.operation; import com.itextpdf.text.pdf.AcroFields; import com.itextpdf.text.pdf.PdfReader; import com.itextpdf.text.pdf.security.CertificateInfo; import com.itextpdf.text.pdf.security.CertificateInfo.X500Name; import com.itextpdf.text.pdf.security.PdfPKCS7; import cz.hobrasoft.pdfmu.MapSorter; import cz.hobrasoft.pdfmu.PreferenceListComparator; import cz.hobrasoft.pdfmu.jackson.CertificateResult; import cz.hobrasoft.pdfmu.jackson.Inspect; import cz.hobrasoft.pdfmu.jackson.Signature; import cz.hobrasoft.pdfmu.jackson.SignatureDisplay; import cz.hobrasoft.pdfmu.jackson.SignatureMetadata; import cz.hobrasoft.pdfmu.operation.args.InPdfArgs; import cz.hobrasoft.pdfmu.operation.metadata.MetadataParameters; import cz.hobrasoft.pdfmu.operation.version.PdfVersion; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.io.InputStream; import java.security.cert.Certificate; import java.security.cert.X509Certificate; import java.util.ArrayList; import java.util.Date; import java.util.HashMap; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.SortedMap; import javax.security.auth.x500.X500Principal; import net.sourceforge.argparse4j.inf.Namespace; import net.sourceforge.argparse4j.inf.Subparser; import org.apache.commons.lang3.StringUtils; /** * * @author Filip Bartek */ public class OperationInspect extends OperationCommon { private final InPdfArgs in = new InPdfArgs(); @Override public Subparser configureSubparser(Subparser subparser) { String help = "Display PDF version, properties and signatures of a PDF document"; // Configure the subparser subparser.help(help) .description(help) .defaultHelp(true); in.addArguments(subparser); return subparser; } @Override public void execute(Namespace namespace) throws OperationException { in.setFromNamespace(namespace); in.open(); PdfReader pdfReader = in.getPdfReader(); Inspect result; try { result = execute(pdfReader); } finally { in.close(); } writeResult(result); } public Inspect execute(File file) throws OperationException, IOException { assert file != null; Inspect result; try (InputStream is = new FileInputStream(file)) { PdfReader pdfReader = new PdfReader(is); try { result = execute(pdfReader); } finally { pdfReader.close(); } } return result; } private Inspect execute(PdfReader pdfReader) throws OperationException { Inspect result = new Inspect(); // Fetch the PDF version of the input PDF document PdfVersion inVersion = new PdfVersion(pdfReader.getPdfVersion()); to.println(String.format("PDF version: %s", inVersion)); result.version = inVersion.toString(); result.properties = get(pdfReader); result.signatures = display(pdfReader); return result; } private SortedMap<String, String> get(PdfReader pdfReader) { Map<String, String> properties = pdfReader.getInfo(); MetadataParameters mp = new MetadataParameters(); mp.setFromInfo(properties); SortedMap<String, String> propertiesSorted = mp.getSorted(); { to.indentMore("Properties:"); for (Map.Entry<String, String> property : propertiesSorted.entrySet()) { String key = property.getKey(); String value = property.getValue(); to.println(String.format("%s: %s", key, value)); } to.indentLess(); } return propertiesSorted; } public SignatureDisplay display(PdfReader pdfReader) { // digitalsignatures20130304.pdf : Code sample 5.1 AcroFields fields = pdfReader.getAcroFields(); return display(fields); } private SignatureDisplay display(AcroFields fields) { SignatureDisplay result = new SignatureDisplay(); // digitalsignatures20130304.pdf : Code sample 5.1 ArrayList<String> names = fields.getSignatureNames(); // Print number of signatures to.println(String.format("Number of signatures: %d", names.size())); to.println(String.format("Number of document revisions: %d", fields.getTotalRevisions())); result.nRevisions = fields.getTotalRevisions(); List<Signature> signatures = new ArrayList<>(); for (String name : names) { to.println(String.format("Signature field name: %s", name)); to.indentMore(); Signature signature; try { signature = display(fields, name); // May throw OperationException } finally { to.indentLess(); } signature.id = name; signatures.add(signature); } result.signatures = signatures; return result; } private Signature display(AcroFields fields, String name) { // digitalsignatures20130304.pdf : Code sample 5.2 to.println(String.format("Signature covers the whole document: %s", (fields.signatureCoversWholeDocument(name) ? "Yes" : "No"))); to.println(String.format("Document revision: %d of %d", fields.getRevision(name), fields.getTotalRevisions())); PdfPKCS7 pkcs7 = fields.verifySignature(name); Signature signature = display(pkcs7); signature.coversWholeDocument = fields.signatureCoversWholeDocument(name); signature.revision = fields.getRevision(name); return signature; } private Signature display(PdfPKCS7 pkcs7) { Signature signature = new Signature(); // digitalsignatures20130304.pdf : Code sample 5.3 to.println("Signature metadata:"); { SignatureMetadata metadata = new SignatureMetadata(); to.indentMore(); // Only name may be null. // The values are set in {@link PdfPKCS7#verifySignature}. { // name String name = pkcs7.getSignName(); // May be null metadata.name = name; if (name == null) { to.println("Name is not set."); } else { to.println(String.format("Name: %s", name)); } } // TODO?: Print "N/A" if the value is an empty string // TODO?: Determine whether the value is set in the signature to.println(String.format("Reason: %s", pkcs7.getReason())); metadata.reason = pkcs7.getReason(); to.println(String.format("Location: %s", pkcs7.getLocation())); metadata.location = pkcs7.getLocation(); { // Date Date date = pkcs7.getSignDate().getTime(); to.println(String.format("Date and time: %s", date)); metadata.date = date.toString(); } to.indentLess(); signature.metadata = metadata; } { // Certificate chain to.indentMore("Certificate chain:"); Certificate[] certificates = pkcs7.getSignCertificateChain(); to.println(String.format("Number of certificates: %d", certificates.length)); int i = 0; List<CertificateResult> certificatesResult = new ArrayList<>(); for (Certificate certificate : certificates) { to.indentMore(String.format("Certificate %d%s:", i, (i == 0 ? " (the signing certificate)" : ""))); CertificateResult certRes; String type = certificate.getType(); to.println(String.format("Type: %s", type)); // http://docs.oracle.com/javase/1.5.0/docs/guide/security/CryptoSpec.html#AppA if ("X.509".equals(type)) { X509Certificate certificateX509 = (X509Certificate) certificate; certRes = showCertInfo(certificateX509); } else { certRes = new CertificateResult(); } certRes.type = type; to.indentLess(); certificatesResult.add(certRes); ++i; } signature.certificates = certificatesResult; to.indentLess(); } return signature; } private CertificateResult showCertInfo(X509Certificate cert) { CertificateResult certRes = new CertificateResult(); { // Self-signed? X500Principal principalSubject = cert.getSubjectX500Principal(); X500Principal principalIssuer = cert.getIssuerX500Principal(); boolean selfSigned = principalSubject.equals(principalIssuer); to.println(String.format("Self-signed: %s", (selfSigned ? "Yes" : "No"))); certRes.selfSigned = selfSigned; } // Note: More attributes may be available by more direct processing of `cert` // than by using `CertificateInfo.get*Fields`. { // Subject to.indentMore("Subject:"); certRes.subject = showX500Name(CertificateInfo.getSubjectFields(cert)); to.indentLess(); } { // Issuer to.indentMore("Issuer:"); certRes.issuer = showX500Name(CertificateInfo.getIssuerFields(cert)); to.indentLess(); } return certRes; } // The desired order of DN attributes by their type private static final MapSorter<String> dnTypeSorter = new PreferenceListComparator(new String[]{ "CN", "E", "OU", "O", "STREET", "L", "ST", "C"}); /** * The returned map is ordered by keys by {@link dnTypeSorter}. */ private SortedMap<String, List<String>> showX500Name(X500Name name) { Map<String, ArrayList<String>> fields = name.getFields(); // Convert to Map<String, List<String>> Map<String, List<String>> fieldsLists = new LinkedHashMap<>(); fieldsLists.putAll(fields); // Sort by dnTypeSorter SortedMap<String, List<String>> fieldsSorted = dnTypeSorter.sort(fieldsLists); // Print for (Entry<String, List<String>> field : fieldsSorted.entrySet()) { String type = field.getKey(); type = niceX500AttributeType(type); List<String> values = field.getValue(); String valuesString = StringUtils.join(values, ", "); to.println(String.format("%s: %s", type, valuesString)); } return fieldsSorted; } private static final Map<String, String> attributeTypeAliases = new HashMap<>(); static { // Alias sources: // http://www.ietf.org/rfc/rfc2253.txt : Section 2.3 // http://api.itextpdf.com/itext/com/itextpdf/text/pdf/security/CertificateInfo.X500Name.html attributeTypeAliases.put("CN", "Common name"); attributeTypeAliases.put("L", "Locality"); attributeTypeAliases.put("ST", "State or province"); attributeTypeAliases.put("O", "Organization"); attributeTypeAliases.put("OU", "Organizational unit"); attributeTypeAliases.put("C", "Country code"); attributeTypeAliases.put("STREET", "Street address"); attributeTypeAliases.put("DC", "Domain component"); attributeTypeAliases.put("UID", "User ID"); attributeTypeAliases.put("E", "Email address"); attributeTypeAliases.put("SN", "Serial number"); attributeTypeAliases.put("T", "Title"); } private static String niceX500AttributeType(String type) { String nice = attributeTypeAliases.get(type); if (nice != null) { type = nice; } else { return String.format("<%s>", type); } return type; } private static OperationInspect instance = null; public static OperationInspect getInstance() { if (instance == null) { instance = new OperationInspect(); } return instance; } private OperationInspect() { // Singleton } }
agpl-3.0
o2oa/o2oa
o2server/x_organization_assemble_control/src/main/java/com/x/organization/assemble/control/jaxrs/role/ExceptionDuplicateUnique.java
407
package com.x.organization.assemble.control.jaxrs.role; import com.x.base.core.project.exception.LanguagePromptException; class ExceptionDuplicateUnique extends LanguagePromptException { private static final long serialVersionUID = 4132300948670472899L; ExceptionDuplicateUnique(String name, String unique) { super("角色 {} 的唯一标识:{},不能和已有的标识冲突.", name, unique); } }
agpl-3.0
atomicbits/scraml-maven-plugin
src/main/java/io/atomicbits/scraml/mvnplugin/ScramlMojo.java
11513
/* * * (C) Copyright 2015 Atomic BITS (http://atomicbits.io). * * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Affero General Public License * (AGPL) version 3.0 which accompanies this distribution, and is available in * the LICENSE file or at http://www.gnu.org/licenses/agpl-3.0.en.html * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Affero General Public License for more details. * * Contributors: * Peter Rigole * */ package io.atomicbits.scraml.mvnplugin; import io.atomicbits.scraml.generator.ScramlGenerator; import io.atomicbits.scraml.mvnplugin.util.ListUtils; import io.atomicbits.scraml.mvnplugin.util.StringUtil; import org.apache.maven.plugin.AbstractMojo; import org.apache.maven.plugin.MojoExecutionException; import org.apache.maven.plugin.MojoFailureException; import org.apache.maven.plugins.annotations.Mojo; import org.apache.maven.plugins.annotations.Parameter; import org.apache.maven.project.MavenProject; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.Arrays; import java.util.List; import java.util.Map; /** * Created by peter on 4/10/15. */ @Mojo(name = "scraml") public class ScramlMojo extends AbstractMojo { @Parameter(defaultValue = "${project}", readonly = true, required = true) private MavenProject project; /** * Scraml file pointer to the RAML specification main file. */ @Parameter(property = "scraml.ramlApi", defaultValue = "") private String ramlApi; /** * Scraml package name for the api client class and all its resources. Default is empty, then the name will be deduced from the * relative location of the main RAML file. */ @Parameter(property = "scraml.apiPackage", defaultValue = "") private String apiPackage; /** * The language (platform) for which code will be generated. * * @deprecated use the 'platform' parameter instead. */ @Parameter(property = "scraml.language", defaultValue = "") private String language; /** * The platform for which code will be generated (used to be called 'language'). * <p> * Platforms: * - JavaJackson * - ScalaPlay * - AndroidJavaJackson (in the pipeline) * - OsxSwift (in the pipeline) * - Python (in the pipeline) */ @Parameter(property = "scraml.platform", defaultValue = "") private String platform; /** * Scraml base directory to find the RAML files. */ @Parameter(property = "scraml.resourceDirectory", defaultValue = "src/main/resources") private String resourceDirectory; /** * Scraml client source generation output directory. */ @Parameter(property = "scraml.outputDirectory", defaultValue = "target/generated-sources/scraml") private String outputDirectory; /** * Scraml license key. */ @Parameter(property = "scraml.licenseKey", defaultValue = "") private String licenseKey; /** * Scraml class header. */ @Parameter(property = "scraml.classHeader", defaultValue = "") private String classHeader; /** * Single target source filename */ @Parameter(property = "scraml.singleSourceFile", defaultValue = "") private String singleSourceFile; @Override public void execute() throws MojoExecutionException, MojoFailureException { if (!ramlApi.isEmpty()) { File ramlBaseDir; File ramlSource; if (isTopLevel(resourceDirectory)) { ramlBaseDir = new File(resourceDirectory); ramlSource = new File(ramlBaseDir, ramlApi); } else { ramlBaseDir = new File(project.getBasedir(), resourceDirectory); ramlSource = new File(ramlBaseDir, ramlApi); } String[] apiPackageAndClass = packageAndClassFromRamlPointer(ramlApi, apiPackage); String apiPackageName = apiPackageAndClass[0]; String apiClassName = apiPackageAndClass[1]; Map<String, String> generatedFiles; try { generatedFiles = ScramlGenerator.generateScramlCode( getPlatform(), ramlSource.toURI().toURL().toString(), apiPackageName, apiClassName, licenseKey, classHeader, singleSourceFile ); } catch (MalformedURLException | NullPointerException e) { feedbackOnException(ramlBaseDir, ramlApi, ramlSource); throw new RuntimeException("Could not generate RAML client.", e); } File outputDirAsFile; if (isTopLevel(outputDirectory)) { outputDirAsFile = new File(outputDirectory); } else { outputDirAsFile = new File(project.getBasedir(), outputDirectory); } outputDirAsFile.mkdirs(); try { for (Map.Entry<String, String> entry : generatedFiles.entrySet()) { String filePath = entry.getKey(); String content = entry.getValue(); File fileInDst = new File(outputDirAsFile, filePath); fileInDst.getParentFile().mkdirs(); FileWriter writer = new FileWriter(fileInDst); writer.write(content); writer.close(); } } catch (IOException e) { e.printStackTrace(); throw new RuntimeException("Could not generate RAML client.", e); } project.addCompileSourceRoot(outputDirectory); } } private String getPlatform() { if(StringUtil.isDefined(platform)) { if("scala".equals(platform.toLowerCase())) { return Platform.SCALA_PLAY; } else if("java".equals(platform.toLowerCase())) { return Platform.JAVA_JACKSON; } else { return platform; } } else if(StringUtil.isDefined(language)) { if("scala".equals(language.toLowerCase())) { return Platform.SCALA_PLAY; } else if("java".equals(language.toLowerCase())) { return Platform.JAVA_JACKSON; } else { return language; } } else { return Platform.JAVA_JACKSON; } } private Boolean isTopLevel(String directory) { return !StringUtil.isNullOrEmpty(directory) && (directory.startsWith("/") || directory.contains(":\\") || directory.contains(":/")); } private String escape(char ch) { return "\\Q" + ch + "\\E"; } private String[] packageAndClassFromRamlPointer(String pointer, String apiPackageName) { String[] parts = pointer.split(escape('/')); if (parts.length == 1) { String packageName; if (StringUtil.isNullOrEmpty(apiPackageName)) packageName = "io.atomicbits"; else packageName = apiPackageName; return new String[]{packageName, cleanFileName(parts[0])}; } else { String className = cleanFileName(parts[parts.length - 1]); List<String> firstParts = Arrays.asList(parts).subList(0, parts.length - 1); // toIndex is exclusive String packageName; if (StringUtil.isNullOrEmpty(apiPackageName)) packageName = ListUtils.mkString(firstParts, "."); else packageName = apiPackageName; return new String[]{packageName, className}; } } private String cleanFileName(String fileName) { String[] nameSplit = fileName.split(escape('.')); String withOutExtension; if (nameSplit.length == 0) { withOutExtension = fileName; } else { withOutExtension = nameSplit[0]; } // capitalize after special characters and drop those characters along the way List<Character> dropChars = Arrays.asList('-', '_', '+', ' '); String cleanedDropChars = withOutExtension; for (Character dropChar : dropChars) { List<String> items = removeEmpty(Arrays.asList(cleanedDropChars.split(escape(dropChar)))); List<String> capitalized = new ArrayList<>(); for (String item : items) { capitalized.add((capitalize(item))); } cleanedDropChars = ListUtils.mkString(capitalized, ""); } // capitalize after numbers 0 to 9, but keep the numbers List<Character> numbers = Arrays.asList('0', '1', '2', '3', '4', '5', '6', '7', '8', '9'); // Make sure we don't drop the occurrences of numbers at the end by adding a space and removing it later. String cleanedNumbers = cleanedDropChars + " "; for (Character number : numbers) { List<String> items = Arrays.asList(cleanedNumbers.split(escape(number))); // it's important NOT to remove the empty strings here List<String> capitalized = new ArrayList<>(); for (String item : items) { capitalized.add((capitalize(item))); } cleanedNumbers = ListUtils.mkString(capitalized, number.toString()); } // final cleanup of all strange characters return cleanedNumbers.replaceAll("[^A-Za-z0-9]", "").trim(); } private String capitalize(String dirtyName) { char[] chars = dirtyName.toCharArray(); if (chars.length > 0) { chars[0] = Character.toUpperCase(chars[0]); } return new String(chars); } private List<String> removeEmpty(List<String> items) { List<String> emptied = new ArrayList<>(); for (String item : items) { if (!item.isEmpty()) { emptied.add(item); } } return emptied; } private void feedbackOnException(File ramlBaseDir, String ramlPointer, File ramlSource) { System.out.println( "Exception during RAMl parsing, possibly caused by a wrong RAML path.\n" + "Are you sure the following values are correct (non-null)?\n\n" + "- - - - - - - - - - - - - - - - - - - - - - -\n" + "RAML base path: " + ramlBaseDir + "\n" + "RAML relative path: " + ramlPointer + "\n" + "RAML absolute path" + ramlSource + "\n" + "- - - - - - - - - - - - - - - - - - - - - - -\n\n" + "In case the relative path is wrong or null, check your project settings and" + "make sure the 'scramlRamlApi in scraml in Compile' value points to the main" + "raml file in your project's (or module's) resources directory." ); } }
agpl-3.0
marcossilva/convMod
app/src/main/java/com/loyola/talktracer/view/RectangleView.java
2425
package com.loyola.talktracer.view; import android.content.Context; import android.graphics.Canvas; import android.graphics.Color; import android.graphics.Paint; import android.graphics.RectF; import android.util.AttributeSet; import android.util.Log; import android.view.View; /** * draws the Speakers' bars in SummaryActivity */ public class RectangleView extends View { private static final String TAG = "RectangleView"; private boolean mVisible = false; private int mColor = Color.GREEN; private float mBarRatio = (float) 0.50; private RectF mRectF; private Paint mPaint; public RectangleView(Context context, AttributeSet attrs) { super(context, attrs); init(); Log.i(TAG, "RectangleView(Context, AttributeSet)"); } public RectangleView(Context context) { super(context); init(); Log.i(TAG, "RectangleView(Context)"); } private void init() { mRectF = new RectF(); mPaint = new Paint(); } public void setColor(int color) { Log.i(TAG, "setColor() color: " + color); mColor = color; } public void setVisible(boolean visible) { Log.i(TAG, "setVisible() visible: " + visible); mVisible = visible; } public void setBarRatio(float barRatio) { // mBarRatio can range from 0 to 1.0 // 1.0 means it's the longest speaker // 0.5 means that this speaker has spoken half as much as the longest speaker // etc... Log.i(TAG, "setBarRatio() barRatio: " + barRatio); mBarRatio = barRatio; } @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); Log.i(TAG, "onDraw()"); if (mVisible) { mRectF.left = 0; mRectF.top = 0; mRectF.right = mBarRatio * (float) (getWidth() - getLeft()); mRectF.bottom = getHeight(); Log.i(TAG, "getWidth() " + getWidth() + " getLeft() " + getLeft() + " rect.right " + mRectF.right + " bottom " + mRectF.bottom); mPaint.setColor(mColor); mPaint.setStrokeWidth(1); canvas.drawRect(mRectF, mPaint); } } @Override protected void onSizeChanged(int w, int h, int oldw, int oldh) { super.onSizeChanged(w, h, oldw, oldh); Log.i(TAG, "onSizeChanged( " + w + ", " + h + ", " + oldw + ", " + oldh + " )"); } }
agpl-3.0
JHierrot/openprodoc
ProdocWeb/src/java/prodocUI/forms/FMessage.java
1862
/* * OpenProdoc * * See the help doc files distributed with * this work for additional information regarding copyright ownership. * Joaquin Hierro licenses this file to You under: * * License GNU GPL v3 http://www.gnu.org/licenses/gpl.html * * you may not use this file except in compliance with the License. * Unless agreed to in writing, software is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * author: Joaquin Hierro 2011 * */ package prodocUI.forms; import html.*; import javax.servlet.http.HttpServletRequest; import prodocUI.servlet.RefreshDocs; import prodocUI.servlet.RefreshThes; import prodocUI.servlet.SParent; /** * * @author jhierrot */ public class FMessage extends FBase { public FieldButton2 AceptButton; /** Creates a new instance of FormularioLogin * @param Req * @param pTitulo * @param pCabecera * @param Message */ public FMessage(HttpServletRequest Req, String pTitulo, String pCabecera, String Message) { super(Req, pTitulo, pCabecera); AceptButton=new FieldButton2(TT("Ok"), "BOk"); AceptButton.setCSSClass("FFormInputButton"); Table FormTab=new Table(2, 4, 0); FormTab.setCSSClass("FFormularios"); FormTab.getCelda(0,0).setWidth(-40); FormTab.getCelda(1,0).AddElem(new Element(Message)); FormTab.getCelda(1,2).AddElem(AceptButton); Form LoginForm; if (SParent.IsThes(Req)) LoginForm=new Form(RefreshThes.getUrlServlet(),"FormVal"); else LoginForm=new Form(RefreshDocs.getUrlServlet(),"FormVal"); // Form LoginForm=new Form(SMain.getUrlServlet(),"FormVal"); LoginForm.AddElem(FormTab); AddBody(LoginForm); } //----------------------------------------------------------------------------------------------- }
agpl-3.0
dhosa/yamcs
yamcs-core/src/main/java/org/yamcs/hornetq/HornetQEventService.java
549
package org.yamcs.hornetq; import java.util.List; import org.yamcs.ConfigurationException; /** * takes event data from yarch streams and publishes it to hornetq address (reverse of HornetQTmProvider) * Please remove the lines from the EventRecorder when enabling this in the config * */ public class HornetQEventService extends AbstractHornetQTranslatorService { public HornetQEventService(String instance, List<String> streamNames) throws ConfigurationException { super(instance, streamNames, new EventTupleTranslator()); } }
agpl-3.0
OpenWeek/inginious-ucl-java-bac1
Tasks/M02Q02_Morse/student/M02Q02.java
8993
/** * Copyright (c) 2016 Ody Lucas, Rousseaux Tom * 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 student; import java.lang.StringBuffer; import java.lang.System; import static org.junit.Assert.*; import org.junit.runner.JUnitCore; import org.junit.runner.Result; import org.junit.Test; import java.util.Random; import org.junit.runner.notification.Failure; import java.io.*; public class M02Q02 { private static String str = "Le code semble comporter des erreurs : "; @Test public void testNul(){ try{ StringBuffer sb = new StringBuffer(); int nMorceau = 0, nTiret = 2, nPoint = 3; for (int i = 0; i < nMorceau; i++) { // Tirets for (int j = 0; j < nTiret; j++) { sb.append('-'); } // Points for (int j = 0; j < nPoint; j++) { sb.append('.'); } } assertEquals("Avez-vous pensé au cas nul ?", sb.toString(), M02Q02Stu.drawLine(nMorceau, nTiret, nPoint)); sb = new StringBuffer(); nMorceau = 2; nTiret = 0; nPoint = 3; for (int i = 0; i < nMorceau; i++) { // Tirets for (int j = 0; j < nTiret; j++) { sb.append('-'); } // Points for (int j = 0; j < nPoint; j++) { sb.append('.'); } } assertEquals("Avez-vous pensé au cas nul ?", sb.toString(), M02Q02Stu.drawLine(nMorceau, nTiret, nPoint)); sb = new StringBuffer(); nMorceau = 2; nTiret = 3; nPoint = 0; for (int i = 0; i < nMorceau; i++) { // Tirets for (int j = 0; j < nTiret; j++) { sb.append('-'); } // Points for (int j = 0; j < nPoint; j++) { sb.append('.'); } } assertEquals("Avez-vous pensé au cas nul ?", sb.toString(), M02Q02Stu.drawLine(nMorceau, nTiret, nPoint)); sb = new StringBuffer(); nMorceau = 2; nTiret = 4; nPoint = 3; for (int i = 0; i < nMorceau; i++) { // Tirets for (int j = 0; j < nTiret; j++) { sb.append('-'); } // Points for (int j = 0; j < nPoint; j++) { sb.append('.'); } } }catch (ArithmeticException e){ fail(str + "Le code est incorrect : il est interdit de diviser par zéro."); e.printStackTrace(); }catch(ClassCastException e){ fail(str + "Attention, certaines variables ont été mal castées !"); e.printStackTrace(); }catch(StringIndexOutOfBoundsException e){ e.printStackTrace(); fail(str + "Attention, vous tentez de lire en dehors des limites d'un String ! (StringIndexOutOfBoundsException)"); e.printStackTrace(); }catch(ArrayIndexOutOfBoundsException e){ e.printStackTrace(); fail(str + "Attention, vous tentez de lire en dehors des limites d'un tableau ! (ArrayIndexOutOfBoundsException)"); e.printStackTrace(); }catch(NullPointerException e){ fail(str + "Attention, vous faites une opération sur un objet qui vaut null ! Veillez à bien gérer ce cas."); e.printStackTrace(); }catch(Exception e){ fail(str + "\n" + e.getMessage()); e.printStackTrace(); } } @Test public void testTaille(){ try{ StringBuffer sb = new StringBuffer(); int nMorceau = 2, nTiret = 4, nPoint = 3; for (int i = 0; i < nMorceau; i++) { // Tirets for (int j = 0; j < nTiret; j++) { sb.append('-'); } // Points for (int j = 0; j < nPoint; j++) { sb.append('.'); } } assertEquals("Votre réponse ne contient pas assez de caractères, vérifiez le nombre de tours de vos boucles", M02Q02Stu.drawLine(nMorceau, nTiret, nPoint).length() < sb.toString().length(), false); assertEquals("Votre réponse contient trop de caractères, vérifiez le nombre de tours de vos boucles", M02Q02Stu.drawLine(nMorceau, nTiret, nPoint).length() > sb.toString().length(), false); }catch (ArithmeticException e){ fail(str + "Le code est incorrect : il est interdit de diviser par zéro."); e.printStackTrace(); }catch(ClassCastException e){ fail(str + "Attention, certaines variables ont été mal castées !"); e.printStackTrace(); }catch(StringIndexOutOfBoundsException e){ e.printStackTrace(); fail(str + "Attention, vous tentez de lire en dehors des limites d'un String ! (StringIndexOutOfBoundsException)"); e.printStackTrace(); }catch(ArrayIndexOutOfBoundsException e){ e.printStackTrace(); fail(str + "Attention, vous tentez de lire en dehors des limites d'un tableau ! (ArrayIndexOutOfBoundsException)"); e.printStackTrace(); }catch(NullPointerException e){ fail(str + "Attention, vous faites une opération sur un objet qui vaut null ! Veillez à bien gérer ce cas."); e.printStackTrace(); }catch(Exception e){ fail(str + "\n" + e.getMessage()); e.printStackTrace(); } } @Test public void testNormal(){ try{ StringBuffer sb = new StringBuffer(); int nMorceau = 2, nTiret = 4, nPoint = 3; for (int i = 0; i < nMorceau; i++) { // Tirets for (int j = 0; j < nTiret; j++) { sb.append('-'); } // Points for (int j = 0; j < nPoint; j++) { sb.append('.'); } } assertEquals("Votre réponse n'est pas la réponse attendue. Votre réponse : " + M02Q02Stu.drawLine(nMorceau, nTiret, nPoint) + "\nLa réponse attendue : " + sb.toString(),M02Q02Stu.drawLine(nMorceau, nTiret, nPoint).equals(sb.toString()), true); }catch (ArithmeticException e){ fail(str + "Le code est incorrect : il est interdit de diviser par zéro."); e.printStackTrace(); }catch(ClassCastException e){ fail(str + "Attention, certaines variables ont été mal castées !"); e.printStackTrace(); }catch(StringIndexOutOfBoundsException e){ e.printStackTrace(); fail(str + "Attention, vous tentez de lire en dehors des limites d'un String ! (StringIndexOutOfBoundsException)"); e.printStackTrace(); }catch(ArrayIndexOutOfBoundsException e){ e.printStackTrace(); fail(str + "Attention, vous tentez de lire en dehors des limites d'un tableau ! (ArrayIndexOutOfBoundsException)"); e.printStackTrace(); }catch(NullPointerException e){ fail(str + "Attention, vous faites une opération sur un objet qui vaut null ! Veillez à bien gérer ce cas."); e.printStackTrace(); }catch(Exception e){ fail(str + "\n" + e.getMessage()); e.printStackTrace(); } } // Code verificateur public static void main(String[] args) { Result result = JUnitCore.runClasses(M02Q02.class); for (Failure failure: result.getFailures()) { System.err.println(failure.toString()); } if (result.wasSuccessful()) { System.out.println("Tous les tests se sont passés sans encombre"); System.exit(127); } } }
agpl-3.0
WenbinHou/PKUAutoGateway.Android
Reference/IPGWAndroid/android/support/v4/widget/p.java
207
package android.support.v4.widget; import android.database.Cursor; interface p { Cursor a(); Cursor a(CharSequence charSequence); void a(Cursor cursor); CharSequence b(Cursor cursor); }
agpl-3.0
raedle/univis
lib/springframework-1.2.8/src/org/springframework/aop/framework/adapter/ThrowsAdviceAdapter.java
1325
/* * Copyright 2002-2005 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.aop.framework.adapter; import org.aopalliance.aop.Advice; import org.aopalliance.intercept.Interceptor; import org.springframework.aop.Advisor; import org.springframework.aop.ThrowsAdvice; /** * @author Rod Johnson */ class ThrowsAdviceAdapter implements AdvisorAdapter { /** * @see org.springframework.aop.framework.adapter.AdvisorAdapter#supportsAdvice */ public boolean supportsAdvice(Advice advice) { return advice instanceof ThrowsAdvice; } /** * @see org.springframework.aop.framework.adapter.AdvisorAdapter#getInterceptor */ public Interceptor getInterceptor(Advisor advisor) { return new ThrowsAdviceInterceptor(advisor.getAdvice()); } }
lgpl-2.1
chenyahui/Not-yet-named
Not-yet-named/src/org/archive/crawler/frontier/AbstractFrontier.java
45878
/* AbstractFrontier * * $Id: AbstractFrontier.java 6704 2009-11-25 01:38:55Z gojomo $ * * Created on Aug 17, 2004 * * Copyright (C) 2004 Internet Archive. * * This file is part of the Heritrix web crawler (crawler.archive.org). * * Heritrix is free software; you can redistribute it and/or modify * it under the terms of the GNU Lesser Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * any later version. * * Heritrix is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser Public License for more details. * * You should have received a copy of the GNU Lesser Public License * along with Heritrix; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package org.archive.crawler.frontier; import java.io.BufferedWriter; import java.io.File; import java.io.FileOutputStream; import java.io.IOException; import java.io.OutputStreamWriter; import java.io.PrintWriter; import java.io.Serializable; import java.io.StringWriter; import java.io.Writer; import java.util.Iterator; import java.util.List; import java.util.concurrent.atomic.AtomicLong; import java.util.logging.Level; import java.util.logging.Logger; import java.util.regex.Pattern; import javax.management.AttributeNotFoundException; import org.apache.commons.httpclient.HttpStatus; import org.archive.crawler.datamodel.CandidateURI; import org.archive.crawler.datamodel.CoreAttributeConstants; import org.archive.crawler.datamodel.CrawlHost; import org.archive.crawler.datamodel.CrawlOrder; import org.archive.crawler.datamodel.CrawlServer; import org.archive.crawler.datamodel.CrawlSubstats; import org.archive.crawler.datamodel.CrawlURI; import org.archive.crawler.datamodel.FetchStatusCodes; import org.archive.crawler.datamodel.RobotsExclusionPolicy; import org.archive.crawler.datamodel.CrawlSubstats.Stage; import org.archive.crawler.event.CrawlStatusListener; import org.archive.crawler.framework.CrawlController; import org.archive.crawler.framework.Frontier; import org.archive.crawler.framework.ToeThread; import org.archive.crawler.framework.exceptions.EndedException; import org.archive.crawler.framework.exceptions.FatalConfigurationException; import org.archive.crawler.settings.ModuleType; import org.archive.crawler.settings.RegularExpressionConstraint; import org.archive.crawler.settings.SimpleType; import org.archive.crawler.settings.Type; import org.archive.crawler.url.Canonicalizer; import org.archive.net.UURI; import org.archive.util.ArchiveUtils; /** * Shared facilities for Frontier implementations. * * @author gojomo */ public abstract class AbstractFrontier extends ModuleType implements CrawlStatusListener, Frontier, FetchStatusCodes, CoreAttributeConstants, Serializable { private static final long serialVersionUID = -4766504935003203930L; private static final Logger logger = Logger .getLogger(AbstractFrontier.class.getName()); protected transient CrawlController controller; /** ordinal numbers to assign to created CrawlURIs */ protected AtomicLong nextOrdinal = new AtomicLong(1); /** should the frontier hold any threads asking for URIs? */ protected boolean shouldPause = false; /** * should the frontier send an EndedException to any threads asking for * URIs? */ protected transient boolean shouldTerminate = false; /** * how many multiples of last fetch elapsed time to wait before recontacting * same server */ public final static String ATTR_DELAY_FACTOR = "delay-factor"; protected final static Float DEFAULT_DELAY_FACTOR = new Float(5); /** * always wait this long after one completion before recontacting same * server, regardless of multiple */ public final static String ATTR_MIN_DELAY = "min-delay-ms"; // 3 secs. protected final static Integer DEFAULT_MIN_DELAY = new Integer(3000); /** * Whether to respect a 'Crawl-Delay' (in seconds) given in a site's * robots.txt */ public final static String ATTR_RESPECT_CRAWL_DELAY_UP_TO_SECS = "respect-crawl-delay-up-to-secs"; // by default, respect robots.txt-provided Crawl-Delay up to 300 secs protected final static Integer DEFAULT_RESPECT_CRAWL_DELAY_UP_TO_SECS = 300; // 5 minutes /** never wait more than this long, regardless of multiple */ public final static String ATTR_MAX_DELAY = "max-delay-ms"; // 30 secs protected final static Integer DEFAULT_MAX_DELAY = new Integer(30000); /** number of hops of embeds (ERX) to bump to front of host queue */ public final static String ATTR_PREFERENCE_EMBED_HOPS = "preference-embed-hops"; protected final static Integer DEFAULT_PREFERENCE_EMBED_HOPS = new Integer(1); /** maximum per-host bandwidth usage */ public final static String ATTR_MAX_HOST_BANDWIDTH_USAGE = "max-per-host-bandwidth-usage-KB-sec"; protected final static Integer DEFAULT_MAX_HOST_BANDWIDTH_USAGE = new Integer(0); /** maximum overall bandwidth usage */ public final static String ATTR_MAX_OVERALL_BANDWIDTH_USAGE = "total-bandwidth-usage-KB-sec"; protected final static Integer DEFAULT_MAX_OVERALL_BANDWIDTH_USAGE = new Integer(0); /** for retryable problems, seconds to wait before a retry */ public final static String ATTR_RETRY_DELAY = "retry-delay-seconds"; // 15 mins protected final static Long DEFAULT_RETRY_DELAY = new Long(900); /** maximum times to emit a CrawlURI without final disposition */ public final static String ATTR_MAX_RETRIES = "max-retries"; protected final static Integer DEFAULT_MAX_RETRIES = new Integer(30); public final static String ATTR_QUEUE_ASSIGNMENT_POLICY = "queue-assignment-policy"; /** queue assignment to force onto CrawlURIs; intended to be overridden */ public final static String ATTR_FORCE_QUEUE = "force-queue-assignment"; protected final static String DEFAULT_FORCE_QUEUE = ""; // word chars, dash, period, comma, colon protected final static String ACCEPTABLE_FORCE_QUEUE = "[-\\w\\.,:]*"; /** whether pause, rather than finish, when crawl appears done */ public final static String ATTR_PAUSE_AT_FINISH = "pause-at-finish"; // TODO: change default to true once well-tested protected final static Boolean DEFAULT_PAUSE_AT_FINISH = Boolean.FALSE; /** whether to pause at crawl start */ public final static String ATTR_PAUSE_AT_START = "pause-at-start"; protected final static Boolean DEFAULT_PAUSE_AT_START = Boolean.FALSE; /** whether to pause at crawl start */ public final static String ATTR_SOURCE_TAG_SEEDS = "source-tag-seeds"; protected final static Boolean DEFAULT_SOURCE_TAG_SEEDS = Boolean.FALSE; /** * Recover log on or off attribute. */ protected final static String ATTR_RECOVERY_ENABLED = "recovery-log-enabled"; protected final static Boolean DEFAULT_ATTR_RECOVERY_ENABLED = Boolean.TRUE; // to maintain serialization compatibility, stored under old names protected long queuedUriCount; protected long succeededFetchCount; protected long failedFetchCount; protected long disregardedUriCount; // top-level stats /** total URIs queued to be visited */ transient protected AtomicLong liveQueuedUriCount = new AtomicLong(0); transient protected AtomicLong liveSucceededFetchCount = new AtomicLong(0); transient protected AtomicLong liveFailedFetchCount = new AtomicLong(0); /** URIs that are disregarded (for example because of robot.txt rules */ transient protected AtomicLong liveDisregardedUriCount = new AtomicLong(0); /** * Used when bandwidth constraint are used. */ protected long totalProcessedBytes = 0; private transient long nextURIEmitTime = 0; protected long processedBytesAfterLastEmittedURI = 0; protected int lastMaxBandwidthKB = 0; /** * Crawl replay logger. * * Currently captures Frontier/URI transitions. * Can be null if user chose not to run a recovery.log. */ private transient FrontierJournal recover = null; /** file collecting report of ignored seed-file entries (if any) */ public static final String IGNORED_SEEDS_FILENAME = "seeds.ignored"; /** * @param name Name of this frontier. * @param description Description for this frontier. */ public AbstractFrontier(String name, String description) { super(name, description); addElementToDefinition(new SimpleType(ATTR_DELAY_FACTOR, "How many multiples of last fetch elapsed time to wait before " + "recontacting same server", DEFAULT_DELAY_FACTOR)); addElementToDefinition(new SimpleType(ATTR_MAX_DELAY, "Never wait more than this long.", DEFAULT_MAX_DELAY)); addElementToDefinition(new SimpleType(ATTR_MIN_DELAY, "Always wait this long after one completion before recontacting " + "same server.", DEFAULT_MIN_DELAY)); addElementToDefinition(new SimpleType(ATTR_RESPECT_CRAWL_DELAY_UP_TO_SECS, "Respect a Crawl-Delay directive in a site's robots.txt " +"up to this value in seconds. (If longer, simply " +"respect this value.) Default is 300 seconds (5 minutes).", DEFAULT_RESPECT_CRAWL_DELAY_UP_TO_SECS)); addElementToDefinition(new SimpleType(ATTR_MAX_RETRIES, "How often to retry fetching a URI that failed to be retrieved. " + "If zero, the crawler will get the robots.txt only.", DEFAULT_MAX_RETRIES)); addElementToDefinition(new SimpleType(ATTR_RETRY_DELAY, "How long to wait by default until we retry fetching a" + " URI that failed to be retrieved (seconds). ", DEFAULT_RETRY_DELAY)); addElementToDefinition(new SimpleType( ATTR_PREFERENCE_EMBED_HOPS, "Number of embedded (or redirected) hops up to which " + "a URI has higher priority scheduling. For example, if set " + "to 1 (the default), items such as inline images (1-hop " + "embedded resources) will be scheduled ahead of all regular " + "links (or many-hop resources, like nested frames). If set to " + "zero, no preferencing will occur, and embeds/redirects are " + "scheduled the same as regular links.", DEFAULT_PREFERENCE_EMBED_HOPS)); Type t; t = addElementToDefinition(new SimpleType( ATTR_MAX_OVERALL_BANDWIDTH_USAGE, "The maximum average bandwidth the crawler is allowed to use. " + "The actual read speed is not affected by this setting, it only " + "holds back new URIs from being processed when the bandwidth " + "usage has been to high. 0 means no bandwidth limitation.", DEFAULT_MAX_OVERALL_BANDWIDTH_USAGE)); t.setOverrideable(false); t = addElementToDefinition(new SimpleType( ATTR_MAX_HOST_BANDWIDTH_USAGE, "The maximum average bandwidth the crawler is allowed to use per " + "host. The actual read speed is not affected by this setting, " + "it only holds back new URIs from being processed when the " + "bandwidth usage has been to high. 0 means no bandwidth " + "limitation.", DEFAULT_MAX_HOST_BANDWIDTH_USAGE)); t.setExpertSetting(true); // Read the list of permissible choices from heritrix.properties. // Its a list of space- or comma-separated values. String queueStr = System.getProperty(AbstractFrontier.class.getName() + "." + ATTR_QUEUE_ASSIGNMENT_POLICY, HostnameQueueAssignmentPolicy.class.getName() + " " + IPQueueAssignmentPolicy.class.getName() + " " + BucketQueueAssignmentPolicy.class.getName() + " " + SurtAuthorityQueueAssignmentPolicy.class.getName() + " " + TopmostAssignedSurtQueueAssignmentPolicy.class.getName()); Pattern p = Pattern.compile("\\s*,\\s*|\\s+"); String [] queues = p.split(queueStr); if (queues.length <= 0) { throw new RuntimeException("Failed parse of " + " assignment queue policy string: " + queueStr); } t = addElementToDefinition(new SimpleType(ATTR_QUEUE_ASSIGNMENT_POLICY, "Defines how to assign URIs to queues. Can assign by host, " + "by ip, and into one of a fixed set of buckets (1k).", queues[0], queues)); t.setExpertSetting(true); t.setOverrideable(true); t = addElementToDefinition(new SimpleType( ATTR_FORCE_QUEUE, "The queue name into which to force URIs. Should " + "be left blank at global level. Specify a " + "per-domain/per-host override to force URIs into " + "a particular named queue, regardless of the assignment " + "policy in effect (domain or ip-based politeness). " + "This could be used on domains known to all be from " + "the same small set of IPs (eg blogspot, dailykos, etc.) " + "to simulate IP-based politeness, or it could be used if " + "you wanted to enforce politeness over a whole domain, even " + "though the subdomains are split across many IPs.", DEFAULT_FORCE_QUEUE)); t.setOverrideable(true); t.setExpertSetting(true); t.addConstraint(new RegularExpressionConstraint(ACCEPTABLE_FORCE_QUEUE, Level.WARNING, "This field must contain only alphanumeric " + "characters plus period, dash, comma, colon, or underscore.")); t = addElementToDefinition(new SimpleType( ATTR_PAUSE_AT_START, "Whether to pause when the crawl begins, before any URIs " + "are tried. This gives the operator a chance to verify or " + "adjust the crawl before actual work begins. " + "Default is false.", DEFAULT_PAUSE_AT_START)); t = addElementToDefinition(new SimpleType( ATTR_PAUSE_AT_FINISH, "Whether to pause when the crawl appears finished, rather " + "than immediately end the crawl. This gives the operator an " + "opportunity to view crawl results, and possibly add URIs or " + "adjust settings, while the crawl state is still available. " + "Default is false.", DEFAULT_PAUSE_AT_FINISH)); t.setOverrideable(false); t = addElementToDefinition(new SimpleType( ATTR_SOURCE_TAG_SEEDS, "Whether to tag seeds with their own URI as a heritable " + "'source' String, which will be carried-forward to all URIs " + "discovered on paths originating from that seed. When " + "present, such source tags appear in the second-to-last " + "crawl.log field.", DEFAULT_SOURCE_TAG_SEEDS)); t.setOverrideable(false); t = addElementToDefinition(new SimpleType(ATTR_RECOVERY_ENABLED, "Set to false to disable recovery log writing. Do this if " + "you you are using the checkpoint feature for recovering " + "crashed crawls.", DEFAULT_ATTR_RECOVERY_ENABLED)); t.setExpertSetting(true); // No sense in it being overrideable. t.setOverrideable(false); } public void start() { if (((Boolean)getUncheckedAttribute(null, ATTR_PAUSE_AT_START)) .booleanValue()) { // trigger crawl-wide pause controller.requestCrawlPause(); } else { // simply begin unpause(); } } synchronized public void pause() { shouldPause = true; } synchronized public void unpause() { shouldPause = false; notifyAll(); } public void initialize(CrawlController c) throws FatalConfigurationException, IOException { c.addCrawlStatusListener(this); File logsDisk = null; try { logsDisk = c.getSettingsDir(CrawlOrder.ATTR_LOGS_PATH); } catch (AttributeNotFoundException e) { logger.log(Level.SEVERE, "Failed to get logs directory", e); } if (logsDisk != null) { String logsPath = logsDisk.getAbsolutePath() + File.separatorChar; if (((Boolean)getUncheckedAttribute(null, ATTR_RECOVERY_ENABLED)) .booleanValue()) { this.recover = new RecoveryJournal(logsPath, FrontierJournal.LOGNAME_RECOVER); } } // try { // final Class qapClass = Class.forName((String)getUncheckedAttribute( // null, ATTR_QUEUE_ASSIGNMENT_POLICY)); // // queueAssignmentPolicy = // (QueueAssignmentPolicy)qapClass.newInstance(); // } catch (Exception e) { // logger.log(Level.SEVERE, "Bad queue assignment policy class", e); // throw new FatalConfigurationException(e.getMessage()); // } } synchronized public void terminate() { shouldTerminate = true; if (this.recover != null) { this.recover.close(); this.recover = null; } unpause(); } /** * Report CrawlURI to each of the three 'substats' accumulators * (group/queue, server, host) for a given stage. * * @param curi * @param stage */ protected void tally(CrawlURI curi, Stage stage) { // Tally per-server, per-host, per-frontier-class running totals CrawlServer server = controller.getServerCache().getServerFor(curi); if (server != null) { server.getSubstats().tally(curi, stage); } CrawlHost host = controller.getServerCache().getHostFor(curi); if (host != null) { host.getSubstats().tally(curi, stage); } FrontierGroup group = controller.getFrontier().getGroup(curi); group.getSubstats().tally(curi, stage); } protected void doJournalFinishedSuccess(CrawlURI c) { tally(c,CrawlSubstats.Stage.SUCCEEDED); if (this.recover != null) { this.recover.finishedSuccess(c); } } protected void doJournalAdded(CrawlURI c) { tally(c,CrawlSubstats.Stage.SCHEDULED); if (this.recover != null) { this.recover.added(c); } } protected void doJournalRescheduled(CrawlURI c) { tally(c,CrawlSubstats.Stage.RETRIED); if (this.recover != null) { this.recover.rescheduled(c); } } protected void doJournalFinishedFailure(CrawlURI c) { tally(c,CrawlSubstats.Stage.FAILED); if (this.recover != null) { this.recover.finishedFailure(c); } } protected void doJournalDisregarded(CrawlURI c) { tally(c,CrawlSubstats.Stage.DISREGARDED); if (this.recover != null) { this.recover.finishedDisregard(c); } } protected void doJournalEmitted(CrawlURI c) { if (this.recover != null) { this.recover.emitted(c); } } /** * Frontier is empty only if all queues are empty and no URIs are in-process * * @return True if queues are empty. */ public boolean isEmpty() { return liveQueuedUriCount.get() == 0; } /** * Increment the running count of queued URIs. */ protected void incrementQueuedUriCount() { liveQueuedUriCount.incrementAndGet(); } /** * Increment the running count of queued URIs. Synchronized because * operations on longs are not atomic. * * @param increment * amount to increment the queued count */ protected void incrementQueuedUriCount(long increment) { liveQueuedUriCount.addAndGet(increment); } /** * Note that a number of queued Uris have been deleted. * * @param numberOfDeletes */ protected void decrementQueuedCount(long numberOfDeletes) { liveQueuedUriCount.addAndGet(-numberOfDeletes); } /** * (non-Javadoc) * * @see org.archive.crawler.framework.Frontier#queuedUriCount() */ public long queuedUriCount() { return liveQueuedUriCount.get(); } /** * (non-Javadoc) * * @see org.archive.crawler.framework.Frontier#finishedUriCount() */ public long finishedUriCount() { return liveSucceededFetchCount.get() + liveFailedFetchCount.get() + liveDisregardedUriCount.get(); } /** * Increment the running count of successfully fetched URIs. */ protected void incrementSucceededFetchCount() { liveSucceededFetchCount.incrementAndGet(); } /** * (non-Javadoc) * * @see org.archive.crawler.framework.Frontier#succeededFetchCount() */ public long succeededFetchCount() { return liveSucceededFetchCount.get(); } /** * Increment the running count of failed URIs. */ protected void incrementFailedFetchCount() { liveFailedFetchCount.incrementAndGet(); } /** * (non-Javadoc) * * @see org.archive.crawler.framework.Frontier#failedFetchCount() */ public long failedFetchCount() { return liveFailedFetchCount.get(); } /** * Increment the running count of disregarded URIs. Synchronized because * operations on longs are not atomic. */ protected void incrementDisregardedUriCount() { liveDisregardedUriCount.incrementAndGet(); } public long disregardedUriCount() { return liveDisregardedUriCount.get(); } /** @deprecated misnomer; use StatisticsTracking figures instead */ public long totalBytesWritten() { return totalProcessedBytes; } /** * Load up the seeds. * * This method is called on initialize and inside in the crawlcontroller * when it wants to force reloading of configuration. * * @see org.archive.crawler.framework.CrawlController#kickUpdate() */ public void loadSeeds() { Writer ignoredWriter = new StringWriter(); logger.info("beginning"); // Get the seeds to refresh. Iterator iter = this.controller.getScope().seedsIterator(ignoredWriter); int count = 0; while (iter.hasNext()) { UURI u = (UURI)iter.next(); CandidateURI caUri = CandidateURI.createSeedCandidateURI(u); caUri.setSchedulingDirective(CandidateURI.MEDIUM); if (((Boolean)getUncheckedAttribute(null, ATTR_SOURCE_TAG_SEEDS)) .booleanValue()) { caUri.putString(CoreAttributeConstants.A_SOURCE_TAG,caUri.toString()); caUri.makeHeritable(CoreAttributeConstants.A_SOURCE_TAG); } schedule(caUri); count++; if(count%1000==0) { logger.info(count+" seeds"); } } // save ignored items (if any) where they can be consulted later saveIgnoredItems(ignoredWriter.toString(), controller.getDisk()); logger.info("finished"); } /** * Dump ignored seed items (if any) to disk; delete file otherwise. * Static to allow non-derived sibling classes (frontiers not yet * subclassed here) to reuse. * * @param ignoredItems * @param dir */ public static void saveIgnoredItems(String ignoredItems, File dir) { File ignoredFile = new File(dir, IGNORED_SEEDS_FILENAME); if(ignoredItems==null | ignoredItems.length()>0) { try { BufferedWriter bw = new BufferedWriter( new OutputStreamWriter(new FileOutputStream(ignoredFile),"UTF-8")); bw.write(ignoredItems); bw.close(); } catch (IOException e) { // TODO make an alert? e.printStackTrace(); } } else { // delete any older file (if any) ignoredFile.delete(); } } protected CrawlURI asCrawlUri(CandidateURI caUri) { CrawlURI curi; if (caUri instanceof CrawlURI) { curi = (CrawlURI)caUri; } else { curi = CrawlURI.from(caUri, nextOrdinal.getAndIncrement()); } curi.setClassKey(getClassKey(curi)); return curi; } /** * @param now * @throws InterruptedException * @throws EndedException */ protected synchronized void preNext(long now) throws InterruptedException, EndedException { if (this.controller == null) { return; } // Check completion conditions if (this.controller.atFinish()) { if (((Boolean)getUncheckedAttribute(null, ATTR_PAUSE_AT_FINISH)) .booleanValue()) { this.controller.requestCrawlPause(); } else { this.controller.beginCrawlStop(); } } // enforce operator pause if (shouldPause) { while (shouldPause) { this.controller.toePaused(); wait(); } // exitted pause; possibly finish regardless of pause-at-finish if (controller != null && controller.atFinish()) { this.controller.beginCrawlStop(); } } // enforce operator terminate or thread retirement if (shouldTerminate || ((ToeThread)Thread.currentThread()).shouldRetire()) { throw new EndedException("terminated"); } enforceBandwidthThrottle(now); } /** * Perform any special handling of the CrawlURI, such as promoting its URI * to seed-status, or preferencing it because it is an embed. * * @param curi */ protected void applySpecialHandling(CrawlURI curi) { if (curi.isSeed() && curi.getVia() != null && curi.flattenVia().length() > 0) { // The only way a seed can have a non-empty via is if it is the // result of a seed redirect. Add it to the seeds list. // // This is a feature. This is handling for case where a seed // gets immediately redirected to another page. What we're doing is // treating the immediate redirect target as a seed. this.controller.getScope().addSeed(curi); // And it needs rapid scheduling. if (curi.getSchedulingDirective() == CandidateURI.NORMAL) { curi.setSchedulingDirective(CandidateURI.MEDIUM); } } // optionally preferencing embeds up to MEDIUM int prefHops = ((Integer)getUncheckedAttribute(curi, ATTR_PREFERENCE_EMBED_HOPS)).intValue(); if (prefHops > 0) { int embedHops = curi.getTransHops(); if (embedHops > 0 && embedHops <= prefHops && curi.getSchedulingDirective() == CandidateURI.NORMAL) { // number of embed hops falls within the preferenced range, and // uri is not already MEDIUM -- so promote it curi.setSchedulingDirective(CandidateURI.MEDIUM); } } } /** * Perform fixups on a CrawlURI about to be returned via next(). * * @param curi * CrawlURI about to be returned by next() * @param q * the queue from which the CrawlURI came */ protected void noteAboutToEmit(CrawlURI curi, WorkQueue q) { curi.setHolder(q); // if (curi.getServer() == null) { // // TODO: perhaps short-circuit the emit here, // // because URI will be rejected as unfetchable // } doJournalEmitted(curi); } /** * @param curi * @return the CrawlServer to be associated with this CrawlURI */ protected CrawlServer getServer(CrawlURI curi) { return this.controller.getServerCache().getServerFor(curi); } /** * Return a suitable value to wait before retrying the given URI. * * @param curi * CrawlURI to be retried * @return millisecond delay before retry */ protected long retryDelayFor(CrawlURI curi) { int status = curi.getFetchStatus(); return (status == S_CONNECT_FAILED || status == S_CONNECT_LOST || status == S_DOMAIN_UNRESOLVABLE)? ((Long)getUncheckedAttribute(curi, ATTR_RETRY_DELAY)).longValue(): 0; // no delay for most } /** * Update any scheduling structures with the new information in this * CrawlURI. Chiefly means make necessary arrangements for no other URIs at * the same host to be visited within the appropriate politeness window. * * @param curi * The CrawlURI * @return millisecond politeness delay */ protected long politenessDelayFor(CrawlURI curi) { long durationToWait = 0; if (curi.containsKey(A_FETCH_BEGAN_TIME) && curi.containsKey(A_FETCH_COMPLETED_TIME)) { long completeTime = curi.getLong(A_FETCH_COMPLETED_TIME); long durationTaken = (completeTime - curi .getLong(A_FETCH_BEGAN_TIME)); durationToWait = (long)(((Float)getUncheckedAttribute(curi, ATTR_DELAY_FACTOR)).floatValue() * durationTaken); long minDelay = ((Integer)getUncheckedAttribute(curi, ATTR_MIN_DELAY)).longValue(); if (minDelay > durationToWait) { // wait at least the minimum durationToWait = minDelay; } long maxDelay = ((Integer)getUncheckedAttribute(curi, ATTR_MAX_DELAY)).longValue(); if (durationToWait > maxDelay) { // wait no more than the maximum durationToWait = maxDelay; } long respectThreshold = ((Integer)getUncheckedAttribute(curi, ATTR_RESPECT_CRAWL_DELAY_UP_TO_SECS)).longValue()*1000; if(durationToWait<respectThreshold) { // may need to extend wait CrawlServer s = controller.getServerCache().getServerFor(curi); String ua = curi.getUserAgent(); if(ua==null) { ua = controller.getOrder().getUserAgent(curi); } RobotsExclusionPolicy rep = s.getRobots(); if (rep!=null) { long crawlDelay = (long)(1000 * s.getRobots().getCrawlDelay(ua)); crawlDelay = (crawlDelay > respectThreshold) ? respectThreshold : crawlDelay; if (crawlDelay > durationToWait) { // wait at least the directive crawl-delay durationToWait = crawlDelay; } } } long now = System.currentTimeMillis(); int maxBandwidthKB = ((Integer)getUncheckedAttribute(curi, ATTR_MAX_HOST_BANDWIDTH_USAGE)).intValue(); if (maxBandwidthKB > 0) { // Enforce bandwidth limit CrawlHost host = controller.getServerCache().getHostFor(curi); long minDurationToWait = host.getEarliestNextURIEmitTime() - now; float maxBandwidth = maxBandwidthKB * 1.024F; // kilo factor long processedBytes = curi.getContentSize(); host .setEarliestNextURIEmitTime((long)(processedBytes / maxBandwidth) + now); if (minDurationToWait > durationToWait) { durationToWait = minDurationToWait; } } } return durationToWait; } /** * Ensure that any overall-bandwidth-usage limit is respected, by pausing as * long as necessary. * * @param now * @throws InterruptedException */ private void enforceBandwidthThrottle(long now) throws InterruptedException { int maxBandwidthKB = ((Integer)getUncheckedAttribute(null, ATTR_MAX_OVERALL_BANDWIDTH_USAGE)).intValue(); if (maxBandwidthKB > 0) { // Make sure that new bandwidth setting doesn't affect total crawl if (maxBandwidthKB != lastMaxBandwidthKB) { lastMaxBandwidthKB = maxBandwidthKB; processedBytesAfterLastEmittedURI = totalProcessedBytes; } // Enforce bandwidth limit long sleepTime = nextURIEmitTime - now; float maxBandwidth = maxBandwidthKB * 1.024F; // Kilo_factor long processedBytes = totalProcessedBytes - processedBytesAfterLastEmittedURI; long shouldHaveEmittedDiff = nextURIEmitTime == 0? 0 : nextURIEmitTime - now; nextURIEmitTime = (long)(processedBytes / maxBandwidth) + now + shouldHaveEmittedDiff; processedBytesAfterLastEmittedURI = totalProcessedBytes; if (sleepTime > 0) { long targetTime = now + sleepTime; now = System.currentTimeMillis(); while (now < targetTime) { synchronized (this) { if (logger.isLoggable(Level.FINE)) { logger.fine("Frontier waits for: " + sleepTime + "ms to respect bandwidth limit."); } // TODO: now that this is a wait(), frontier can // still schedule and finish items while waiting, // which is good, but multiple threads could all // wait for the same wakeTime, which somewhat // spoils the throttle... should be fixed. wait(targetTime - now); } now = System.currentTimeMillis(); } } } } /** * Take note of any processor-local errors that have been entered into the * CrawlURI. * * @param curi * */ protected void logLocalizedErrors(CrawlURI curi) { if (curi.containsKey(A_LOCALIZED_ERRORS)) { List localErrors = (List)curi.getObject(A_LOCALIZED_ERRORS); Iterator iter = localErrors.iterator(); while (iter.hasNext()) { Object array[] = {curi, iter.next()}; controller.localErrors.log(Level.WARNING, curi.getUURI() .toString(), array); } // once logged, discard curi.remove(A_LOCALIZED_ERRORS); } } /** * Utility method to return a scratch dir for the given key's temp files. * Every key gets its own subdir. To avoid having any one directory with * thousands of files, there are also two levels of enclosing directory * named by the least-significant hex digits of the key string's java * hashcode. * * @param key * @return File representing scratch directory */ protected File scratchDirFor(String key) { String hex = Integer.toHexString(key.hashCode()); while (hex.length() < 4) { hex = "0" + hex; } int len = hex.length(); return new File(this.controller.getStateDisk(), hex.substring(len - 2, len) + File.separator + hex.substring(len - 4, len - 2) + File.separator + key); } protected boolean overMaxRetries(CrawlURI curi) { // never retry more than the max number of times if (curi.getFetchAttempts() >= ((Integer)getUncheckedAttribute(curi, ATTR_MAX_RETRIES)).intValue()) { return true; } return false; } public void importRecoverLog(String pathToLog, boolean retainFailures) throws IOException { File source = new File(pathToLog); if (!source.isAbsolute()) { source = new File(getSettingsHandler().getOrder().getController() .getDisk(), pathToLog); } RecoveryJournal.importRecoverLog(source, controller, retainFailures); } /* * (non-Javadoc) * * @see org.archive.crawler.framework.URIFrontier#kickUpdate() */ public void kickUpdate() { // by default, do nothing // (scope will loadSeeds, if appropriate) } /** * Log to the main crawl.log * * @param curi */ protected void log(CrawlURI curi) { curi.aboutToLog(); Object array[] = {curi}; this.controller.uriProcessing.log(Level.INFO, curi.getUURI().toString(), array); } protected boolean isDisregarded(CrawlURI curi) { switch (curi.getFetchStatus()) { case S_ROBOTS_PRECLUDED: // they don't want us to have it case S_BLOCKED_BY_CUSTOM_PROCESSOR: case S_OUT_OF_SCOPE: // filtered out by scope case S_BLOCKED_BY_USER: // filtered out by user case S_TOO_MANY_EMBED_HOPS: // too far from last true link case S_TOO_MANY_LINK_HOPS: // too far from seeds case S_DELETED_BY_USER: // user deleted return true; default: return false; } } /** * Checks if a recently completed CrawlURI that did not finish successfully * needs to be retried (processed again after some time elapses) * * @param curi * The CrawlURI to check * @return True if we need to retry. */ protected boolean needsRetrying(CrawlURI curi) { if (overMaxRetries(curi)) { return false; } switch (curi.getFetchStatus()) { case HttpStatus.SC_UNAUTHORIZED: // We can get here though usually a positive status code is // a success. We get here if there is rfc2617 credential data // loaded and we're supposed to go around again. See if any // rfc2617 credential present and if there, assume it got // loaded in FetchHTTP on expectation that we're to go around // again. If no rfc2617 loaded, we should not be here. boolean loaded = curi.hasRfc2617CredentialAvatar(); if (!loaded && logger.isLoggable(Level.INFO)) { logger.info("Have 401 but no creds loaded " + curi); } return loaded; case S_DEFERRED: case S_CONNECT_FAILED: case S_CONNECT_LOST: case S_DOMAIN_UNRESOLVABLE: // these are all worth a retry // TODO: consider if any others (S_TIMEOUT in some cases?) deserve // retry return true; default: return false; } } /** * Canonicalize passed uuri. Its would be sweeter if this canonicalize * function was encapsulated by that which it canonicalizes but because * settings change with context -- i.e. there may be overrides in operation * for a particular URI -- its not so easy; Each CandidateURI would need a * reference to the settings system. That's awkward to pass in. * * @param uuri Candidate URI to canonicalize. * @return Canonicalized version of passed <code>uuri</code>. */ protected String canonicalize(UURI uuri) { return Canonicalizer.canonicalize(uuri, this.controller.getOrder()); } /** * Canonicalize passed CandidateURI. This method differs from * {@link #canonicalize(UURI)} in that it takes a look at * the CandidateURI context possibly overriding any canonicalization effect if * it could make us miss content. If canonicalization produces an URL that * was 'alreadyseen', but the entry in the 'alreadyseen' database did * nothing but redirect to the current URL, we won't get the current URL; * we'll think we've already see it. Examples would be archive.org * redirecting to www.archive.org or the inverse, www.netarkivet.net * redirecting to netarkivet.net (assuming stripWWW rule enabled). * <p>Note, this method under circumstance sets the forceFetch flag. * * @param cauri CandidateURI to examine. * @return Canonicalized <code>cacuri</code>. */ protected String canonicalize(CandidateURI cauri) { String canon = canonicalize(cauri.getUURI()); if (cauri.isLocation()) { // If the via is not the same as where we're being redirected (i.e. // we're not being redirected back to the same page, AND the // canonicalization of the via is equal to the the current cauri, // THEN forcefetch (Forcefetch so no chance of our not crawling // content because alreadyseen check things its seen the url before. // An example of an URL that redirects to itself is: // http://bridalelegance.com/images/buttons3/tuxedos-off.gif. // An example of an URL whose canonicalization equals its via's // canonicalization, and we want to fetch content at the // redirection (i.e. need to set forcefetch), is netarkivet.dk. if (!cauri.toString().equals(cauri.getVia().toString()) && canonicalize(cauri.getVia()).equals(canon)) { cauri.setForceFetch(true); } } return canon; } /** * @param cauri CrawlURI we're to get a key for. * @return a String token representing a queue */ public String getClassKey(CandidateURI cauri) { String queueKey = (String)getUncheckedAttribute(cauri, ATTR_FORCE_QUEUE); if ("".equals(queueKey)) { // no forced override QueueAssignmentPolicy queueAssignmentPolicy = getQueueAssignmentPolicy(cauri); queueKey = queueAssignmentPolicy.getClassKey(this.controller, cauri); } return queueKey; } protected QueueAssignmentPolicy getQueueAssignmentPolicy(CandidateURI cauri) { String clsName = (String)getUncheckedAttribute(cauri, ATTR_QUEUE_ASSIGNMENT_POLICY); try { return (QueueAssignmentPolicy) Class.forName(clsName).newInstance(); } catch (Exception e) { throw new RuntimeException(e); } } /** * @return RecoveryJournal instance. May be null. */ public FrontierJournal getFrontierJournal() { return this.recover; } public void crawlEnding(String sExitMessage) { // TODO Auto-generated method stub } public void crawlEnded(String sExitMessage) { if (logger.isLoggable(Level.INFO)) { logger.info("Closing with " + Long.toString(queuedUriCount()) + " urls still in queue."); } } public void crawlStarted(String message) { // TODO Auto-generated method stub } public void crawlPausing(String statusMessage) { // TODO Auto-generated method stub } public void crawlPaused(String statusMessage) { // TODO Auto-generated method stub } public void crawlResuming(String statusMessage) { // TODO Auto-generated method stub } public void crawlCheckpoint(File checkpointDir) throws Exception { if (this.recover == null) { return; } this.recover.checkpoint(checkpointDir); } // // Reporter implementation // public String singleLineReport() { return ArchiveUtils.singleLineReport(this); } public void reportTo(PrintWriter writer) { reportTo(null, writer); } // // maintain serialization compatibility to pre-AtomicLong impl private void writeObject(java.io.ObjectOutputStream out) throws IOException { queuedUriCount = liveQueuedUriCount.get(); succeededFetchCount = liveSucceededFetchCount.get(); failedFetchCount = liveFailedFetchCount.get(); disregardedUriCount = liveDisregardedUriCount.get(); out.defaultWriteObject(); } private void readObject(java.io.ObjectInputStream in) throws IOException, ClassNotFoundException { in.defaultReadObject(); liveQueuedUriCount = new AtomicLong(queuedUriCount); liveSucceededFetchCount = new AtomicLong(succeededFetchCount); liveFailedFetchCount = new AtomicLong(failedFetchCount); liveDisregardedUriCount = new AtomicLong(disregardedUriCount); } }
lgpl-2.1
jeroenvanmaanen/leia
leia-api/src/main/java/org/leialearns/api/common/NodeDataProxy.java
327
package org.leialearns.api.common; import org.leialearns.api.model.Version; import org.leialearns.api.structure.Node; public interface NodeDataProxy<Type> { void setNode(Node node); Node getNode(); void set(Version version, Node node); Version getVersion(); void setData(Type data); Type getData(); }
lgpl-2.1
geotools/geotools
modules/ogc/net.opengis.wcs/src/net/opengis/gml/LinearRingType.java
1565
/** * <copyright> * </copyright> * * $Id$ */ package net.opengis.gml; import org.eclipse.emf.common.util.EList; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Linear Ring Type</b></em>'. * <!-- end-user-doc --> * * <!-- begin-model-doc --> * A LinearRing is defined by four or more coordinate tuples, with linear interpolation between them; the first and last coordinates must be coincident. * <!-- end-model-doc --> * * <p> * The following features are supported: * <ul> * <li>{@link net.opengis.gml.LinearRingType#getPos <em>Pos</em>}</li> * </ul> * </p> * * @see net.opengis.gml.GmlPackage#getLinearRingType() * @model extendedMetaData="name='LinearRingType' kind='elementOnly'" * @generated */ public interface LinearRingType extends AbstractRingType { /** * Returns the value of the '<em><b>Pos</b></em>' containment reference list. * The list contents are of type {@link net.opengis.gml.DirectPositionType}. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Pos</em>' containment reference list isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Pos</em>' containment reference list. * @see net.opengis.gml.GmlPackage#getLinearRingType_Pos() * @model type="net.opengis.gml.DirectPositionType" containment="true" lower="4" * extendedMetaData="kind='element' name='pos' namespace='##targetNamespace'" * @generated */ EList getPos(); } // LinearRingType
lgpl-2.1
devkevanishvili/TreeOresMod
src/main/java/com/lessoner/treeores/Thaumcraft/TreeOresThaumcraft.java
2065
package com.lessoner.treeores.Thaumcraft; import com.lessoner.treeores.References; import com.lessoner.treeores.Thaumcraft.Blocks.TreeOresTHCBlocks; import com.lessoner.treeores.Thaumcraft.Items.TreeOresTHCItems; import net.minecraft.item.ItemStack; import net.minecraftforge.oredict.OreDictionary; /** * Created by Anguarmas on 9/30/2015. */ public class TreeOresThaumcraft { public static void preInit() { TreeOresTHCBlocks.init(); TreeOresTHCItems.init(); } public static void init() { TreeOresTHCBlocks.registerBlocks(); TreeOresTHCItems.registerItems(); oreDict(); TreeOresTHCRecipes.addRecipes(); } private static void oreDict() { for (int i = 0; i < 4; i++) { OreDictionary.registerOre(References.oreDictTHCLeaves, new ItemStack(TreeOresTHCBlocks.TreeOresTHCLeaves1, 1, i)); OreDictionary.registerOre(References.oreDictTHCLeaves, new ItemStack(TreeOresTHCBlocks.TreeOresTHCBossLeaves1, 1, i)); OreDictionary.registerOre(References.oreDictTHCLeaves, new ItemStack(TreeOresTHCBlocks.TreeOresTHCLeaves2, 1, i)); OreDictionary.registerOre(References.oreDictTHCLeaves, new ItemStack(TreeOresTHCBlocks.TreeOresTHCBossLeaves2, 1, i)); OreDictionary.registerOre(References.oreDictTHCLogs, new ItemStack(TreeOresTHCBlocks.TreeOresTHCLogs1, 1, i)); OreDictionary.registerOre(References.oreDictTHCLogs, new ItemStack(TreeOresTHCBlocks.TreeOresTHCLogs2, 1, i)); OreDictionary.registerOre(References.oreDictTHCSaplings, new ItemStack(TreeOresTHCBlocks.TreeOresTHCSaplings1, 1, i)); OreDictionary.registerOre(References.oreDictTHCSaplings, new ItemStack(TreeOresTHCBlocks.TreeOresTHCBossSaplings1, 1, i)); OreDictionary.registerOre(References.oreDictTHCSaplings, new ItemStack(TreeOresTHCBlocks.TreeOresTHCSaplings2, 1, i)); OreDictionary.registerOre(References.oreDictTHCSaplings, new ItemStack(TreeOresTHCBlocks.TreeOresTHCBossSaplings2, 1, i)); } } }
lgpl-2.1
EgorZhuk/pentaho-reporting
designer/datasource-editor-kettle/src/main/java/org/pentaho/reporting/ui/datasources/kettle/FileKettleQueryEntry.java
5610
/* * 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) 2006 - 2013 Pentaho Corporation.. All rights reserved. */ package org.pentaho.reporting.ui.datasources.kettle; import org.pentaho.di.core.exception.KettleException; import org.pentaho.di.repository.Repository; import org.pentaho.di.trans.TransMeta; import org.pentaho.di.trans.step.StepMeta; import org.pentaho.reporting.engine.classic.core.DataFactoryContext; import org.pentaho.reporting.engine.classic.core.ReportDataFactoryException; import org.pentaho.reporting.engine.classic.extensions.datasources.kettle.AbstractKettleTransformationProducer; import org.pentaho.reporting.engine.classic.extensions.datasources.kettle.FormulaArgument; import org.pentaho.reporting.engine.classic.extensions.datasources.kettle.FormulaParameter; import org.pentaho.reporting.engine.classic.extensions.datasources.kettle.KettleTransFromFileProducer; import org.pentaho.reporting.engine.classic.extensions.datasources.kettle.KettleTransformationProducer; import org.pentaho.reporting.libraries.base.util.StringUtils; import org.pentaho.reporting.libraries.resourceloader.ResourceKey; import org.pentaho.reporting.libraries.resourceloader.ResourceManager; import org.pentaho.reporting.ui.datasources.kettle.embedded.KettleParameterInfo; import java.util.Collections; import java.util.List; public class FileKettleQueryEntry extends KettleQueryEntry { private static class InternalKettleTransFromFileProducer extends KettleTransFromFileProducer { public InternalKettleTransFromFileProducer( final String transformationFile ) { super( transformationFile, null, new FormulaArgument[ 0 ], new FormulaParameter[ 0 ] ); } public TransMeta loadTransformation( final Repository repository, final ResourceManager resourceManager, final ResourceKey contextKey ) throws ReportDataFactoryException, KettleException { return super.loadTransformation( repository, resourceManager, contextKey ); } } private String file; private String selectedStepName; private List<StepMeta> cachedSteps; public FileKettleQueryEntry( final String aName ) { super( aName ); } public FileKettleQueryEntry( final String aName, final KettleTransformationProducer producer ) { super( aName ); this.file = producer.getTransformationFile(); this.selectedStepName = producer.getStepName(); if ( producer instanceof AbstractKettleTransformationProducer ) { AbstractKettleTransformationProducer p = (AbstractKettleTransformationProducer) producer; setArguments( p.getArguments() ); setParameters( p.getParameter() ); setStopOnErrors( p.isStopOnError() ); } } public boolean validate() { return super.validate() && ( !StringUtils.isEmpty( selectedStepName ) ) && ( !StringUtils.isEmpty( file ) ); } public void setFile( final String file ) { this.file = file; clearCachedEntries(); setValidated( validate() ); } protected void clearCachedEntries() { super.clearCachedEntries(); cachedSteps = null; } public String getFile() { return file; } public String getSelectedStep() { return selectedStepName; } public void setSelectedStep( final String selectedStep ) { this.selectedStepName = selectedStep; setValidated( validate() ); } public KettleParameterInfo[] getDeclaredParameters( final DataFactoryContext context ) throws KettleException, ReportDataFactoryException { if ( StringUtils.isEmpty( file ) ) { return new KettleParameterInfo[ 0 ]; } return super.getDeclaredParameters( context ); } protected AbstractKettleTransformationProducer loadTransformation( final DataFactoryContext context ) { return new InternalKettleTransFromFileProducer( file ); } public List<StepMeta> getSteps( final DataFactoryContext context ) throws KettleException, ReportDataFactoryException { if ( StringUtils.isEmpty( file ) ) { return Collections.emptyList(); } if ( cachedSteps == null ) { AbstractKettleTransformationProducer trans = loadTransformation( context ); TransMeta transMeta = trans.loadTransformation( context ); cachedSteps = Collections.unmodifiableList( transMeta.getSteps() ); } return cachedSteps; } public KettleTransformationProducer createProducer() { final FormulaArgument[] argumentFields = getArguments(); final FormulaParameter[] varNames = getParameters(); final String file = getFile(); final String selectedStep = getSelectedStep(); KettleTransFromFileProducer kettleTransFromFileProducer = new KettleTransFromFileProducer( file, selectedStep, argumentFields, varNames ); kettleTransFromFileProducer.setStopOnError( isStopOnErrors() ); return kettleTransFromFileProducer; } }
lgpl-2.1
xwiki/xwiki-platform
xwiki-platform-core/xwiki-platform-office/xwiki-platform-office-importer/src/test/java/org/xwiki/officeimporter/internal/cleaner/EmptyLineParagraphOfficeCleaningTest.java
2433
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * 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.xwiki.officeimporter.internal.cleaner; import java.io.StringReader; import org.junit.jupiter.api.Test; import org.w3c.dom.Document; import org.w3c.dom.NodeList; import org.xwiki.test.junit5.mockito.ComponentTest; import static org.junit.jupiter.api.Assertions.assertEquals; /** * Test case for filtering {@code<p><br/></p>} elements in {@link OfficeHTMLCleaner}. * * @version $Id$ * @since 1.8 */ @ComponentTest public class EmptyLineParagraphOfficeCleaningTest extends AbstractHTMLCleaningTest { /** * The first {@code<p><br/></p>} element in a sequence of such elements should be removed. */ @Test public void removeFirstEmptyLineParagraph() { String html = header + "<p><br/></p>" + footer; Document doc = officeHTMLCleaner.clean(new StringReader(html)); NodeList paras = doc.getElementsByTagName("p"); assertEquals(0, paras.getLength()); NodeList breaks = doc.getElementsByTagName("br"); assertEquals(0, breaks.getLength()); } /** * In a sequence of {@code<p><br/></p>} elements, while the first element is removed, rest will be replaced by * {@code<br/>} elements. */ @Test public void replaceAdditionalEmptyLineParagraphs() { String html = header + "<p><br/></p><p><br/></p><p><br/></p><p><br/></p>" + footer; Document doc = officeHTMLCleaner.clean(new StringReader(html)); NodeList breaks = doc.getElementsByTagName("br"); assertEquals(3, breaks.getLength()); } }
lgpl-2.1
jfinkels/tuxguitar
src/main/java/org/herac/tuxguitar/io/midi/MidiFileHeader.java
226
package org.herac.tuxguitar.io.midi; public interface MidiFileHeader { public static final int HEADER_LENGTH = 6; public static final int HEADER_MAGIC = 0x4d546864; public static final int TRACK_MAGIC = 0x4d54726b; }
lgpl-2.1
lucee/unoffical-Lucee-no-jre
source/java/loader/src/lucee/runtime/search/SearchData.java
1265
/** * * Copyright (c) 2014, the Railo Company Ltd. 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. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see <http://www.gnu.org/licenses/>. * **/ package lucee.runtime.search; import java.util.Map; public interface SearchData { public Map<String,SuggestionItem> getSuggestion(); public int getSuggestionMax(); public void setSuggestionQuery(String suggestionQuery); public String getSuggestionQuery(); /** * increments the searched records * * @param count records searched * @return all records searched */ public int addRecordsSearched(int count); /** * return the records searched */ public int getRecordsSearched(); }
lgpl-2.1
lucee/Lucee
core/src/main/java/lucee/runtime/helpers/HttpSessionBindingListenerStruct.java
1940
/** * * Copyright (c) 2014, the Railo Company Ltd. 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. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see <http://www.gnu.org/licenses/>. * **/ package lucee.runtime.helpers; import java.io.IOException; import java.net.MalformedURLException; import java.net.URL; import javax.servlet.http.HttpSessionBindingEvent; import javax.servlet.http.HttpSessionBindingListener; import lucee.runtime.type.Collection; import lucee.runtime.type.StructImpl; public final class HttpSessionBindingListenerStruct extends StructImpl implements HttpSessionBindingListener { private URL url; /** * Constructor of the class * * @param strUrl * @throws MalformedURLException */ public HttpSessionBindingListenerStruct(String strUrl) throws MalformedURLException { this(new URL(strUrl)); } /** * Constructor of the class * * @param url */ public HttpSessionBindingListenerStruct(URL url) { this.url = url; } @Override public void valueBound(HttpSessionBindingEvent event) { } @Override public void valueUnbound(HttpSessionBindingEvent event) { try { url.getContent(); } catch (IOException e) { } } @Override public Collection duplicate(boolean deepCopy) { HttpSessionBindingListenerStruct trg = new HttpSessionBindingListenerStruct(url); copy(this, trg, deepCopy); return trg; } }
lgpl-2.1
GenomicParisCentre/nividic
src/main/java/fr/ens/transcriptome/nividic/om/filters/BioAssayIntegerThresholdFilter.java
5405
/* * Nividic development code * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. If you do not have a copy, * see: * * http://www.gnu.org/copyleft/lesser.html * * Copyright for this code is held jointly by the microarray platform * of the École Normale Supérieure and the individual authors. * These should be listed in @author doc comments. * * For more information on the Nividic project and its aims, * or to join the Nividic mailing list, visit the home page * at: * * http://www.transcriptome.ens.fr/nividic * */ package fr.ens.transcriptome.nividic.om.filters; import fr.ens.transcriptome.nividic.om.BioAssay; /** * This class define a filter for integer with a threshold and a comparator. * @author Laurent Jourdren */ public class BioAssayIntegerThresholdFilter extends BioAssayGenericIntegerFieldFilter { private String field = BioAssay.FIELD_NAME_FLAG; private static final Comparator defaultComparator = Comparator.UPPER; private int threshold; private boolean absolute; private Comparator comparator = Comparator.UPPER; private enum Comparator { LOWER, LOWEREQUALS, EQUALS, NOTEQUALS, UPPEREQUALS, UPPER; public String toString() { switch (this) { case LOWER: return "<"; case LOWEREQUALS: return "<="; case EQUALS: return "="; case NOTEQUALS: return "!="; case UPPEREQUALS: return ">="; case UPPER: return ">"; default: return ""; } } public static Comparator getComparator(final String comparatorString) { if (comparatorString == null) return defaultComparator; String s = comparatorString.trim(); if (s.equals("<")) return LOWER; if (s.equals("<=")) return LOWEREQUALS; if (s.equals("=") || s.equals("==")) return EQUALS; if (s.equals("!=")) return NOTEQUALS; if (s.equals(">=")) return UPPEREQUALS; if (s.equals(">")) return UPPER; return defaultComparator; } }; // // Getter // /** * Define the field to filter. * @return the field to filter */ public String getFieldToFilter() { return field; } /** * Get the comparator. * @return The comparator */ public String getComparator() { return comparator.toString(); } /** * Get the threshold. * @return The threshold */ public double getThreshold() { return this.threshold; } /** * test if the value to test is absolute. * @return true if the value to test is absolute */ public boolean isAbsolute() { return this.absolute; } // // Setter // /** * Set the field to filter. * @param field Field to filter */ public void setFieldToFilter(final String field) { this.field = field; } /** * Set the comparator. * @param comparator Comparator to set */ public void setComparator(final String comparator) { this.comparator = Comparator.getComparator(comparator); } /** * Set the threshold. * @param threshold Threshold to set */ public void setThreshold(final int threshold) { this.threshold = threshold; } /** * Set if the value to test is absolute. * @param absolute true to enable absolute values */ public void setAbsolute(final boolean absolute) { this.absolute = absolute; } // // Other methods // /** * Test the value. * @param value Value to test * @return true if the test if positive */ @Override public boolean test(final int value) { final double threshold = this.threshold; final double v = this.absolute ? Math.abs(value) : value; if (Double.isNaN(threshold)) return false; switch (this.comparator) { case LOWER: return v < threshold; case LOWEREQUALS: return v <= threshold; case EQUALS: return v == threshold; case NOTEQUALS: return v != threshold; case UPPEREQUALS: return v >= threshold; case UPPER: return v > threshold; default: return false; } } /** * Get parameter filter information for the history * @return a String with information about the parameter of the filter */ public String getParameterInfo() { return "Field=" + getFieldToFilter() + ";Comparator=" + getComparator() + ";Threshold=" + getThreshold(); } // // Constructor // /** * Public constructor. * @param field Field to test * @param threshold Threshold of the test * @param comparator comparator to use */ public BioAssayIntegerThresholdFilter(final String field, final String comparator, final int threshold) { this(field, comparator, threshold, false); } /** * Public constructor. * @param field Field to test * @param threshold Threshold of the test * @param comparator comparator to use * @param absolute true if the threshold is absolute value */ public BioAssayIntegerThresholdFilter(final String field, final String comparator, final int threshold, final boolean absolute) { setFieldToFilter(field); setThreshold(threshold); setComparator(comparator); setAbsolute(absolute); } }
lgpl-2.1
metteo/jts
jts-test-library/src/main/java/com/vividsolutions/jtstest/testbuilder/io/shapefile/ShapefileException.java
331
package com.vividsolutions.jtstest.testbuilder.io.shapefile; /** * Thrown when an error relating to the shapefile * occures */ public class ShapefileException extends Exception{ public ShapefileException(){ super(); } public ShapefileException(String s){ super(s); } }
lgpl-2.1
JiriOndrusek/wildfly-core
cli/src/main/java/org/jboss/as/cli/handlers/HelpHandler.java
3465
/* * JBoss, Home of Professional Open Source. * Copyright 2015, Red Hat, Inc., 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.as.cli.handlers; import java.util.ArrayList; import java.util.Collections; import java.util.List; import org.jboss.as.cli.CommandContext; import org.jboss.as.cli.CommandFormatException; import org.jboss.as.cli.CommandHandler; import org.jboss.as.cli.CommandLineException; import org.jboss.as.cli.CommandRegistry; import org.jboss.as.cli.impl.ArgumentWithoutValue; /** * Help command handler. Reads 'help/help.txt' and prints its content to the output stream. * * @author Alexey Loubyansky */ public class HelpHandler extends CommandHandlerWithHelp { private final CommandRegistry cmdRegistry; private final ArgumentWithoutValue commands = new ArgumentWithoutValue(this, "--commands"); public HelpHandler(CommandRegistry cmdRegistry) { this("help", cmdRegistry); } public HelpHandler(String command, CommandRegistry cmdRegistry) { super(command); if(cmdRegistry == null) { throw new IllegalArgumentException("CommandRegistry is null"); } this.cmdRegistry = cmdRegistry; // trick to disable the help arg helpArg.setExclusive(false); helpArg.addCantAppearAfter(commands); helpArg.addRequiredPreceding(commands); } /* (non-Javadoc) * @see org.jboss.as.cli.CommandHandler#handle(org.jboss.as.cli.Context) */ @Override public void handle(CommandContext ctx) throws CommandLineException { boolean printCommands; try { printCommands = commands.isPresent(ctx.getParsedCommandLine()); } catch (CommandFormatException e) { throw new CommandFormatException(e.getLocalizedMessage()); } if(printCommands) { final List<String> commands = new ArrayList<String>(); for(String cmd : cmdRegistry.getTabCompletionCommands()) { CommandHandler handler = cmdRegistry.getCommandHandler(cmd); if(handler.isAvailable(ctx)) { commands.add(cmd); } } Collections.sort(commands); ctx.printLine("Commands available in the current context:"); ctx.printColumns(commands); ctx.printLine("To read a description of a specific command execute 'command_name --help'."); } else { printHelp(ctx); } } @Override protected void doHandle(CommandContext ctx) { } }
lgpl-2.1
dbussink/rxtx
src/gnu/io/Zystem.java
7831
/*------------------------------------------------------------------------ | Zystem is a native interface for message reporting in java. | Copyright 2002 by Trent Jarvi taj@www.linux.org.uk. | | 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. | | The following has been added to allow RXTX to be distributed with Sun | Microsystem's CommAPI library as suggested by the FSF. | | http://www.fsf.org/licenses/gpl-faq.html#LinkingOverControlledInterface | | A program that contains no derivative of any portion of RXTX, but | is designed to work with RXTX by being compiled or linked with it, | is considered a "work that uses the Library" subject to the terms and | conditions of the GNU Lesser General Public License. | | As a special exception, the copyright holders of RXTX give you | permission to link RXTX with independent modules that communicate with | RXTX solely through the Sun Microsytems CommAPI interface, regardless of | the license terms of these independent modules, and to copy and distribute | the resulting combined work under terms of your choice, provided that | every copy of the combined work is accompanied by a complete copy of | the source code of RXTX (the version of RXTX used to produce the | combined work), being distributed under the terms of the GNU Lesser General | Public License plus this exception. An independent module is a | module which is not derived from or based on RXTX. | | Note that people who make modified versions of RXTX are not obligated | to grant this special exception for their modified versions; it is | their choice whether to do so. The GNU Lesser General Public License | gives permission to release a modified version without this exception; this | exception also makes it possible to release a modified version which | carries forward this exception. | | You should have received a copy of the GNU Lesser General Public | License along with this library; if not, write to the Free | Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA --------------------------------------------------------------------------*/ package gnu.io; import java.io.RandomAccessFile; public class Zystem { public static final int SILENT_MODE = 0; public static final int FILE_MODE = 1; public static final int NET_MODE = 2; public static final int MEX_MODE = 3; public static final int PRINT_MODE = 4; public static final int J2EE_MSG_MODE = 5; public static final int J2SE_LOG_MODE = 6; static int mode; static { /* The rxtxZystem library uses Python code and is not included with RXTX. A seperate library will be released to avoid potential license conflicts. Trent Jarvi taj@www.linux.org.uk */ //System.loadLibrary( "rxtxZystem" ); mode = SILENT_MODE; } private static String target; public Zystem( int m ) throws UnSupportedLoggerException { mode = m; startLogger( "asdf" ); } /** * Constructor. * Mode is taken from the java system property "javax.comm.log.mode". The available values are :<ul> * <li> SILENT_MODE No logging * <li> FILE_MODE log to file * <li> NET_MODE * <li> MEX_MODE * <li> PRINT_MODE * <li> J2EE_MSG_MODE * <li> J2SE_LOG_MODE log to java.util.logging * </ul> */ public Zystem () throws UnSupportedLoggerException { String s = System.getProperty ("javax.comm.log.mode"); if (s != null) { if ("SILENT_MODE".equals (s)) { mode = SILENT_MODE; } else if ("FILE_MODE".equals (s)) { mode = FILE_MODE; } else if ("NET_MODE".equals (s)) { mode = NET_MODE; } else if ("MEX_MODE".equals (s)) { mode = MEX_MODE; } else if ("PRINT_MODE".equals (s)) { mode = PRINT_MODE; } else if ("J2EE_MSG_MODE".equals (s)) { mode = J2EE_MSG_MODE; } else if ("J2SE_LOG_MODE".equals (s)) { mode = J2SE_LOG_MODE; } else { try { mode = Integer.parseInt (s); } catch (NumberFormatException e) { mode = SILENT_MODE; } } } else { mode = SILENT_MODE; } startLogger ("asdf"); } public void startLogger( ) throws UnSupportedLoggerException { if ( mode == SILENT_MODE || mode == PRINT_MODE ) { //nativeNetInit( ); return; } throw new UnSupportedLoggerException( "Target Not Allowed" ); } /* accept the host or file to log to. */ public void startLogger( String t ) throws UnSupportedLoggerException { target = t; /* if ( mode == NET_MODE ) { nativeNetInit( ); } if ( nativeInit( ) ) { throw new UnSupportedLoggerException( "Port initializion failed" ); } */ return; } public void finalize() { /* if ( mode == NET_MODE ) { nativeNetFinalize( ); } nativeFinalize(); */ mode = SILENT_MODE; target = null; } public void filewrite( String s ) { try { RandomAccessFile w = new RandomAccessFile( target, "rw" );; w.seek( w.length() ); w.writeBytes( s ); w.close(); } catch ( Exception e ) { System.out.println("Debug output file write failed"); } } public boolean report( String s) { if ( mode == NET_MODE ) { // return( nativeNetReportln( s ) ); } else if ( mode == PRINT_MODE ) { System.out.println( s ); return( true ); } else if ( mode == MEX_MODE ) { // return( nativeMexReport( s ) ); } else if ( mode == SILENT_MODE ) { return( true ); } else if ( mode == FILE_MODE ) { filewrite( s ); } else if ( mode == J2EE_MSG_MODE ) { return( false ); } else if (mode == J2SE_LOG_MODE) { java.util.logging.Logger.getLogger ("javax.comm").fine (s); return (true); } return( false ); } public boolean reportln( ) { boolean b; if ( mode == NET_MODE ) { // b= nativeNetReportln( "\n" ); // return(b); } else if ( mode == PRINT_MODE ) { System.out.println( ); return( true ); } else if ( mode == MEX_MODE ) { // b = nativeMexReportln( "\n" ); // return(b); } else if ( mode == SILENT_MODE ) { return( true ); } else if ( mode == FILE_MODE ) { filewrite( "\n" ); } else if ( mode == J2EE_MSG_MODE ) { return( false ); } return( false ); } public boolean reportln( String s) { boolean b; if ( mode == NET_MODE ) { // b= nativeNetReportln( s + "\n" ); // return(b); } else if ( mode == PRINT_MODE ) { System.out.println( s ); return( true ); } else if ( mode == MEX_MODE ) { // b = nativeMexReportln( s + "\n" ); // return(b); } else if ( mode == SILENT_MODE ) { return( true ); } else if ( mode == FILE_MODE ) { filewrite( s + "\n" ); } else if ( mode == J2EE_MSG_MODE ) { return( false ); } else if (mode == J2SE_LOG_MODE) { return (true); } return( false ); } /* private native boolean nativeInit( ); private native void nativeFinalize(); */ /* open and close the socket */ /* private native boolean nativeNetInit( ); private native void nativeNetFinalize(); */ /* dumping to a remote machine */ /* public native boolean nativeNetReport( String s ); public native boolean nativeNetReportln( String s ); */ /* specific to Matlab */ /* public native boolean nativeMexReport( String s ); public native boolean nativeMexReportln( String s ); */ }
lgpl-2.1
geotools/geotools
modules/plugin/jdbc/jdbc-postgis/src/test/java/org/geotools/data/postgis/PostgisFeatureLockingOnlineTest.java
973
/* * GeoTools - The Open Source Java GIS Toolkit * http://geotools.org * * (C) 2002-2009, 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.data.postgis; import org.geotools.jdbc.JDBCFeatureLockingOnlineTest; import org.geotools.jdbc.JDBCTestSetup; public class PostgisFeatureLockingOnlineTest extends JDBCFeatureLockingOnlineTest { @Override protected JDBCTestSetup createTestSetup() { return new PostGISTestSetup(); } }
lgpl-2.1
EgorZhuk/pentaho-reporting
libraries/libloader/src/main/java/org/pentaho/reporting/libraries/resourceloader/loader/raw/RawResourceLoader.java
6293
/* * 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) 2006 - 2013 Pentaho Corporation and Contributors. All rights reserved. */ package org.pentaho.reporting.libraries.resourceloader.loader.raw; import org.pentaho.reporting.libraries.resourceloader.ResourceData; import org.pentaho.reporting.libraries.resourceloader.ResourceException; import org.pentaho.reporting.libraries.resourceloader.ResourceKey; import org.pentaho.reporting.libraries.resourceloader.ResourceKeyCreationException; import org.pentaho.reporting.libraries.resourceloader.ResourceKeyData; import org.pentaho.reporting.libraries.resourceloader.ResourceKeyUtils; import org.pentaho.reporting.libraries.resourceloader.ResourceLoader; import org.pentaho.reporting.libraries.resourceloader.ResourceLoadingException; import java.net.URL; import java.util.HashMap; import java.util.Map; /** * Creation-Date: 12.04.2006, 15:19:03 * * @author Thomas Morgner */ public class RawResourceLoader implements ResourceLoader { public static final String SCHEMA_NAME = RawResourceLoader.class.getName(); public RawResourceLoader() { } /** * Checks, whether this resource loader implementation was responsible for creating this key. * * @param key * @return */ public boolean isSupportedKey( final ResourceKey key ) { if ( SCHEMA_NAME.equals( key.getSchema() ) ) { return true; } return false; } /** * Creates a new resource key from the given object and the factory keys. * * @param value * @param factoryKeys * @return the created key. * @throws org.pentaho.reporting.libraries.resourceloader.ResourceKeyCreationException if creating the key failed. */ public ResourceKey createKey( final Object value, final Map factoryKeys ) throws ResourceKeyCreationException { if ( value instanceof byte[] == false ) { return null; } return new ResourceKey( SCHEMA_NAME, value, factoryKeys ); } /** * Derives a new resource key from the given key. If neither a path nor new factory-keys are given, the parent key is * returned. * * @param parent the parent * @param path the derived path (can be null). * @param factoryKeys the optional factory keys (can be null). * @return the derived key. * @throws org.pentaho.reporting.libraries.resourceloader.ResourceKeyCreationException if the key cannot be derived * for any reason. */ public ResourceKey deriveKey( final ResourceKey parent, final String path, final Map factoryKeys ) throws ResourceKeyCreationException { if ( path != null ) { throw new ResourceKeyCreationException( "Unable to derive key for new path." ); } if ( isSupportedKey( parent ) == false ) { throw new ResourceKeyCreationException( "Assertation: Unsupported parent key type" ); } if ( factoryKeys == null ) { return parent; } final HashMap map = new HashMap(); map.putAll( parent.getFactoryParameters() ); map.putAll( factoryKeys ); return new ResourceKey( parent.getSchema(), parent.getIdentifier(), map ); } public URL toURL( final ResourceKey key ) { // not supported .. return null; } public ResourceData load( final ResourceKey key ) throws ResourceLoadingException { if ( isSupportedKey( key ) == false ) { throw new ResourceLoadingException( "The key type is not supported." ); } return new RawResourceData( key ); } /** * Creates a String version of the resource key that can be used to generate a new ResourceKey object via * deserialization * * @param bundleKey * @param key */ public String serialize( final ResourceKey bundleKey, final ResourceKey key ) throws ResourceException { // Validate the parameter if ( key == null ) { throw new NullPointerException( "The ResourceKey can not be null" ); } if ( isSupportedKey( key ) == false ) { throw new IllegalArgumentException( "Key format is not recognized." ); } if ( !( key.getIdentifier() instanceof byte[] ) ) { throw new IllegalArgumentException( "ResourceKey is invalid - identifier is not a byte[] object" ); } final byte[] data = (byte[]) key.getIdentifier(); final char[] cdata = new char[ data.length ]; for ( int i = 0; i < data.length; i++ ) { cdata[ i ] = (char) ( data[ i ] & 0xFF ); } return ResourceKeyUtils.createStringResourceKey ( String.valueOf( key.getSchema() ), new String( cdata ), key.getFactoryParameters() ); } /** * Parses the input string and returns a newly created ResourceKey based on the string data */ public ResourceKey deserialize( final ResourceKey bundleKey, String stringKey ) throws ResourceKeyCreationException { // Parse the data final ResourceKeyData keyData = ResourceKeyUtils.parse( stringKey ); // Validate the data if ( SCHEMA_NAME.equals( keyData.getSchema() ) == false ) { throw new ResourceKeyCreationException( "Serialized version of key does not contain correct schema" ); } final String identifier = keyData.getIdentifier(); final char[] chars = identifier.toCharArray(); final byte[] data = new byte[ chars.length ]; for ( int i = 0; i < chars.length; i++ ) { data[ i ] = (byte) chars[ i ]; } return createKey( data, keyData.getFactoryParameters() ); } public boolean isSupportedDeserializer( String data ) { return SCHEMA_NAME.equals( ResourceKeyUtils.readSchemaFromString( data ) ); } }
lgpl-2.1
Trumpet63/Rhythm-Project-2
Zero/src/song/Note.java
665
package song; /** * Class that stores information describing a note. */ public class Note { public double time; // time position in seconds of the note in the song public int measurePosition; // position in the measure the note was a part of public int measureSize; // size of the measure the note was a part of public int columnNumber; // the track or column to which the note belongs public double bpm; // the bpm of the song at the note's time @Override public String toString() { return String.format("%-10.4f %-16d %-12d %-13d %-13.4f", time, measurePosition, measureSize, columnNumber, bpm); } }
lgpl-2.1
FRC-RoboLib/RoboLib-MemAccess
src/org/usfirst/frc/team1554/lib/memaccess/storage/ByteHandler.java
3159
/*================================================================================================== RoboLib-MemAccess - Native Memory Access for RoboLib Copyright (C) 2015 Matthew Crocco 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 =================================================================================================*/ package org.usfirst.frc.team1554.lib.memaccess.storage; import org.usfirst.frc.team1554.lib.common.exception.RobotReflectionException; /** * Created by Matthew on 2/23/2015. */ public abstract class ByteHandler { public static ByteHandler get() { ByteHandler bh; try { bh = unsafeByteHandler(); } catch (Exception e) { bh = safeByteHandler(); } return bh; } private static ByteHandler safeByteHandler() { return new BitShiftByteHandler(); } private static ByteHandler unsafeByteHandler() throws RobotReflectionException { try { Class<? extends ByteHandler> klass = ByteHandler.class.getClassLoader() .loadClass(ByteHandler.class.getPackage().getName() + ".UnsafeByteHandler") .asSubclass(ByteHandler.class); return klass.newInstance(); } catch (Exception e) { throw new RobotReflectionException("Failed to load UnsafeByteHandler!", e); } } public abstract boolean isUnsafe(); public abstract byte getByte(byte[] data, int offset); public abstract void putByte(byte[] data, int offset, byte val); public abstract short getUnsignedByte(byte[] data, int offset); public abstract void putUnsignedByte(byte[] data, int offset, short val); public abstract short getShort(byte[] data, int offset); public abstract void putShort(byte[] data, int offset, short val); public abstract int getUnsignedShort(byte[] data, int offset); public abstract void putUnsignedShort(byte[] data, int offset, int val); public abstract int getInt(byte[] data, int offset); public abstract void putInt(byte[] data, int offset, int value); public abstract long getUnsignedInt(byte[] data, int offset); public abstract void putUnsignedInt(byte[] data, int offset, long value); public abstract long getLong(byte[] data, int offset); public abstract void putLong(byte[] data, int offset, long value); public abstract void copy(byte[] src, int srcOffset, byte[] dst, int dstOffset, int length); }
lgpl-2.1
Foeskes/Flaux-Mod
src/main/java/com/foeskes/flaux/untils/weapon/WeaponDamageTier2.java
2043
package com.foeskes.flaux.untils.weapon; import com.foeskes.flaux.untils.FlauxHelper; import net.minecraft.entity.EntityLivingBase; import net.minecraft.entity.player.EntityPlayer; public class WeaponDamageTier2 implements IWeaponTierDamage { @Override public void doDamageForLevel1(EntityLivingBase attacker, EntityLivingBase entity, float weaponLevel, float defaultDamage, float drainDamage) { if (entity != null) { if (attacker == null && entity != attacker) entity.attackEntityFrom(FlauxHelper.flaux2, defaultDamage); else if (attacker instanceof EntityLivingBase) { entity.attackEntityFrom(FlauxHelper.causePlayerDamage((EntityLivingBase) attacker), defaultDamage); } } } @Override public void doDamageForLevel2(EntityLivingBase attacker, EntityLivingBase entity, float weaponLevel, float defaultDamage, float drainDamage) { if (entity != null) { if (attacker == null && entity != attacker) entity.attackEntityFrom(FlauxHelper.flaux2, defaultDamage * 1.65f); else if (attacker instanceof EntityLivingBase) { entity.attackEntityFrom(FlauxHelper.causePlayerDamage((EntityLivingBase) attacker), defaultDamage * 1.65f); } } } @Override public void doDamageForLevel3(EntityLivingBase attacker, EntityLivingBase entity, float weaponLevel, float defaultDamage, float drainDamage) { if (attacker == null && entity != attacker) FlauxHelper.drainHealth(entity, (int) drainDamage, (attacker instanceof EntityPlayer)); } @Override public void doDamageForLevel4(EntityLivingBase attacker, EntityLivingBase entity, float weaponLevel, float defaultDamage, float drainDamage) { doDamageForLevel3(attacker, entity, weaponLevel, defaultDamage, drainDamage); } @Override public void doDamageForLevel5(EntityLivingBase attacker, EntityLivingBase entity, float weaponLevel, float defaultDamage, float drainDamage) { doDamageForLevel3(attacker, entity, weaponLevel, defaultDamage, drainDamage); } @Override public int getMaxLevel() { return 3; } }
lgpl-2.1
raedle/champanager
src/java/org/championship/manager/util/VectorUtils.java
562
package org.championship.manager.util; import java.util.Vector; import java.util.Collection; // @todo document me! /** * VectorUtils. * <p/> * User: rro * Date: 31.07.2005 * Time: 18:20:27 * * @author Roman R&auml;dle * @version $Id: VectorUtils.java,v 1.1 2006/04/05 09:09:14 raedler Exp $ */ public class VectorUtils { public static Vector<Object> collectionToVector(Collection list) { Vector<Object> vector = new Vector<Object>(); for (Object o : list) { vector.add(o); } return vector; } }
lgpl-2.1
opensagres/xdocreport.eclipse
dynaresume/org.dynaresume.eclipse.ui/src/org/dynaresume/eclipse/ui/viewers/HobbyLabelProvider.java
927
package org.dynaresume.eclipse.ui.viewers; import org.dynaresume.domain.hr.Hobby; import org.dynaresume.eclipse.ui.internal.ImageResources; import org.eclipse.jface.viewers.LabelProvider; import org.eclipse.swt.graphics.Image; public class HobbyLabelProvider extends LabelProvider { private static HobbyLabelProvider instance; public static HobbyLabelProvider getInstance() { synchronized (HobbyLabelProvider.class) { if (instance == null) { instance = new HobbyLabelProvider(); } return instance; } } @Override public String getText(Object element) { if (element instanceof Hobby) { return ((Hobby) element).getLabel(); } return super.getText(element); } @Override public Image getImage(Object element) { if (element instanceof Hobby) { return ImageResources.getImage(ImageResources.IMG_HOBBIES_16); } return super.getImage(element); } }
lgpl-2.1
alesharik/SimplyInstruments
src/main/java/SimplyTools/patterns/Pattern.java
1166
package SimplyTools.patterns; import net.minecraft.item.Item; import net.minecraft.util.ResourceLocation; public class Pattern extends Item { private PatternModel model = null; private ResourceLocation texture = null; private ResourceLocation texturePreview = null; private boolean[] matrix = new boolean[9]; public Pattern() { this.setMaxDamage(0); this.setMaxStackSize(16); } public Item setModel(PatternModel model) { this.model = model; return this; } public PatternModel getModel() { return this.model; } public Item setTextureName(String textureName) { this.texture = new ResourceLocation(textureName); return this; } public ResourceLocation getTexture() { return this.texture; } public Item setUnlocalizedName(String name) { this.setUnlocalizedName("SIPattern" + name); return this; } public Item setMatrix(boolean[] matrix) { this.matrix = matrix; return this; } public boolean[] getMatrix() { return this.matrix; } public Item setTexturePrewiev(ResourceLocation tp) { this.texturePreview = tp; return this; } public ResourceLocation getTexturePrewiev() { return this.texturePreview; } }
lgpl-2.1
shabanovd/exist
src/org/exist/util/serializer/json/JSONWriter.java
8384
package org.exist.util.serializer.json; import java.io.IOException; import java.io.Writer; import java.util.Properties; import java.util.Stack; import javax.xml.transform.TransformerException; import org.apache.log4j.Logger; import org.exist.dom.QName; import org.exist.storage.serializers.EXistOutputKeys; import org.exist.util.serializer.XMLWriter; /** * This class plugs into eXist's serialization to transform XML to JSON. It is used * if the serialization property "method" is set to "json". * * The following rules apply for the mapping of XML to JSON: * * <ul> * <li>The root element will be absorbed, i.e. &lt;root&gt;text&lt;/root&gt; becomes "root".</li> * <li>Sibling elements with the same name are added to an array.</li> * <li>If an element has attribute and text content, the text content becomes a * property, e.g. '#text': 'my text'.</li> * <li>In mixed content nodes, text nodes will be dropped.</li> * <li>An empty element becomes 'null', i.e. &lt;e/&gt; becomes {"e": null}.</li> * <li>An element with a single text child becomes a property with the value of the text child, i.e. * &lt;e&gt;text&lt;/e&gt; becomes {"e": "text"}<li> * <li>An element with name "json:value" is serialized as a simple value, not an object, i.e. * &lt;json:value&gt;value&lt;/json:value&gt; just becomes "value".</li> * </ul> * * Namespace prefixes will be dropped from element and attribute names by default. If the serialization * property {@link EXistOutputKeys#JSON_OUTPUT_NS_PREFIX} is set to "yes", namespace prefixes will be * added to the resulting JSON property names, replacing the ":" with a "_", i.e. &lt;foo:node&gt; becomes * "foo_node". * * If an attribute json:array is present on an element it will always be serialized as an array, even if there * are no other sibling elements with the same name. * * The attribute json:literal indicates that the element's text content should be serialized literally. This is * handy for writing boolean or numeric values. By default, text content is serialized as a Javascript string. * * @author wolf * */ public class JSONWriter extends XMLWriter { private final static Logger LOG = Logger.getLogger(JSONWriter.class); private final static String ARRAY = "array"; private final static String LITERAL = "literal"; private final static String VALUE = "value"; private final static String NAME = "name"; private final static String JSON_ARRAY = "json:" + ARRAY; private final static String JSON_LITERAL = "json:" + LITERAL; private final static String JSON_VALUE = "json:" + VALUE; private final static String JSON_NAME = "json:" + NAME; public final static String JASON_NS = "http://www.json.org"; protected JSONNode root; protected final Stack<JSONObject> stack = new Stack<JSONObject>(); protected boolean useNSPrefix = false; protected boolean prefixAttributes = false; private String jsonp = null; public JSONWriter() { // empty } public JSONWriter(final Writer writer) { super(writer); } @Override protected void resetObjectState() { super.resetObjectState(); stack.clear(); root = null; } @Override public void setOutputProperties(final Properties properties) { super.setOutputProperties(properties); final String useNSProp = properties.getProperty(EXistOutputKeys.JSON_OUTPUT_NS_PREFIX, "no"); useNSPrefix = useNSProp.equalsIgnoreCase("yes"); final String prefixForAttr = properties.getProperty(EXistOutputKeys.JSON_PREFIX_ATTRIBUTES, "no"); prefixAttributes = prefixForAttr.equalsIgnoreCase("yes"); jsonp = properties.getProperty(EXistOutputKeys.JSONP); } @Override public void startDocument() throws TransformerException { } @Override public void endDocument() throws TransformerException { try { if(root != null) { if(jsonp != null) { getWriter().write(jsonp + "("); } root.serialize(getWriter(), true); if(jsonp != null) { getWriter().write(")"); } } } catch(final IOException ioe) { LOG.error(ioe.getMessage(), ioe); } } @Override public void startElement(final String namespaceURI, final String localName, final String qname) throws TransformerException { if(qname.equals(JSON_VALUE)) { processStartValue(); } else if(useNSPrefix) { processStartElement(qname.replace(':', '_'), false); } else { processStartElement(QName.extractLocalName(qname), false); } } @Override public void startElement(final QName qname) throws TransformerException { if(JASON_NS.equals(qname.getNamespaceURI()) && VALUE.equals(qname.getLocalName())) { processStartValue(); } else if(useNSPrefix) { processStartElement(qname.getPrefix() + '_' + qname.getLocalName(), false); } else { processStartElement(qname.getLocalName(), false); } } private void processStartElement(final String localName, boolean simpleValue) { final JSONObject obj = new JSONObject(localName); if(root == null) { root = obj; stack.push(obj); } else { final JSONObject parent = stack.peek(); parent.addObject(obj); stack.push(obj); } } private void processStartValue() throws TransformerException { // a json:value is stored as an unnamed object final JSONObject obj = new JSONObject(); if(root == null) { root = obj; stack.push(obj); } else { final JSONObject parent = stack.peek(); parent.addObject(obj); stack.push(obj); } } @Override public void endElement(final String namespaceUri, final String localName, final String qname) throws TransformerException { stack.pop(); } @Override public void endElement(final QName qname) throws TransformerException { stack.pop(); } @Override public void namespace(final String prefix, final String nsURI) throws TransformerException { } @Override public void attribute(final String qname, final String value) throws TransformerException { final JSONObject parent = stack.peek(); if(qname.equals(JSON_ARRAY)) { parent.setSerializationType(JSONNode.SerializationType.AS_ARRAY); } else if(qname.equals(JSON_LITERAL)) { parent.setSerializationType(JSONNode.SerializationType.AS_LITERAL); } else if(qname.equals(JSON_NAME)) { parent.setName(value); } else { final String name = prefixAttributes ? "@" + qname : qname; final JSONSimpleProperty obj = new JSONSimpleProperty(name, value); parent.addObject(obj); } } @Override public void attribute(final QName qname, final String value) throws TransformerException { attribute(qname.toString(), value); } @Override public void characters(final CharSequence chars) throws TransformerException { final JSONObject parent = stack.peek(); final JSONNode value = new JSONValue(chars.toString()); value.setSerializationType(parent.getSerializationType()); parent.addObject(value); } @Override public void characters(final char[] ch, final int start, final int len) throws TransformerException { characters(new String(ch, start, len)); } @Override public void processingInstruction(final String target, final String data) throws TransformerException { // skip } @Override public void comment(final CharSequence data) throws TransformerException { // skip } @Override public void cdataSection(final char[] ch, final int start, final int len) throws TransformerException { // treat as string content characters(ch, start, len); } @Override public void documentType(final String name, final String publicId, final String systemId) throws TransformerException { // skip } }
lgpl-2.1
tekkies/jcommon-serialdate-refactor
source/org/jfree/ui/about/LibraryTableModel.java
5115
/* ======================================================================== * JCommon : a free general purpose class library for the Java(tm) platform * ======================================================================== * * (C) Copyright 2000-2005, by Object Refinery Limited and Contributors. * * Project Info: http://www.jfree.org/jcommon/index.html * * 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. * * [Java is a trademark or registered trademark of Sun Microsystems, Inc. * in the United States and other countries.] * * ---------------------- * LibraryTableModel.java * ---------------------- * (C) Copyright 2002-2004, by Object Refinery Limited. * * Original Author: David Gilbert (for Object Refinery Limited); * Contributor(s): -; * * $Id: LibraryTableModel.java,v 1.4 2005/11/16 15:58:41 taqua Exp $ * * Changes * ------- * 28-Feb-2002 : Version 1 (DG); * 15-Mar-2002 : Modified to use ResourceBundle for elements that require localisation (DG); * 08-Oct-2002 : Fixed errors reported by Checkstyle (DG); * */ package org.jfree.ui.about; import java.util.List; import java.util.ResourceBundle; import javax.swing.table.AbstractTableModel; import org.jfree.base.Library; /** * A table model containing a list of libraries used in a project. * <P> * Used in the LibraryPanel class. * * @author David Gilbert */ public class LibraryTableModel extends AbstractTableModel { /** Storage for the libraries. */ private List libraries; /** Localised name column label. */ private String nameColumnLabel; /** Localised version column label. */ private String versionColumnLabel; /** Localised licence column label. */ private String licenceColumnLabel; /** Localised info column label. */ private String infoColumnLabel; /** * Constructs a LibraryTableModel. * * @param libraries the libraries. */ public LibraryTableModel(final List libraries) { this.libraries = libraries; final String baseName = "org.jfree.ui.about.resources.AboutResources"; final ResourceBundle resources = ResourceBundle.getBundle(baseName); this.nameColumnLabel = resources.getString("libraries-table.column.name"); this.versionColumnLabel = resources.getString("libraries-table.column.version"); this.licenceColumnLabel = resources.getString("libraries-table.column.licence"); this.infoColumnLabel = resources.getString("libraries-table.column.info"); } /** * Returns the number of rows in the table model. * * @return the number of rows. */ public int getRowCount() { return this.libraries.size(); } /** * Returns the number of columns in the table model. In this case, there are always four * columns (name, version, licence and other info). * * @return the number of columns in the table model. */ public int getColumnCount() { return 4; } /** * Returns the name of a column in the table model. * * @param column the column index (zero-based). * * @return the name of the specified column. */ public String getColumnName(final int column) { String result = null; switch (column) { case 0: result = this.nameColumnLabel; break; case 1: result = this.versionColumnLabel; break; case 2: result = this.licenceColumnLabel; break; case 3: result = this.infoColumnLabel; break; } return result; } /** * Returns the value for a cell in the table model. * * @param row the row index (zero-based). * @param column the column index (zero-based). * * @return the value. */ public Object getValueAt(final int row, final int column) { Object result = null; final Library library = (Library) this.libraries.get(row); if (column == 0) { result = library.getName(); } else if (column == 1) { result = library.getVersion(); } else if (column == 2) { result = library.getLicenceName(); } else if (column == 3) { result = library.getInfo(); } return result; } }
lgpl-2.1
geotools/geotools
modules/ogc/net.opengis.wcs/src/net/opengis/wcs11/CoverageDescriptionsType.java
1651
/** * <copyright> * </copyright> * * $Id$ */ package net.opengis.wcs11; import org.eclipse.emf.common.util.EList; import org.eclipse.emf.ecore.EObject; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Coverage Descriptions Type</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * <ul> * <li>{@link net.opengis.wcs11.CoverageDescriptionsType#getCoverageDescription <em>Coverage Description</em>}</li> * </ul> * </p> * * @see net.opengis.wcs11.Wcs111Package#getCoverageDescriptionsType() * @model extendedMetaData="name='CoverageDescriptions_._type' kind='elementOnly'" * @generated */ public interface CoverageDescriptionsType extends EObject { /** * Returns the value of the '<em><b>Coverage Description</b></em>' containment reference list. * The list contents are of type {@link net.opengis.wcs11.CoverageDescriptionType}. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Coverage Description</em>' containment reference list isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Coverage Description</em>' containment reference list. * @see net.opengis.wcs11.Wcs111Package#getCoverageDescriptionsType_CoverageDescription() * @model type="net.opengis.wcs11.CoverageDescriptionType" containment="true" required="true" * extendedMetaData="kind='element' name='CoverageDescription' namespace='##targetNamespace'" * @generated */ EList getCoverageDescription(); } // CoverageDescriptionsType
lgpl-2.1
mbatchelor/pentaho-reporting
engine/core/src/main/java/org/pentaho/reporting/engine/classic/core/modules/parser/bundle/data/ParameterAttributeReadHandler.java
1810
/* * 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) 2001 - 2013 Object Refinery Ltd, Hitachi Vantara and Contributors.. All rights reserved. */ package org.pentaho.reporting.engine.classic.core.modules.parser.bundle.data; import org.pentaho.reporting.libraries.xmlns.parser.StringReadHandler; import org.xml.sax.Attributes; import org.xml.sax.SAXException; public class ParameterAttributeReadHandler extends StringReadHandler { private String namespace; private String name; public ParameterAttributeReadHandler() { } protected void startParsing( final Attributes attrs ) throws SAXException { super.startParsing( attrs ); name = attrs.getValue( getUri(), "name" ); if ( name == null ) { throw new SAXException( "Required attribute 'name' is missing." ); } namespace = attrs.getValue( getUri(), "namespace" ); if ( namespace == null ) { throw new SAXException( "Required attribute 'namespace' is missing." ); } } public String getNamespace() { return namespace; } public String getName() { return name; } }
lgpl-2.1
deegree/deegree3
deegree-core/deegree-core-geometry/src/main/java/org/deegree/geometry/standard/composite/DefaultCompositeSolid.java
6036
//$HeadURL$ /*---------------------------------------------------------------------------- This file is part of deegree, http://deegree.org/ Copyright (C) 2001-2009 by: Department of Geography, University of Bonn and lat/lon GmbH This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation; either version 2.1 of the License, or (at your option) any later version. This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA Contact information: lat/lon GmbH Aennchenstr. 19, 53177 Bonn Germany http://lat-lon.de/ Department of Geography, University of Bonn Prof. Dr. Klaus Greve Postfach 1147, 53001 Bonn Germany http://www.geographie.uni-bonn.de/deegree/ e-mail: info@deegree.org ----------------------------------------------------------------------------*/ package org.deegree.geometry.standard.composite; import java.util.Collection; import java.util.Iterator; import java.util.List; import java.util.ListIterator; import org.deegree.commons.uom.Measure; import org.deegree.commons.uom.Unit; import org.deegree.cs.coordinatesystems.ICRS; import org.deegree.geometry.composite.CompositeSolid; import org.deegree.geometry.precision.PrecisionModel; import org.deegree.geometry.primitive.Solid; import org.deegree.geometry.primitive.Surface; import org.deegree.geometry.standard.AbstractDefaultGeometry; /** * Default implementation of {@link CompositeSolid}. * * @author <a href="mailto:schneider@lat-lon.de">Markus Schneider </a> * @author last edited by: $Author$ * * @version $Revision$, $Date$ */ public class DefaultCompositeSolid extends AbstractDefaultGeometry implements CompositeSolid { private List<Solid> memberSolids; /** * Creates a new {@link DefaultCompositeSolid} from the given parameters. * * @param id * identifier, may be null * @param crs * coordinate reference system, may be null * @param pm * precision model, may be null * @param memberSolids * */ public DefaultCompositeSolid( String id, ICRS crs, PrecisionModel pm, List<Solid> memberSolids ) { super( id, crs, pm ); this.memberSolids = memberSolids; } @Override public int getCoordinateDimension() { return memberSolids.get( 0 ).getCoordinateDimension(); } @Override public GeometryType getGeometryType() { return GeometryType.PRIMITIVE_GEOMETRY; } @Override public PrimitiveType getPrimitiveType() { return PrimitiveType.Solid; } @Override public SolidType getSolidType() { return SolidType.CompositeSolid; } @Override public Surface getExteriorSurface() { // TODO Auto-generated method stub return null; } @Override public List<Surface> getInteriorSurfaces() { // TODO Auto-generated method stub return null; } @Override public Measure getArea( Unit requestedBaseUnit ) { throw new UnsupportedOperationException(); } @Override public Measure getVolume( Unit requestedBaseUnit ) { throw new UnsupportedOperationException(); } // ----------------------------------------------------------------------- // delegate methods for List<Solid> // ----------------------------------------------------------------------- public void add( int index, Solid element ) { memberSolids.add( index, element ); } public boolean add( Solid e ) { return memberSolids.add( e ); } public boolean addAll( Collection<? extends Solid> c ) { return memberSolids.addAll( c ); } public boolean addAll( int index, Collection<? extends Solid> c ) { return memberSolids.addAll( index, c ); } public void clear() { memberSolids.clear(); } public boolean contains( Object o ) { return memberSolids.contains( o ); } public boolean containsAll( Collection<?> c ) { return memberSolids.containsAll( c ); } public Solid get( int index ) { return memberSolids.get( index ); } public int indexOf( Object o ) { return memberSolids.indexOf( o ); } public boolean isEmpty() { return memberSolids.isEmpty(); } public Iterator<Solid> iterator() { return memberSolids.iterator(); } public int lastIndexOf( Object o ) { return memberSolids.lastIndexOf( o ); } public ListIterator<Solid> listIterator() { return memberSolids.listIterator(); } public ListIterator<Solid> listIterator( int index ) { return memberSolids.listIterator( index ); } public Solid remove( int index ) { return memberSolids.remove( index ); } public boolean remove( Object o ) { return memberSolids.remove( o ); } public boolean removeAll( Collection<?> c ) { return memberSolids.removeAll( c ); } public boolean retainAll( Collection<?> c ) { return memberSolids.retainAll( c ); } public Solid set( int index, Solid element ) { return memberSolids.set( index, element ); } public int size() { return memberSolids.size(); } public List<Solid> subList( int fromIndex, int toIndex ) { return memberSolids.subList( fromIndex, toIndex ); } public Object[] toArray() { return memberSolids.toArray(); } public <T> T[] toArray( T[] a ) { return memberSolids.toArray( a ); } }
lgpl-2.1
EgorZhuk/pentaho-reporting
engine/core/src/main/java/org/pentaho/reporting/engine/classic/core/style/css/StyleReference.java
1569
/*! * 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-2013 Pentaho Corporation.. All rights reserved. */ package org.pentaho.reporting.engine.classic.core.style.css; /** * There are two kinds of style-references. Type one simply references a inline style, which has no style-source. The * second one is a external stylesheet that has a style-source, and possibly has a style-content as well. * * @author : Thomas Morgner */ public class StyleReference { public static final int LINK = 0; public static final int INLINE = 1; private String styleContent; private int type; public StyleReference( final int type, final String styleContent ) { this.type = type; this.styleContent = styleContent; } public int getType() { return type; } public String getStyleContent() { return styleContent; } }
lgpl-2.1
geotools/geotools
modules/ogc/net.opengis.wcs/src/net/opengis/wcs10/validation/LonLatEnvelopeBaseTypeValidator.java
559
/** * <copyright> * </copyright> * * $Id$ */ package net.opengis.wcs10.validation; /** * A sample validator interface for {@link net.opengis.wcs10.LonLatEnvelopeBaseType}. * This doesn't really do anything, and it's not a real EMF artifact. * It was generated by the org.eclipse.emf.examples.generator.validator plug-in to illustrate how EMF's code generator can be extended. * This can be disabled with -vmargs -Dorg.eclipse.emf.examples.generator.validator=false. */ public interface LonLatEnvelopeBaseTypeValidator { boolean validate(); }
lgpl-2.1
jeroenvanmaanen/leia
leia-api/src/main/java/org/leialearns/api/session/Root.java
4545
package org.leialearns.api.session; import org.leialearns.api.interaction.Alphabet; import org.leialearns.api.interaction.InteractionContext; import org.leialearns.api.model.expectation.Expectation; import org.leialearns.api.model.expectation.Fraction; /** * Defines the singleton that contains the objects that are at least partially persisted through the ORM framework, * but have no owner that is also persistent. */ public interface Root { /** * Creates a new interaction context instance. The URIs for the alphabets and the structure are derived from * the given URI. * @param interactionContextURI The URI that identifies the new interaction context * @return A new interaction context instance */ InteractionContext createInteractionContext(String interactionContextURI); /** * Creates a new interaction context instance. * @param interactionContextURI The URI that identifies the new interaction context * @param actionsURI The URI that identifies the alphabet of actions * @param responsesURI The URI that identifies the alphabet of actions * @param structureURI The URI that identifies the tree of interaction histories * @return A new interaction context instance */ InteractionContext createInteractionContext(String interactionContextURI, String actionsURI, String responsesURI, String structureURI); /** * Creates a session that can be used to create and/or obtain {@link org.leialearns.api.model.Version}s of * various types of models. * @param interactionContextURI The URI that identifies the interaction context * @return A new session instance */ Session createSession(String interactionContextURI); /** * Creates a session that can be used to create and/or obtain {@link org.leialearns.api.model.Version}s of * various types of models. * @param interactionContext The interaction context for the new session * @return A new session instance */ Session createSession(InteractionContext interactionContext); /** * Returns all alphabets that are available in the data store. * @return All alphabets that are available in the data store */ Alphabet.Iterable findAlphabets(); /** * Creates a new persistent fraction object. * @param index The index of the new fraction * @param numerator The numerator of the new object * @param denominator The denominator of the new object * @return The new fraction object */ @SuppressWarnings("unused") Fraction createFraction(long index, long numerator, long denominator); /** * Returns a persistent fraction object, creates a new one if necessary. * @param index The index of the fraction * @param numerator The numerator of the fraction * @param denominator The denominator of the fraction * @return The requested fraction object */ @SuppressWarnings("unused") Fraction findOrCreateFraction(long index, long numerator, long denominator); /** * Returns a persistent fraction object, creates a new one if necessary. * @param fraction The (probably transient) fraction to make persistent * @return The requested fraction object */ Fraction findOrCreateFraction(Fraction fraction); /** * Creates a new persistent fraction object. * @param index The index of the new fraction * @param numerator The numerator of the new object * @param denominator The denominator of the new object * @param inOracle Indication of whether the new fraction is part of the oracle or not * @return The new fraction object */ Fraction createFraction(long index, long numerator, long denominator, boolean inOracle); /** * Returns all fraction objects in the data store. * @return All fraction objects in the data store */ Fraction.Iterable findFractions(); /** * Returns the fraction object with the given index. * @param index The index of the requested fraction * @return The requested fraction */ Fraction findFraction(long index); /** * Creates a new transient fraction object. * @param index The index of the new fraction * @param numerator The numerator of the new object * @param denominator The denominator of the new object * @return The new fraction object */ Fraction createTransientFraction(long index, long numerator, long denominator); Expectation createExpectation(); }
lgpl-2.1
heiko-braun/agenda
src/test/java/org/jboss/metrics/agenda/TaskDefinitionTest.java
840
package org.jboss.metrics.agenda; import static java.util.concurrent.TimeUnit.*; import static org.junit.Assert.assertEquals; import org.junit.Test; public class TaskDefinitionTest { @Test(expected = IllegalArgumentException.class) public void illegalUnitNano() { new TaskDefinition("foo", "bar", 1, NANOSECONDS); } @Test(expected = IllegalArgumentException.class) public void illegalUnitMicro() { new TaskDefinition("foo", "bar", 1, MICROSECONDS); } @Test(expected = IllegalArgumentException.class) public void illegalUnitMilli() { new TaskDefinition("foo", "bar", 1, MILLISECONDS); } @Test public void defaultInterval() { TaskDefinition taskDefinition = new TaskDefinition("foo", "bar", 1); assertEquals(SECONDS, taskDefinition.getUnit()); } }
lgpl-2.1
fjalvingh/domui
to.etc.domui/src/main/java/to/etc/domui/testsupport/ui/DateInputTestPage.java
2434
package to.etc.domui.testsupport.ui; import org.eclipse.jdt.annotation.Nullable; import to.etc.domui.annotations.UIUrlParameter; import to.etc.domui.component.buttons.DefaultButton; import to.etc.domui.component.input.DateInput; import to.etc.domui.dom.html.Div; import to.etc.domui.dom.html.IClicked; import to.etc.domui.dom.html.UrlPage; import to.etc.domui.util.DomUtil; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; /** * Selenium test date input check page. * * @author <a href="mailto:jal@etc.to">Frits Jalvingh</a> * Created on May 27, 2014 */ public class DateInputTestPage extends UrlPage { private boolean m_withtime; @Nullable private Div m_result; @UIUrlParameter(name = "withtime") public boolean isWithtime() { return m_withtime; } public void setWithtime(boolean withtime) { m_withtime = withtime; } @Override public void createContent() throws Exception { final DateInput di = new DateInput(isWithtime()); preventAlertsFromOpening(); add(di); di.setTestID("datein"); DefaultButton button = new DefaultButton("Click", new IClicked<DefaultButton>() { @Override public void clicked(DefaultButton clickednode) throws Exception { Date dt = di.getValueSafe(); Div result = m_result; if(null == result) { m_result = result = new Div(); add(result); result.setTestID("result"); } result.removeAllChildren(); if(dt == null) { result.setText("error"); } else { DateFormat df = new SimpleDateFormat("yyyyMMddHHmm"); result.setText(df.format(dt)); } } }); button.setTestID("btn"); add(button); DefaultButton clear = new DefaultButton("Click", new IClicked<DefaultButton>() { @Override public void clicked(DefaultButton clickednode) throws Exception { di.setValue(null); Div result = m_result; if(null != result) { result.remove(); m_result = null; } } }); clear.setTestID("clear"); add(clear); } /** * Prevent alert from opening since it's presence will be indicated in result div as an error. * @return */ protected void preventAlertsFromOpening() { StringBuilder sb = new StringBuilder(); sb.append("var defaultAlert = alert;"); sb.append("alert = function(message){"); sb.append(" console.log('Alert blocked: ' + message);"); sb.append("}"); this.appendCreateJS(DomUtil.nullChecked(sb.toString())); } }
lgpl-2.1
paolopavan/biojava
biojava-sequencing/src/test/java/org/biojava/nbio/sequencing/io/fastq/SolexaFastqReaderTest.java
4898
/* * BioJava development code * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. If you do not have a copy, * see: * * http://www.gnu.org/copyleft/lesser.html * * Copyright for this code is held jointly by the individual * authors. These should be listed in @author doc comments. * * For more information on the BioJava project and its aims, * or to join the biojava-l mailing list, visit the home page * at: * * http://www.biojava.org/ * */ package org.biojava.nbio.sequencing.io.fastq; import java.io.IOException; import java.io.InputStream; import java.net.URL; /** * Unit test for SolexaFastqReader. */ public final class SolexaFastqReaderTest extends AbstractFastqReaderTest { @Override public Fastq createFastq() { return new FastqBuilder() .withDescription("description") .withSequence("sequence") .withQuality("quality_") .withVariant(FastqVariant.FASTQ_SOLEXA) .build(); } @Override public FastqReader createFastqReader() { return new SolexaFastqReader(); } @Override public FastqWriter createFastqWriter() { return new SolexaFastqWriter(); } public void testValidateDescription() throws Exception { SolexaFastqReader reader = new SolexaFastqReader(); URL invalidDescription = getClass().getResource("solexa-invalid-description.fastq"); try { reader.read(invalidDescription); fail("read(invalidDescription) expected IOException"); } catch (IOException e) { assertTrue(e.getMessage().contains("description must begin with a '@' character")); } } public void testValidateRepeatDescription() throws Exception { SolexaFastqReader reader = new SolexaFastqReader(); URL invalidRepeatDescription = getClass().getResource("solexa-invalid-repeat-description.fastq"); try { reader.read(invalidRepeatDescription); fail("read(invalidRepeatDescription) expected IOException"); } catch (IOException e) { assertTrue(e.getMessage().contains("repeat description must match description")); } } public void testWrappingAsSolexa() throws Exception { FastqReader reader = createFastqReader(); InputStream inputStream = getClass().getResourceAsStream("wrapping_as_solexa.fastq"); Iterable<Fastq> iterable = reader.read(inputStream); assertNotNull(iterable); int count = 0; for (Fastq f : iterable) { assertNotNull(f); count++; } assertEquals(3, count); inputStream.close(); } public void testFullRangeAsSolexa() throws Exception { FastqReader reader = createFastqReader(); InputStream inputStream = getClass().getResourceAsStream("solexa_full_range_as_solexa.fastq"); Iterable<Fastq> iterable = reader.read(inputStream); assertNotNull(iterable); int count = 0; for (Fastq f : iterable) { assertNotNull(f); count++; } assertEquals(2, count); inputStream.close(); } public void testMiscDnaAsSolexa() throws Exception { FastqReader reader = createFastqReader(); InputStream inputStream = getClass().getResourceAsStream("misc_dna_as_solexa.fastq"); Iterable<Fastq> iterable = reader.read(inputStream); assertNotNull(iterable); int count = 0; for (Fastq f : iterable) { assertNotNull(f); count++; } assertEquals(4, count); inputStream.close(); } public void testMiscRnaAsSolexa() throws Exception { FastqReader reader = createFastqReader(); InputStream inputStream = getClass().getResourceAsStream("misc_rna_as_solexa.fastq"); Iterable<Fastq> iterable = reader.read(inputStream); assertNotNull(iterable); int count = 0; for (Fastq f : iterable) { assertNotNull(f); count++; } assertEquals(4, count); inputStream.close(); } public void testLongReadsAsSolexa() throws Exception { FastqReader reader = createFastqReader(); InputStream inputStream = getClass().getResourceAsStream("longreads_as_solexa.fastq"); Iterable<Fastq> iterable = reader.read(inputStream); assertNotNull(iterable); int count = 0; for (Fastq f : iterable) { assertNotNull(f); count++; } assertEquals(10, count); inputStream.close(); } }
lgpl-2.1
GenomicParisCentre/nividic
src/main/java/fr/ens/transcriptome/nividic/om/filters/ExpressionMatrixSelectIdentifiersFilter.java
2450
/* * Nividic development code * * This code may be freely distributed and modified under the * terms of the GNU Lesser General Public Licence. This should * be distributed with the code. If you do not have a copy, * see: * * http://www.gnu.org/copyleft/lesser.html * * Copyright for this code is held jointly by the microarray platform * of the École Normale Supérieure and the individual authors. * These should be listed in @author doc comments. * * For more information on the Nividic project and its aims, * or to join the Nividic mailing list, visit the home page * at: * * http://www.transcriptome.ens.fr/nividic * */ package fr.ens.transcriptome.nividic.om.filters; import fr.ens.transcriptome.nividic.om.translators.Translator; /** * This class implements a filter using rows identifier as a filter. * @author Laurent Jourdren */ public class ExpressionMatrixSelectIdentifiersFilter extends ExpressionMatrixIdentifersFilter { /** * Test if filtered identifiers must be removed. * @return true if filtered row must be removed */ public boolean isRemoveFoundId() { return false; } // // Constructor // /** * Default constructor. */ public ExpressionMatrixSelectIdentifiersFilter() { setFilterNull(true); } /** * Default constructor. * @param translator to use */ public ExpressionMatrixSelectIdentifiersFilter(final Translator translator) { this(); setTranslator(translator); } /** * Default constructor. * @param id Identifier to add to filter list * @param translator Translator */ public ExpressionMatrixSelectIdentifiersFilter(final Translator translator, final String id) { this(translator); this.add(id); } /** * Default constructor. * @param id Identifier to add to filter list */ public ExpressionMatrixSelectIdentifiersFilter(final String id) { this(); this.add(id); } /** * Default constructor. * @param ids Identifiers to add to filter list * @param translator Translator */ public ExpressionMatrixSelectIdentifiersFilter(final Translator translator, final String[] ids) { this(translator); this.add(ids); } /** * Default constructor. * @param ids Identifiers to add to filter list */ public ExpressionMatrixSelectIdentifiersFilter(final String[] ids) { this(); this.add(ids); } }
lgpl-2.1
celements/celements-core
src/main/java/com/celements/pagetype/java/DefaultPageTypeConfig.java
4272
/* * See the NOTICE file distributed with this work for additional * information regarding copyright ownership. * * 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 com.celements.pagetype.java; import java.util.ArrayList; import java.util.List; import org.xwiki.model.reference.DocumentReference; import org.xwiki.model.reference.SpaceReference; import com.celements.cells.attribute.AttributeBuilder; import com.celements.model.context.ModelContext; import com.celements.model.util.References; import com.celements.pagetype.IPageTypeConfig; import com.celements.web.service.IWebUtilsService; import com.google.common.base.Optional; import com.google.common.base.Strings; import com.xpn.xwiki.web.Utils; /** * DefaultPageTypeConfig may be exposed to non privileged code (e.g. scripts) */ public class DefaultPageTypeConfig implements IPageTypeConfig { public static final String PRETTYNAME_DICT_PREFIX = "cel_pagetype_prettyname_"; private IJavaPageTypeRole pageTypeImpl; private ModelContext getContext() { return Utils.getComponent(ModelContext.class); } private IWebUtilsService getWebUtilsService() { return Utils.getComponent(IWebUtilsService.class); } public DefaultPageTypeConfig(IJavaPageTypeRole pageTypeImpl) { this.pageTypeImpl = pageTypeImpl; } @Override public String getName() { return pageTypeImpl.getName(); } @Override public String getPrettyName() { String dictNameKey = PRETTYNAME_DICT_PREFIX + getName(); String dictionaryPrettyName = getWebUtilsService().getAdminMessageTool().get(dictNameKey); if (!dictNameKey.equals(dictionaryPrettyName)) { return dictionaryPrettyName; } return getName(); } @Override public boolean hasPageTitle() { return pageTypeImpl.hasPageTitle(); } @Override public boolean displayInFrameLayout() { return pageTypeImpl.displayInFrameLayout(); } @Override public List<String> getCategories() { return new ArrayList<>(pageTypeImpl.getCategoryNames()); } @Override public String getRenderTemplateForRenderMode(String renderMode) { DocumentReference localTemplateRef = getLocalTemplateRef(renderMode); return Strings.nullToEmpty(getWebUtilsService().getInheritedTemplatedPath(localTemplateRef)); } private DocumentReference getLocalTemplateRef(String renderMode) { DocumentReference localTemplateRef = null; String templateName = pageTypeImpl.getRenderTemplateForRenderMode(renderMode); if (!Strings.isNullOrEmpty(templateName)) { localTemplateRef = References.create(DocumentReference.class, templateName, getTemplateSpaceRef()); } return localTemplateRef; } private SpaceReference getTemplateSpaceRef() { return References.create(SpaceReference.class, TEMPLATE_SPACE_NAME, getContext().getWikiRef()); } @Override public boolean isVisible() { return pageTypeImpl.isVisible(); } @Override public boolean isUnconnectedParent() { return pageTypeImpl.isUnconnectedParent(); } @Override public boolean useInlineEditorMode() { return pageTypeImpl.useInlineEditorMode(); } @Override public Optional<String> defaultTagName() { return pageTypeImpl.defaultTagName(); } @Override public void collectAttributes(AttributeBuilder attrBuilder, DocumentReference cellDocRef) { pageTypeImpl.collectAttributes(attrBuilder, cellDocRef); } }
lgpl-2.1
jhalliday/hibernate-ogm
core/src/main/java/org/hibernate/ogm/failure/operation/CreateAssociationWithKey.java
721
/* * Hibernate OGM, Domain model persistence for NoSQL datastores * * 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.ogm.failure.operation; import org.hibernate.ogm.dialect.spi.GridDialect; import org.hibernate.ogm.model.key.spi.AssociationKey; /** * Represents one execution of * {@link GridDialect#createAssociation(org.hibernate.ogm.model.key.spi.AssociationKey, org.hibernate.ogm.dialect.spi.AssociationContext)} * . * * @author Gunnar Morling */ public interface CreateAssociationWithKey extends GridDialectOperation { AssociationKey getAssociationKey(); }
lgpl-2.1
geotools/geotools
modules/library/opengis/src/main/java/org/opengis/filter/spatial/DWithin.java
896
/* * GeoTools - The Open Source Java GIS Toolkit * http://geotools.org * * (C) 2011, Open Source Geospatial Foundation (OSGeo) * (C) 2005, Open Geospatial Consortium Inc. * * All Rights Reserved. http://www.opengis.org/legal/ */ package org.opengis.filter.spatial; // Annotations import org.opengis.annotation.XmlElement; /** * Concrete {@linkplain DistanceBufferOperator distance buffer operator} that evaluates as true when * any part of the first geometry lies within the given distance of the second geometry. * * @version <A HREF="http://www.opengis.org/docs/02-059.pdf">Implementation specification 1.0</A> * @author Chris Dillard (SYS Technologies) * @since GeoAPI 2.0 */ @XmlElement("DWithin") public interface DWithin extends DistanceBufferOperator { /** Operator name used to check FilterCapabilities */ public static String NAME = "DWithin"; }
lgpl-2.1