repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
rubenswagner/L2J-Global
java/com/l2jglobal/gameserver/model/stats/finalizers/RegenMPFinalizer.java
5614
/* * This file is part of the L2J Global project. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.l2jglobal.gameserver.model.stats.finalizers; import java.util.Optional; import com.l2jglobal.Config; import com.l2jglobal.gameserver.data.xml.impl.ClanHallData; import com.l2jglobal.gameserver.instancemanager.CastleManager; import com.l2jglobal.gameserver.instancemanager.FortManager; import com.l2jglobal.gameserver.instancemanager.ZoneManager; import com.l2jglobal.gameserver.model.actor.L2Character; import com.l2jglobal.gameserver.model.actor.instance.L2PcInstance; import com.l2jglobal.gameserver.model.actor.instance.L2PetInstance; import com.l2jglobal.gameserver.model.residences.AbstractResidence; import com.l2jglobal.gameserver.model.residences.ResidenceFunction; import com.l2jglobal.gameserver.model.residences.ResidenceFunctionType; import com.l2jglobal.gameserver.model.stats.BaseStats; import com.l2jglobal.gameserver.model.stats.IStatsFunction; import com.l2jglobal.gameserver.model.stats.Stats; import com.l2jglobal.gameserver.model.zone.ZoneId; import com.l2jglobal.gameserver.model.zone.type.L2CastleZone; import com.l2jglobal.gameserver.model.zone.type.L2ClanHallZone; import com.l2jglobal.gameserver.model.zone.type.L2FortZone; import com.l2jglobal.gameserver.model.zone.type.L2MotherTreeZone; /** * @author UnAfraid */ public class RegenMPFinalizer implements IStatsFunction { @Override public double calc(L2Character creature, Optional<Double> base, Stats stat) { throwIfPresent(base); double baseValue = creature.isPlayer() ? creature.getActingPlayer().getTemplate().getBaseMpRegen(creature.getLevel()) : creature.getTemplate().getBaseMpReg(); baseValue *= creature.isRaid() ? Config.RAID_MP_REGEN_MULTIPLIER : Config.MP_REGEN_MULTIPLIER; if (creature.isPlayer()) { final L2PcInstance player = creature.getActingPlayer(); if (player.isInsideZone(ZoneId.CLAN_HALL) && (player.getClan() != null) && (player.getClan().getHideoutId() > 0)) { final L2ClanHallZone zone = ZoneManager.getInstance().getZone(player, L2ClanHallZone.class); final int posChIndex = zone == null ? -1 : zone.getResidenceId(); final int clanHallIndex = player.getClan().getHideoutId(); if ((clanHallIndex > 0) && (clanHallIndex == posChIndex)) { final AbstractResidence residense = ClanHallData.getInstance().getClanHallById(player.getClan().getHideoutId()); if (residense != null) { final ResidenceFunction func = residense.getFunction(ResidenceFunctionType.MP_REGEN); if (func != null) { baseValue *= func.getValue(); } } } } if (player.isInsideZone(ZoneId.CASTLE) && (player.getClan() != null) && (player.getClan().getCastleId() > 0)) { final L2CastleZone zone = ZoneManager.getInstance().getZone(player, L2CastleZone.class); final int posCastleIndex = zone == null ? -1 : zone.getResidenceId(); final int castleIndex = player.getClan().getCastleId(); if ((castleIndex > 0) && (castleIndex == posCastleIndex)) { final AbstractResidence residense = CastleManager.getInstance().getCastleById(player.getClan().getCastleId()); if (residense != null) { final ResidenceFunction func = residense.getFunction(ResidenceFunctionType.MP_REGEN); if (func != null) { baseValue *= func.getValue(); } } } } if (player.isInsideZone(ZoneId.FORT) && (player.getClan() != null) && (player.getClan().getFortId() > 0)) { final L2FortZone zone = ZoneManager.getInstance().getZone(player, L2FortZone.class); final int posFortIndex = zone == null ? -1 : zone.getResidenceId(); final int fortIndex = player.getClan().getFortId(); if ((fortIndex > 0) && (fortIndex == posFortIndex)) { final AbstractResidence residense = FortManager.getInstance().getFortById(player.getClan().getCastleId()); if (residense != null) { final ResidenceFunction func = residense.getFunction(ResidenceFunctionType.MP_REGEN); if (func != null) { baseValue *= func.getValue(); } } } } // Mother Tree effect is calculated at last' if (player.isInsideZone(ZoneId.MOTHER_TREE)) { final L2MotherTreeZone zone = ZoneManager.getInstance().getZone(player, L2MotherTreeZone.class); final int mpBonus = zone == null ? 0 : zone.getMpRegenBonus(); baseValue += mpBonus; } // Calculate Movement bonus if (player.isSitting()) { baseValue *= 1.5; // Sitting } else if (!player.isMoving()) { baseValue *= 1.1; // Staying } else if (player.isRunning()) { baseValue *= 0.7; // Running } // Add MEN bonus baseValue *= creature.getLevelMod() * BaseStats.MEN.calcBonus(creature); } else if (creature.isPet()) { baseValue = ((L2PetInstance) creature).getPetLevelData().getPetRegenMP() * Config.PET_MP_REGEN_MULTIPLIER; } return Stats.defaultValue(creature, stat, baseValue); } }
gpl-3.0
Yelbosh/deep-in-algorithms
src/main/java/com/yelbosh/gof/template/ReadHtml.java
1544
package com.yelbosh.gof.template; /** * A concrete class extends AbstractRead * This class can read HTML from a HTTP URL */ import java.io.*; import java.net.*; public class ReadHtml extends AbstractRead { private URLConnection conn; private BufferedReader in; public ReadHtml() { } public ReadHtml(String s) { resource = s; } public boolean open() { try { URL url = new URL(resource); conn = url.openConnection(); in = new BufferedReader ( new InputStreamReader(conn.getInputStream())); } catch (MalformedURLException e) { System.out.println("Uable to connect URL:" + resource); return false; } catch (IOException e) { System.out.println("IOExeption when connecting to URL" + resource); return false; } return true; } protected void readContent() { try { if(in != null) { String str; while((str = in.readLine()) != null) { System.out.println(str); } } } catch(IOException e) { System.out.println("Read file error !"); } } protected void close() { if(in != null) { try { in.close(); } catch(IOException e) { System.out.println("IO error !"); } } } }
gpl-3.0
tvesalainen/util
jmx/src/main/java/org/vesalainen/jmx/SimpleMBeanServerBuilder.java
1505
/* * Copyright (C) 2021 Timo Vesalainen <timo.vesalainen@iki.fi> * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.vesalainen.jmx; import javax.management.MBeanServer; import javax.management.MBeanServerBuilder; import javax.management.MBeanServerDelegate; /** * * @author Timo Vesalainen <timo.vesalainen@iki.fi> */ public class SimpleMBeanServerBuilder extends MBeanServerBuilder { public SimpleMBeanServerBuilder() { } @Override public MBeanServer newMBeanServer(String defaultDomain, MBeanServer outer, MBeanServerDelegate delegate) { return new SimpleMBeanServer(defaultDomain, outer, delegate); //To change body of generated methods, choose Tools | Templates. } @Override public MBeanServerDelegate newMBeanServerDelegate() { return new MBeanServerDelegate(); } }
gpl-3.0
fppt/mindmapsdb
grakn-core/src/main/java/ai/grakn/graql/MatchQuery.java
5566
/* * Grakn - A Distributed Semantic Database * Copyright (C) 2016 Grakn Labs Limited * * Grakn 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. * * Grakn 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 Grakn. If not, see <http://www.gnu.org/licenses/gpl.txt>. */ package ai.grakn.graql; import ai.grakn.GraknGraph; import ai.grakn.graql.admin.MatchQueryAdmin; import ai.grakn.concept.Concept; import java.util.*; import java.util.stream.Stream; import static ai.grakn.graql.Order.asc; import static java.util.stream.Collectors.toList; /** * a query used for finding data in a graph that matches the given patterns. * <p> * The {@code MatchQuery} is a pattern-matching query. The patterns are described in a declarative fashion, forming a * subgraph, then the {@code MatchQuery} will traverse the graph in an efficient fashion to find any matching subgraphs. * <p> * Each matching subgraph will produce a map, where keys are variable names and values are concepts in the graph. */ public interface MatchQuery extends Query<List<Map<String, Concept>>>, Streamable<Map<String, Concept>> { @Override default List<Map<String, Concept>> execute() { return stream().collect(toList()); } /** * @param names an array of variable names to select * @return a new MatchQuery that selects the given variables */ default MatchQuery select(String... names) { return select(new HashSet<>(Arrays.asList(names))); } /** * @param names a set of variable names to select * @return a new MatchQuery that selects the given variables */ MatchQuery select(Set<String> names); /** * @param name a variable name to get * @return a stream of concepts */ Stream<Concept> get(String name); /** * @return an ask query that will return true if any matches are found */ AskQuery ask(); /** * @param vars an array of variables to insert for each result of this match query * @return an insert query that will insert the given variables for each result of this match query */ default InsertQuery insert(Var... vars) { return insert(Arrays.asList(vars)); } /** * @param vars a collection of variables to insert for each result of this match query * @return an insert query that will insert the given variables for each result of this match query */ InsertQuery insert(Collection<? extends Var> vars); /** * @param names an array of variable names to delete for each result of this match query * @return a delete query that will delete the given variable names for each result of this match query */ DeleteQuery delete(String... names); /** * @param deleters an array of variables stating what properties to delete for each result of this match query * @return a delete query that will delete the given properties for each result of this match query */ default DeleteQuery delete(Var... deleters) { return delete(Arrays.asList(deleters)); } /** * @param deleters a collection of variables stating what properties to delete for each result of this match query * @return a delete query that will delete the given properties for each result of this match query */ DeleteQuery delete(Collection<? extends Var> deleters); /** * Order the results by degree in ascending order * @param varName the variable name to order the results by * @return a new MatchQuery with the given ordering */ default MatchQuery orderBy(String varName) { return orderBy(varName, asc); } /** * Order the results by degree * @param varName the variable name to order the results by * @param order the ordering to use * @return a new MatchQuery with the given ordering */ MatchQuery orderBy(String varName, Order order); /** * @param graph the graph to execute the query on * @return a new MatchQuery with the graph set */ MatchQuery withGraph(GraknGraph graph); /** * @param limit the maximum number of results the query should return * @return a new MatchQuery with the limit set */ MatchQuery limit(long limit); /** * @param offset the number of results to skip * @return a new MatchQuery with the offset set */ MatchQuery offset(long offset); /** * remove any duplicate results from the query * @return a new MatchQuery without duplicate results */ MatchQuery distinct(); /** * Use rules in the graph in order to infer additional results */ MatchQuery infer(); /** * Aggregate results of a query. * @param aggregate the aggregate operation to apply * @param <S> the type of the aggregate result * @return a query that will yield the aggregate result */ <S> AggregateQuery<S> aggregate(Aggregate<? super Map<String, Concept>, S> aggregate); /** * @return admin instance for inspecting and manipulating this query */ MatchQueryAdmin admin(); }
gpl-3.0
jsaintyv/JEnseigne
src/org/jenseigne/lettre/LetterHUpper.java
463
package org.jenseigne.lettre; public class LetterHUpper extends ASymbol { @Override public char getCharacter() { return 'H'; } @Override public void initListGraphic() { append(new Line(UPPER_RIGHT_CORNER, BOTTOM_RIGHT_CORNER)); append(new DrawJump()); append(new Line(UPPER_LEFT_CORNER, BOTTOM_LEFT_CORNER)); append(new DrawJump()); append(new Line(RIGHT_MIDDLE, LEFT_MIDDLE)); } @Override public boolean isUpper() { return true; } }
gpl-3.0
MichaelJ2/big-buum-man
source/big-buum-man-server/src/main/java/at/big_buum_man/server/gui/objects/MapListe.java
1486
package at.big_buum_man.server.gui.objects; import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; import java.util.ArrayList; import at.big_buum_man.server.gui.helper.Variables; /*** * @version 1.0 * @author Michael Januschek * */ public class MapListe { ArrayList<String[]> v=new ArrayList<String[]>(); public static void main(String[] args) { } public MapListe() { FileReader myFile= null; BufferedReader buff= null; ArrayList<String[]> values=new ArrayList<String[]>(); try { myFile =new FileReader(Variables.maps+"Beginning.txt"); buff =new BufferedReader(myFile); //int o=0; while (true) { String [] valuesSplited = null; String line = buff.readLine(); if (line == null) break; valuesSplited = line.split(","); // Spliten nach dem Sonderzeichen "," values.add(valuesSplited); //o++; } v= values; } catch (IOException e) { System.err.println("Error2 :"+e); } finally { try { buff.close(); myFile.close(); } catch (IOException e) { System.err.println("Error2 :"+e); } } } public ArrayList<String[]> getMap() { return this.v; } }
gpl-3.0
gvincenzi/bglogin
bglogin-web/src/main/java/org/bglogin/web/config/SpringMvcConfig.java
2435
package org.bglogin.web.config; import java.util.Locale; import org.springframework.context.MessageSource; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.context.support.ReloadableResourceBundleMessageSource; import org.springframework.web.servlet.LocaleResolver; import org.springframework.web.servlet.config.annotation.EnableWebMvc; import org.springframework.web.servlet.config.annotation.InterceptorRegistry; import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.i18n.CookieLocaleResolver; import org.springframework.web.servlet.i18n.LocaleChangeInterceptor; import org.springframework.web.servlet.view.InternalResourceViewResolver; import org.springframework.web.servlet.view.JstlView; /** * Class for Annotation Type Configuration * * @author Giuseppe Vincenzi * */ @EnableWebMvc @Configuration @ComponentScan({ "org.bglogin.web.*" }) public class SpringMvcConfig extends WebMvcConfigurerAdapter { @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { registry.addResourceHandler("/resources/**").addResourceLocations("/resources/"); } @Bean public InternalResourceViewResolver viewResolver() { InternalResourceViewResolver viewResolver = new InternalResourceViewResolver(); viewResolver.setViewClass(JstlView.class); viewResolver.setPrefix("/WEB-INF/views/"); viewResolver.setSuffix(".jsp"); return viewResolver; } @Bean public MessageSource messageSource() { ReloadableResourceBundleMessageSource messageSource = new ReloadableResourceBundleMessageSource(); messageSource.setBasename("/i18n/message"); messageSource.setDefaultEncoding("UTF-8"); return messageSource; } @Bean public LocaleResolver localeResolver() { CookieLocaleResolver resolver = new CookieLocaleResolver(); resolver.setDefaultLocale(new Locale("en")); resolver.setCookieName("bgLoginLocaleCookie"); resolver.setCookieMaxAge(4800); return resolver; } @Override public void addInterceptors(InterceptorRegistry registry) { LocaleChangeInterceptor interceptor = new LocaleChangeInterceptor(); interceptor.setParamName("locale"); registry.addInterceptor(interceptor); } }
gpl-3.0
AKSW/DL-Learner
components-core/src/main/java/org/dllearner/accuracymethods/AccMethodTwoValued.java
1302
/** * Copyright (C) 2007 - 2016, Jens Lehmann * * This file is part of DL-Learner. * * DL-Learner 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. * * DL-Learner is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.dllearner.accuracymethods; /** * Accuracy calculation with true/false positive/negative */ public interface AccMethodTwoValued extends AccMethod { /** * Compute accuracy according to this method * @param tp True Positives (positive as positive) * @param fn False Negative (positive as negative) * @param fp False Positive (negative as positive) * @param tn True Negative (negative as negative) * @param noise Noise * @return accuracy value or -1 if too weak */ double getAccOrTooWeak2(int tp, int fn, int fp, int tn, double noise); }
gpl-3.0
derkaiserreich/structr
structr-core/src/main/java/org/structr/core/graph/NodeService.java
7077
/** * Copyright (C) 2010-2016 Structr GmbH * * This file is part of Structr <http://structr.org>. * * Structr 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. * * Structr 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 Structr. If not, see <http://www.gnu.org/licenses/>. */ package org.structr.core.graph; import java.io.File; import java.util.Collection; import java.util.EnumMap; import java.util.Iterator; import java.util.Map; import java.util.Properties; import java.util.logging.Level; import java.util.logging.Logger; import org.structr.api.DatabaseService; import org.structr.api.index.Index; import org.structr.api.graph.Node; import org.structr.api.graph.Relationship; import org.structr.api.Transaction; import org.structr.api.config.Structr; import org.structr.common.SecurityContext; import org.structr.common.error.FrameworkException; import org.structr.api.service.Command; import org.structr.core.GraphObject; import org.structr.core.Services; import org.structr.api.service.SingletonService; import org.structr.api.service.StructrServices; import org.structr.core.app.StructrApp; /** * The graph/node service main class. * * * */ public class NodeService implements SingletonService { private static final Logger logger = Logger.getLogger(NodeService.class.getName()); //~--- fields --------------------------------------------------------- private DatabaseService graphDb = null; private Index<Node> fulltextIndex = null; private Index<Node> keywordIndex = null; private Index<Node> layerIndex = null; private Index<Relationship> relFulltextIndex = null; private Index<Relationship> relKeywordIndex = null; // indices private final Map<RelationshipIndex, Index<Relationship>> relIndices = new EnumMap<>(RelationshipIndex.class); private final Map<NodeIndex, Index<Node>> nodeIndices = new EnumMap<>(NodeIndex.class); /** Dependent services */ private String filesPath = null; private boolean isInitialized = false; //~--- constant enums ------------------------------------------------- /** * The list of existing node indices. */ public static enum NodeIndex { keyword, fulltext, layer } /** * The list of existing relationship indices. */ public static enum RelationshipIndex { rel_keyword, rel_fulltext } @Override public void injectArguments(Command command) { if (command != null) { command.setArgument("graphDb", graphDb); command.setArgument(NodeIndex.fulltext.name(), fulltextIndex); command.setArgument(NodeIndex.keyword.name(), keywordIndex); command.setArgument(NodeIndex.layer.name(), layerIndex); command.setArgument(RelationshipIndex.rel_fulltext.name(), relFulltextIndex); command.setArgument(RelationshipIndex.rel_keyword.name(), relKeywordIndex); command.setArgument("filesPath", filesPath); command.setArgument("indices", NodeIndex.values()); command.setArgument("relationshipIndices", RelationshipIndex.values()); } } @Override public void initialize(final StructrServices services, final Properties config) throws ClassNotFoundException, InstantiationException, IllegalAccessException { final String databaseDriver = config.getProperty(Structr.DATABASE_DRIVER, "org.structr.neo4j.Neo4jDatabaseService"); graphDb = (DatabaseService)Class.forName(databaseDriver).newInstance(); if (graphDb != null) { graphDb.initialize(config); filesPath = config.getProperty(Services.FILES_PATH); // check existence of files path File files = new File(filesPath); if (!files.exists()) { files.mkdir(); } logger.log(Level.INFO, "Database ready."); // index creation transaction try ( final Transaction tx = graphDb.beginTx() ) { fulltextIndex = graphDb.nodeIndexer().fulltext(); nodeIndices.put(NodeIndex.fulltext, fulltextIndex); keywordIndex = graphDb.nodeIndexer().exact(); nodeIndices.put(NodeIndex.keyword, keywordIndex); layerIndex = graphDb.nodeIndexer().spatial(); nodeIndices.put(NodeIndex.layer, layerIndex); relFulltextIndex = graphDb.relationshipIndexer().fulltext(); relIndices.put(RelationshipIndex.rel_fulltext, relFulltextIndex); relKeywordIndex = graphDb.relationshipIndexer().exact(); relIndices.put(RelationshipIndex.rel_keyword, relKeywordIndex); tx.success(); } catch (Throwable t) { logger.log(Level.WARNING, "Error while initializing indexes.", t); } isInitialized = true; } } @Override public void initialized() { // check for empty database and seed file importSeedFile(StructrApp.getConfigurationValue(Services.BASE_PATH)); } @Override public void shutdown() { if (isRunning()) { logger.log(Level.INFO, "Shutting down graph database service"); graphDb.shutdown(); graphDb = null; isInitialized = false; } } @Override public String getName() { return NodeService.class.getSimpleName(); } public DatabaseService getGraphDb() { return graphDb; } @Override public boolean isRunning() { return ((graphDb != null) && isInitialized); } @Override public boolean isVital() { return true; } public Collection<Index<Node>> getNodeIndices() { return nodeIndices.values(); } public Collection<Index<Relationship>> getRelationshipIndices() { return relIndices.values(); } public Index<Node> getNodeIndex(NodeIndex name) { return nodeIndices.get(name); } public Index<Relationship> getRelationshipIndex(RelationshipIndex name) { return relIndices.get(name); } private void importSeedFile(final String basePath) { final File seedFile = new File(StructrServices.trim(basePath) + "/" + Services.INITIAL_SEED_FILE); if (seedFile.exists()) { boolean hasApplicationNodes = false; try (final Tx tx = StructrApp.getInstance().tx()) { final Iterator<Node> allNodes = graphDb.getAllNodes().iterator(); final String idName = GraphObject.id.dbName(); while (allNodes.hasNext()) { if (allNodes.next().hasProperty(idName)) { hasApplicationNodes = true; break; } } tx.success(); } catch (FrameworkException fex) { } if (!hasApplicationNodes) { logger.log(Level.INFO, "Found initial seed file and no application nodes, applying initial seed.."); try { SyncCommand.importFromFile(graphDb, SecurityContext.getSuperUserInstance(), seedFile.getAbsoluteFile().getAbsolutePath(), false); } catch (FrameworkException fex) { logger.log(Level.WARNING, "Unable to import initial seed file.", fex); } } } } }
gpl-3.0
deodaj/MCMBTools
src/main/java/com/Deoda/MCMBTools/reference/Default.java
344
package com.Deoda.MCMBTools.reference; public class Default { public static final int MAX_WALL = 9; public static final int MAX_EXPAND = 9; public static final int BUILDING_WAND_ID = 5337; public static final int EXPAND_WAND_ID = 5338; public static final int DECONSTRUCT_WAND_ID = 5339; public static final boolean AUTOCRAFT = true; }
gpl-3.0
timrs2998/JTA-Fork
src/main/java/de/mud/jta/plugin/Shell.java
2794
package de.mud.jta.plugin; import de.mud.jta.FilterPlugin; import de.mud.jta.Plugin; import de.mud.jta.PluginBus; import de.mud.jta.event.ConfigurationListener; import de.mud.jta.event.OnlineStatus; import de.mud.jta.event.SocketListener; import java.io.IOException; // import java.io.InputStream; // import java.io.OutputStream; /** * The shell plugin is the backend component for terminal emulation using * a shell. It provides the i/o streams of the shell as data source. * <p> * <B>Maintainer:</B> Matthias L. Jugel * * @author Matthias L. Jugel, Marcus Mei�ner, Pete Zaitcev * @version $Id: Shell.java 499 2005-09-29 08:24:54Z leo $ */ public class Shell extends Plugin implements FilterPlugin { protected String shellCommand; private HandlerPTY pty; public Shell(final PluginBus bus, final String id) { super(bus, id); bus.registerPluginListener((ConfigurationListener) cfg -> { String tmp; if ((tmp = cfg.getProperty("Shell", id, "command")) != null) { shellCommand = tmp; // System.out.println("Shell: Setting config " + tmp); // P3 } else { // System.out.println("Shell: Not setting config"); // P3 shellCommand = "/bin/sh"; } }); bus.registerPluginListener(new SocketListener() { // we do actually ignore these parameters public void connect(String host, int port) { // XXX Fix this together with window size changes // String ttype = (String)bus.broadcast(new TerminalTypeRequest()); // String ttype = getTerminalType(); // if(ttype == null) ttype = "dumb"; // XXX Add try around here to catch missing DLL/.so. pty = new HandlerPTY(); if (pty.start(shellCommand) == 0) { bus.broadcast(new OnlineStatus(true)); } else { bus.broadcast(new OnlineStatus(false)); } } public void disconnect() { bus.broadcast(new OnlineStatus(false)); pty = null; } }); } public void setFilterSource(FilterPlugin plugin) { // we do not have a source other than our socket } public FilterPlugin getFilterSource() { return null; } public int read(byte[] b) throws IOException { if (pty == null) { return 0; } int ret = pty.read(b); if (ret <= 0) { throw new IOException("EOF on PTY"); } return ret; } public void write(byte[] b) throws IOException { if (pty != null) { pty.write(b); } } }
gpl-3.0
CodeCrafter47/bungeetablistplus-skinservice
src/main/java/codecrafter47/skinservice/SkinRequest.java
441
package codecrafter47.skinservice; import codecrafter47.skinservice.util.ImageWrapper; import lombok.Data; import lombok.RequiredArgsConstructor; @Data @RequiredArgsConstructor public class SkinRequest { private final ImageWrapper image; private final String ip; private volatile boolean finished = false; private volatile boolean error = false; private int timeLeft = 1; private volatile SkinInfo result = null; }
gpl-3.0
czwen-ing/mynote
app/src/main/java/com/example/mynote/adapter/NoteRecyclerAdapter.java
10315
package com.example.mynote.adapter; import android.content.Context; import android.database.Cursor; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.support.v7.widget.RecyclerView; import android.util.Log; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.widget.CheckBox; import android.widget.ImageView; import android.widget.TextView; import com.example.mynote.bean.Note; import com.example.mynote.R; import com.example.mynote.data.Notes; import com.example.mynote.utils.DataUtils; import com.example.mynote.utils.ImageUtils; import com.example.mynote.utils.ResourceParser; import com.example.mynote.utils.ResourceParser.NoteBgResources; import java.text.DateFormat; import java.util.Collection; import java.util.Date; import java.util.HashMap; import java.util.HashSet; import java.util.Iterator; import java.util.List; public class NoteRecyclerAdapter extends RecyclerView.Adapter<NoteRecyclerAdapter.TwoSpanViewHolder> { private Context mContext; private List<Note> notes; private boolean longClickable = true; private boolean choiceMode = false; private HashMap<Integer,Boolean> mSelectedItems; private int sortWay; private int type = 0; private int size; public NoteRecyclerAdapter(Context context, List<Note> notes,int sortWay) { mContext = context; this.notes = notes; this.sortWay = sortWay; mSelectedItems = new HashMap<>(); } public NoteRecyclerAdapter(Context context, List<Note> notes,int sortWay,int type) { mContext = context; this.notes = notes; this.sortWay = sortWay; mSelectedItems = new HashMap<>(); this.type = type; } @Override public int getItemViewType(int position) { if (type == 0){ return 0; } else { return 1; } } @Override public TwoSpanViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { if (viewType == 0){ return new TwoSpanViewHolder(LayoutInflater.from(mContext) .inflate(R.layout.note_item, parent, false)); } else if (viewType == 1){ return new TwoSpanViewHolder(LayoutInflater.from(mContext) .inflate(R.layout.note_item2, parent, false)); } return null; } @Override public void onBindViewHolder(final TwoSpanViewHolder holder,int position) { final Note note = notes.get(position); holder.contentText.setText(note.getContent()); Bitmap bitmap = DataUtils.getImageFromDB(mContext.getContentResolver(),note.getNoteId()); if (bitmap != null){ int width =View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED); int height =View.MeasureSpec.makeMeasureSpec(0,View.MeasureSpec.UNSPECIFIED); holder.viewGroup.measure(width,height); if (type == 0){ if (size == 0){ size = holder.viewGroup.getMeasuredWidth(); } } else { if (size == 0){ size = holder.viewGroup.getMeasuredHeight(); } } Log.e("TAG"," itemView size " + size); holder.imageView.setImageBitmap(ImageUtils.scaleBitmapInSameSize(bitmap,size)); holder.imageView.setVisibility(View.VISIBLE); } else { holder.imageView.setVisibility(View.GONE); holder.itemView.setBackgroundResource(NoteBgResources.getNoteListBgResource(note.getBgId())); } if (sortWay == ResourceParser.SORT_BY_CREATE_DATE){ holder.timeText.setText(getCurrentDateAndTime(note.getCreatedTime())); } else { holder.timeText.setText(getCurrentDateAndTime(note.getModifiedTime())); } holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mOnItemClickListener != null) { mOnItemClickListener.onItemClick(v, holder.getAdapterPosition(), note.getNoteId()); } } }); holder.itemView.setOnLongClickListener(new View.OnLongClickListener() { @Override public boolean onLongClick(View v) { if (longClickable && mOnItemLongClickListener != null) { mOnItemLongClickListener.onItemLongClick(v, holder.getAdapterPosition(),note.getNoteId()); return true; } else { return false; } } }); if (choiceMode) { holder.checkBox.setVisibility(View.VISIBLE); holder.checkBox.setChecked(isSelectedItem(position)); } else { holder.checkBox.setVisibility(View.GONE); } if (note.getAlarmDate() > System.currentTimeMillis()){ holder.clockView.setVisibility(View.VISIBLE); } else { holder.clockView.setVisibility(View.GONE); } } private String getCurrentDateAndTime(long currentTime) { DateFormat dateFormat = DateFormat.getDateInstance(); DateFormat timeFormat = DateFormat.getTimeInstance(DateFormat.SHORT); Date date = new Date(currentTime); String dateStr = dateFormat.format(date); String timeStr = timeFormat.format(date); if (dateStr.equals(dateFormat.format(new Date(System.currentTimeMillis())))) { return timeStr; } else { return dateStr + timeStr; } } @Override public int getItemCount() { return notes.size(); } class TwoSpanViewHolder extends RecyclerView.ViewHolder { ImageView imageView; ViewGroup viewGroup; TextView contentText; TextView timeText; CheckBox checkBox; ImageView clockView; public TwoSpanViewHolder(View itemView) { super(itemView); viewGroup = (ViewGroup) itemView.findViewById(R.id.note_ll); imageView = (ImageView) itemView.findViewById(R.id.imageView); contentText = (TextView) itemView.findViewById(R.id.content_text); timeText = (TextView) itemView.findViewById(R.id.time_text); checkBox = (CheckBox) itemView.findViewById(R.id.check_box); clockView = (ImageView) itemView.findViewById(R.id.clock_iv); } } /** * 设置是否可以长按 * @param longClickable */ public void setLongClickable(boolean longClickable) { this.longClickable = longClickable; } public interface OnItemClickListener { void onItemClick(View view, int position, int id); } private OnItemClickListener mOnItemClickListener = null; public void setOnItemClickListener(OnItemClickListener listener) { mOnItemClickListener = listener; } public interface OnItemLongClickListener { void onItemLongClick(View view, int position,int id); } private OnItemLongClickListener mOnItemLongClickListener = null; public void setOnItemLongClickListener(OnItemLongClickListener listener) { mOnItemLongClickListener = listener; } /** * 设置是否进入选择删除模式 * @param choiceMode */ public void setChoiceMode(boolean choiceMode) { mSelectedItems.clear(); this.choiceMode = choiceMode; } public boolean isInChoiceMode() { return choiceMode; } /** * 将被选中的Item放入mSelectedItems健值集合中 * @param position * @param checked */ public void setCheckItem(int position, boolean checked){ mSelectedItems.put(position,checked); notifyDataSetChanged(); } /** * 判断在mSelectedItems是否包含所选的Item,判断是否被选中 * @param position * @return */ public boolean isSelectedItem(int position){ if (null == mSelectedItems.get(position)) { return false; } return mSelectedItems.get(position); } /** * 全选 * @param isAllSelectec */ public void selectAll(boolean isAllSelectec) { for (int i = 0; i < notes.size(); i++){ setCheckItem(i,isAllSelectec); } } public int getSelectedCount(){ Collection<Boolean> values = mSelectedItems.values(); Iterator<Boolean> iter = values.iterator(); int count = 0; while (iter.hasNext()) { if (iter.next()) { count++; } } return count; } public boolean isAllSelected(){ int selectedCount = getSelectedCount(); return selectedCount != 0 && selectedCount == notes.size(); } /** * 获取被选中的Item的NoteId,用以从数据库中删除数据 * @return */ public HashSet<Long> getSelectedItemIds() { HashSet<Long> itemsIds = new HashSet<>(); for (Integer position : mSelectedItems.keySet()){ if (mSelectedItems.get(position)){ long id = getItemId(position); itemsIds.add(id); } } return itemsIds; } @Override public long getItemId(int position) { return notes.get(position).getNoteId(); } private Bitmap getImageFromDB(long noteId) { Bitmap bitmap = null; Cursor cursor = mContext.getContentResolver().query(Notes.CONTENT_MEDIA_URI, new String[]{Notes.MediaColumns.IMAGE_BLOB}, Notes.MediaColumns.NOTE_ID + "=?", new String[]{ String.valueOf(noteId)}, null); if (cursor != null) { if (cursor.moveToFirst()) { byte[] bmpBlob = cursor.getBlob(cursor.getColumnIndex(Notes.MediaColumns.IMAGE_BLOB)); bitmap = BitmapFactory.decodeByteArray(bmpBlob,0,bmpBlob.length); } cursor.close(); } else { throw new IllegalArgumentException("未能找到此Id的数据" + noteId); } return bitmap; } public void setItemView(int type){ this.type = type; } }
gpl-3.0
sonologic/jingleboard
src/nl/sonologic/jingles/Pair.java
208
/** * */ package nl.sonologic.jingles; /** * @author gmc * */ public class Pair<T1, T2> { public T1 v1; public T2 v2; /** * */ public Pair(T1 v1, T2 v2) { this.v1 = v1; this.v2 = v2; } }
gpl-3.0
lucasgueiros/variados
ConexaoJavaBD/src/DAO/ConsultasImportantesDAO.java
213
package DAO; import java.sql.ResultSet; public interface ConsultasImportantesDAO { public ResultSet projetosDoDepartamento(int numDepartamento); public double HorasTrabalhadasNoProjeto(int numProjeto); }
gpl-3.0
liyi-david/ePMC
plugins/jani-interaction/src/main/java/epmc/jani/interaction/remote/TaskServerLocal.java
9131
/**************************************************************************** ePMC - an extensible probabilistic model checker Copyright (C) 2017 This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see <http://www.gnu.org/licenses/>. *****************************************************************************/ package epmc.jani.interaction.remote; import static epmc.error.UtilError.fail; import java.io.File; import java.io.IOException; import java.lang.ProcessBuilder.Redirect; import java.rmi.NoSuchObjectException; import java.rmi.NotBoundException; import java.rmi.RemoteException; import java.rmi.registry.LocateRegistry; import java.rmi.registry.Registry; import java.rmi.server.UnicastRemoteObject; import java.util.ArrayList; import java.util.List; import java.util.concurrent.TimeUnit; import javax.json.JsonValue; import epmc.error.EPMCException; import epmc.main.EPMC; import epmc.messages.Message; import epmc.messages.OptionsMessages; import epmc.options.Options; import epmc.plugin.OptionsPlugin; /** * Represents a task server running on the local machine. * * @author Ernst Moritz Hahn */ public final class TaskServerLocal implements TaskServer { /** name of system property to obtain Java home */ private final static String JAVA_HOME = "java.home"; /** subdirectory for Java binaries within Java home */ private final static String BIN = "bin"; /** name of command to start Java */ private final static String JAVA = "java"; /** name of system property to obtain Java class path */ private final static String JAVA_CLASS_PATH = "java.class.path"; /** Java VM parameter to enable assertions */ private final static String ENABLE_ASSERTIONS = "-ea"; /** Java VM parameter to enable extended object serialisation debugging */ private final static String EXTENDED_SERIALIZATION_DEBUG = "-Dsun.io.serialization.extendedDebugInfo=true"; /** Java VM parameter to set the class path */ private final static String CLASSPATH = "-cp"; /** EPMC parameter to start as task server */ private final static String COMMAND_SERVER = "server"; /** string containing comma */ private final static String COMMA = ","; /** string containing a sequence of two minuses, for EPMC parameters */ private final static String DOUBLE_MINUS = "--"; /** string containing "false", for EPMC parameters */ private final static String FALSE = "false"; /** contains the locally running Java VM running EPMC task server */ private Process process; /** RMI connection to EPMC task server to send commands to */ private JANIRemote server; /** whether the server has been started */ private boolean started; /** whether the server has been stopped */ private boolean stopped; @Override public void start() { assert !started; started = true; Class<EPMC> mainClass = epmc.main.EPMC.class; String javaHome = System.getProperty(JAVA_HOME); String javaBin = javaHome + File.separator + BIN + File.separator + JAVA; String classpath = System.getProperty(JAVA_CLASS_PATH); String className = mainClass.getCanonicalName(); List<String> plugins = Options.get().get(OptionsPlugin.PLUGIN); assert plugins != null; String pluginString = String.join(COMMA, plugins); ProcessBuilder builder = new ProcessBuilder(); List<String> command = new ArrayList<>(); command.add(javaBin); try { assert false; } catch (AssertionError e) { command.add(ENABLE_ASSERTIONS); command.add(EXTENDED_SERIALIZATION_DEBUG); } command.add(CLASSPATH); command.add(classpath); command.add(className); command.add(COMMAND_SERVER); command.add(DOUBLE_MINUS + OptionsMessages.TRANSLATE_MESSAGES); command.add(FALSE); if (plugins.size() > 0) { command.add(DOUBLE_MINUS + OptionsPlugin.PLUGIN); command.add(pluginString); } builder.command(command); try { assert false; } catch (AssertionError e) { builder.redirectError(Redirect.INHERIT); } Process process = null; try { process = builder.start(); } catch (IOException e) { fail(ProblemsRemote.REMOTE_PROCESS_CREATE_IO_EXCEPTION, e.getMessage(), e); } RMIConnectionData rmi = UtilRemote.readServerStatus(process.getInputStream()); Registry registry = null; try { registry = LocateRegistry.getRegistry(rmi.getPort()); } catch (RemoteException e) { fail(ProblemsRemote.REMOTE_GET_REGISTRY_FAILED, e.getMessage(), e); } JANIRemote iscasMcServer = null; try { iscasMcServer = (JANIRemote) registry.lookup(rmi.getName()); } catch (RemoteException e) { fail(ProblemsRemote.REMOTE_REGISTRY_LOOKUP_REMOTE_EXCEPTION, e.getMessage(), e); } catch (NotBoundException e) { fail(ProblemsRemote.REMOTE_NOT_BOUND_EXCEPTION, e.getMessage(), e); } this.process = process; this.server = iscasMcServer; } @Override public JANIRemote getServer() { return server; } @Override public void stop() { assert started; assert !stopped; stopped = true; /* if the server has already been terminated before, we are done */ if (!process.isAlive()) { return; } /* Try to terminate server by exit command. Start new thread, otherwise * will block in case the command does not work as expected and the call * thus does not terminate. */ new Thread(() -> { try { EPMCChannel channel = new EPMCChannel() { @Override public void setTimeStarted(long time) throws RemoteException { } @Override public void send(long time, Message key, String... arguments) throws RemoteException { } @Override public void send(EPMCException exception) throws RemoteException { } @Override public void send(String name, JsonValue result) throws RemoteException { } }; Options userOptions = Options.get().clone(); userOptions.set(Options.COMMAND, JANIServer.EXIT); execute(userOptions, channel, null, true); UnicastRemoteObject.unexportObject(channel, true); } catch (EPMCException e) { /* we don't care about exceptions thrown at this point */ } catch (NoSuchObjectException e) { /* we don't care about exceptions thrown at this point */ } }); /* If the exit command worked immediately, return. Otherwise, wait and * check again. */ if (!process.isAlive()) { return; } try { process.waitFor(1000, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { } if (!process.isAlive()) { return; } /* If the exit command did not work, destroy the process. First, try to * do so in a nice way. If this does not work, force termination. */ process.destroy(); if (!process.isAlive()) { return; } try { process.waitFor(2000, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { } if (!process.isAlive()) { return; } process.destroyForcibly(); if (!process.isAlive()) { return; } try { process.waitFor(2000, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { } if (!process.isAlive()) { return; } try { process.waitFor(10000, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { } /* If the process did not terminate even after trying to force to * terminate it and waiting quite a while, we have a problem and must * ask the user to terminate it manually. */ if (process.isAlive()) { fail(ProblemsRemote.REMOTE_FAILED_TERMINATE_PROCESS); } } }
gpl-3.0
CMPUT301W15T09/Team9Project
Team9ProjectTests/src/com/indragie/comput301as1/test/UserManagerTests.java
1366
/* * Copyright (C) 2015 Indragie Karunaratne * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.indragie.comput301as1.test; import com.indragie.cmput301as1.User; import com.indragie.cmput301as1.UserManager; import android.test.AndroidTestCase; public class UserManagerTests extends AndroidTestCase { public void testActiveUser() { UserManager manager = new UserManager(getContext()); User user = new User("test_id", "Indragie Karunaratne"); manager.setActiveUser(user); assertEquals(user, manager.getActiveUser()); // UserManager for the same Context should be accessing the // same shared data. UserManager anotherManager = new UserManager(getContext()); assertEquals(user, anotherManager.getActiveUser()); } }
gpl-3.0
NapoleonTheCake/notificatorro
source/app/src/main/java/com/cake/notificator/SettingsActivity.java
5812
package com.cake.notificator; import android.content.SharedPreferences; import android.os.Bundle; import android.support.v7.app.AppCompatActivity; import android.support.v7.widget.Toolbar; import android.widget.Switch; public class SettingsActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_settings); Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar); setSupportActionBar(toolbar); getSupportActionBar().setDisplayHomeAsUpEnabled(true); //read all settings here. SharedPreferences mPrefAppSettings = getSharedPreferences("appsettings", 0); //set vibration. ((Switch) findViewById(R.id.switch_Vibration)) .setChecked(mPrefAppSettings.getBoolean("vibration", false)); //set reset silent. ((Switch) findViewById(R.id.switch_Reset_Silent)) .setChecked(mPrefAppSettings.getBoolean("reset_silent", false)); //set reset delay. ((Switch) findViewById(R.id.switch_Reset_Delay)) .setChecked(mPrefAppSettings.getBoolean("reset_delay", false)); //set alt notifications. ((Switch) findViewById(R.id.switch_Alt_Notifications)) .setChecked(mPrefAppSettings.getBoolean("alt_notifications", false)); //set ignore title. ((Switch) findViewById(R.id.switch_Ignore_Title)) .setChecked(mPrefAppSettings.getBoolean("ignore_title", false)); //set quicknote prompt. ((Switch) findViewById(R.id.switch_Quicknote_Prompt)) .setChecked(mPrefAppSettings.getBoolean("quicknoteprompt", false)); //set quicknote silent. ((Switch) findViewById(R.id.switch_Quicknote_Silent)) .setChecked(mPrefAppSettings.getBoolean("isSilentQuick", false)); //set pinned priority. ((Switch) findViewById(R.id.switch_Persist_Prior)) .setChecked(mPrefAppSettings.getBoolean("persist_prior", false)); //set crazy vibration! ((Switch) findViewById(R.id.switch_Delayed_Crazyvibration)) .setChecked(mPrefAppSettings.getBoolean("crazyvib", false)); } //==================================== // //set all settings here. // @Override // public void onBackPressed() { // // append(); // // super.onBackPressed(); // } // // //handle taskbar back click here. // @Override // public boolean onOptionsItemSelected(MenuItem item) { // switch (item.getItemId()) { // case android.R.id.home: // this.onBackPressed(); // break; // } // // return true; // } @Override protected void onStop() { append(); super.onStop(); } //========================================================= private void append() { SharedPreferences.Editor mPrefAppSettingsEdit = getSharedPreferences("appsettings", 0).edit(); //set vibration. if (((Switch) findViewById(R.id.switch_Vibration)).isChecked()) { mPrefAppSettingsEdit.putBoolean("vibration", true).apply(); } else { mPrefAppSettingsEdit.putBoolean("vibration", false).apply(); } //set reset silent. if (((Switch) findViewById(R.id.switch_Reset_Silent)).isChecked()) { mPrefAppSettingsEdit.putBoolean("reset_silent", true).apply(); } else { mPrefAppSettingsEdit.putBoolean("reset_silent", false).apply(); } //set reset delay. if (((Switch) findViewById(R.id.switch_Reset_Delay)).isChecked()) { mPrefAppSettingsEdit.putBoolean("reset_delay", true).apply(); } else { mPrefAppSettingsEdit.putBoolean("reset_delay", false).apply(); } //set alt notifications. if (((Switch) findViewById(R.id.switch_Alt_Notifications)).isChecked()) { mPrefAppSettingsEdit.putBoolean("alt_notifications", true).apply(); } else { mPrefAppSettingsEdit.putBoolean("alt_notifications", false).apply(); } //set ignore title. if (((Switch) findViewById(R.id.switch_Ignore_Title)).isChecked()) { mPrefAppSettingsEdit.putBoolean("ignore_title", true).apply(); } else { mPrefAppSettingsEdit.putBoolean("ignore_title", false).apply(); } //set quicknote prompt. if (((Switch) findViewById(R.id.switch_Quicknote_Prompt)).isChecked()) { mPrefAppSettingsEdit.putBoolean("quicknoteprompt", true).apply(); } else { mPrefAppSettingsEdit.putBoolean("quicknoteprompt", false).apply(); } //set quicknote silent. if (((Switch) findViewById(R.id.switch_Quicknote_Silent)).isChecked()) { mPrefAppSettingsEdit.putBoolean("isSilentQuick", true).apply(); } else { mPrefAppSettingsEdit.putBoolean("isSilentQuick", false).apply(); } //set pinned priority. if (((Switch) findViewById(R.id.switch_Persist_Prior)).isChecked()) { mPrefAppSettingsEdit.putBoolean("persist_prior", true).apply(); } else { mPrefAppSettingsEdit.putBoolean("persist_prior", false).apply(); } //set crazy vibration! if (((Switch) findViewById(R.id.switch_Delayed_Crazyvibration)).isChecked()) mPrefAppSettingsEdit.putBoolean("crazyvib", true).apply(); else mPrefAppSettingsEdit.putBoolean("crazyvib", false).apply(); //// //echo done. // Toast.makeText(this, getString(R.string.settings_Apply_Success), Toast.LENGTH_SHORT).show(); } }
gpl-3.0
etomica/etomica
etomica-core/src/main/java/etomica/units/dimensions/Temperature.java
1632
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package etomica.units.dimensions; import java.io.ObjectStreamException; import etomica.units.Prefix; import etomica.units.SimpleUnit; import etomica.units.Unit; import etomica.units.systems.UnitSystem; /** * The temperature dimension. Internally, temperature always represents kT, * that is, the temperature multiplied by Boltzmann's constant; this gives a * quantity having dimensions of energy, and thus is in units of D-A^2/ps^2. However, * temperature is treated as fundamental when defining its Dimension. */ public final class Temperature extends Dimension { /** * Singleton instance of this class. */ public static final Dimension DIMENSION = new Temperature(); /** * The simulation unit for temperature, which as kT has dimensions * of energy and is D-A^2/ps^2. */ public static final Unit SIM_UNIT = new SimpleUnit(DIMENSION, 1.0, "sim temperature units", "kB D-A^2/ps^2", Prefix.NOT_ALLOWED); private Temperature() { super("Temperature", 0, 0, 0, 0, 1, 0, 0);// LMTCtNl } public Unit getUnit(UnitSystem unitSystem) { return unitSystem.temperature(); } /** * Required to guarantee singleton when deserializing. * * @return the singleton DIMENSION */ private Object readResolve() throws ObjectStreamException { return DIMENSION; } private static final long serialVersionUID = 1; }
mpl-2.0
itesla/ipst-core
computation-mpi/src/main/java/eu/itesla_project/computation/mpi/MpiNativeServices.java
810
/** * Copyright (c) 2016, All partners of the iTesla project (http://www.itesla-project.eu/consortium) * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package eu.itesla_project.computation.mpi; import java.util.List; /** * @author Geoffroy Jamgotchian <geoffroy.jamgotchian at rte-france.com> */ public interface MpiNativeServices { void initMpi(int coresPerRank, boolean verbose); void terminateMpi(); String getMpiVersion(); int getMpiCommSize(); void sendCommonFile(byte[] message); void startTasks(List<MpiTask> tasks); void checkTasksCompletion(List<MpiTask> runningTasks, List<MpiTask> completedTasks); }
mpl-2.0
therajanmaurya/self-service-app
app/src/test/java/org/mifos/mobilebanking/ThirdPartyTransferPresenterTest.java
3144
package org.mifos.mobilebanking; import android.content.Context; import org.junit.After; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.junit.runner.RunWith; import org.mifos.mobilebanking.api.DataManager; import org.mifos.mobilebanking.models.beneficary.Beneficiary; import org.mifos.mobilebanking.models.templates.account.AccountOptionsTemplate; import org.mifos.mobilebanking.presenters.ThirdPartyTransferPresenter; import org.mifos.mobilebanking.ui.views.ThirdPartyTransferView; import org.mifos.mobilebanking.util.RxSchedulersOverrideRule; import org.mockito.Mock; import org.mockito.junit.MockitoJUnitRunner; import java.util.List; import rx.Observable; import static org.mockito.Mockito.never; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; /** * Created by dilpreet on 24/7/17. */ @RunWith(MockitoJUnitRunner.class) public class ThirdPartyTransferPresenterTest { @Rule public final RxSchedulersOverrideRule mOverrideSchedulersRule = new RxSchedulersOverrideRule(); @Mock Context context; @Mock DataManager dataManager; @Mock ThirdPartyTransferView view; private AccountOptionsTemplate accountOptionsTemplate; private ThirdPartyTransferPresenter presenter; private List<Beneficiary> beneficiaryList; @Before public void setUp() { presenter = new ThirdPartyTransferPresenter(dataManager, context); presenter.attachView(view); accountOptionsTemplate = FakeRemoteDataSource.getAccountOptionsTemplate(); beneficiaryList = FakeRemoteDataSource.getBeneficiaries(); } @After public void tearDown() { presenter.detachView(); } @Test public void testTransferTemplate() { when(dataManager.getThirdPartyTransferTemplate()).thenReturn(Observable. just(accountOptionsTemplate)); when(dataManager.getBeneficiaryList()).thenReturn(Observable. just(beneficiaryList)); presenter.loadTransferTemplate(); verify(view).showProgress(); verify(view).hideProgress(); verify(view).showThirdPartyTransferTemplate(accountOptionsTemplate); verify(view).showBeneficiaryList(beneficiaryList); verify(view, never()).showError(context.getString( R.string.error_fetching_account_transfer_template)); } @Test public void testTransferTemplateFails() { when(dataManager.getThirdPartyTransferTemplate()).thenReturn(Observable. <AccountOptionsTemplate>error(new RuntimeException())); when(dataManager.getBeneficiaryList()).thenReturn(Observable. <List<Beneficiary>>error(new RuntimeException())); presenter.loadTransferTemplate(); verify(view).showProgress(); verify(view).hideProgress(); verify(view).showError(context.getString( R.string.error_fetching_account_transfer_template)); verify(view, never()).showThirdPartyTransferTemplate(accountOptionsTemplate); verify(view, never()).showBeneficiaryList(beneficiaryList); } }
mpl-2.0
adrienlauer/seed
security/specs/src/main/java/org/seedstack/seed/security/AuthorizationException.java
1521
/** * Copyright (c) 2013-2016, The SeedStack authors <http://seedstack.org> * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.seedstack.seed.security; /** * Base class for exceptions concerning authorization failure */ public class AuthorizationException extends RuntimeException { /** UID */ private static final long serialVersionUID = 1L; /** * Creates a new AuthorizationException. */ public AuthorizationException() { super(); } /** * Constructs a new AuthorizationException. * * @param message * the reason for the exception */ public AuthorizationException(String message) { super(message); } /** * Constructs a new AuthorizationException. * * @param cause * the underlying Throwable that caused this exception to be * thrown. */ public AuthorizationException(Throwable cause) { super(cause); } /** * Constructs a new AuthorizationException. * * @param message * the reason for the exception * @param cause * the underlying Throwable that caused this exception to be * thrown. */ public AuthorizationException(String message, Throwable cause) { super(message, cause); } }
mpl-2.0
hserv/coordinated-entry
hmis-survey-api/src/main/java/com/servinglynk/hmis/warehouse/core/model/SurveyCategories.java
801
package com.servinglynk.hmis.warehouse.core.model; import java.util.HashSet; import java.util.Set; import com.fasterxml.jackson.annotation.JsonProperty; import com.fasterxml.jackson.annotation.JsonRootName; @JsonRootName("surveyCategories") public class SurveyCategories extends PaginatedModel{ @JsonProperty("surveyCategories") Set<SurveyCategory> surveyCategories = new HashSet<SurveyCategory>(); public Set<SurveyCategory> getSurveyCategories() { return surveyCategories; } public void setSurveyCategories(Set<SurveyCategory> surveyProjects) { this.surveyCategories = surveyProjects; } public void addSurveyCategory(SurveyCategory surveyCategory) { this.surveyCategories.add(surveyCategory); } }
mpl-2.0
Appverse/appverse-builder-api
src/main/java/org/appverse/builder/web/rest/LogsResource.java
1367
package org.appverse.builder.web.rest; import ch.qos.logback.classic.Level; import ch.qos.logback.classic.LoggerContext; import com.codahale.metrics.annotation.Timed; import org.appverse.builder.web.rest.dto.LoggerDTO; import org.slf4j.LoggerFactory; import org.springframework.http.HttpStatus; import org.springframework.http.MediaType; import org.springframework.web.bind.annotation.*; import java.util.List; import java.util.stream.Collectors; /** * Controller for view and managing Log Level at runtime. */ @RestController @RequestMapping("/api") public class LogsResource { @RequestMapping(value = "/logs", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) @Timed public List<LoggerDTO> getList() { LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); return context.getLoggerList() .stream() .map(LoggerDTO::new) .collect(Collectors.toList()); } @RequestMapping(value = "/logs", method = RequestMethod.PUT) @ResponseStatus(HttpStatus.NO_CONTENT) @Timed public void changeLevel(@RequestBody LoggerDTO jsonLogger) { LoggerContext context = (LoggerContext) LoggerFactory.getILoggerFactory(); context.getLogger(jsonLogger.getName()).setLevel(Level.valueOf(jsonLogger.getLevel())); } }
mpl-2.0
etomica/etomica
etomica-core/src/main/java/etomica/lattice/AbstractLattice.java
1156
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package etomica.lattice; /** * Interface for a generic lattice, which is a collection of sites that can be * accessed individually via specification of a set of integers. Any object can * play the role of a site. */ public interface AbstractLattice<T> { /** * Dimension of the lattice. The value of D describes the number of * integers needed to specify a site (via the site method). */ public int D(); /** * Returns the site specified by the given index. The number of integers * in the index array must be equal to D, the lattice dimension. No specification * is made here regarding the identity of the instance returned by this method. * Thus repeated calls may return different object instances, or the same instance, * regardless of the argument. The concrete implementations of this class should * provide this specification. */ public T site(int[] index); }
mpl-2.0
GeorgiosGoniotakis/BluetoothWrapper
example/src/main/java/io/github/georgiosgoniotakis/bluetoothwrapper/example/MainActivity.java
8288
package io.github.georgiosgoniotakis.bluetoothwrapper.example; import android.app.Activity; import android.bluetooth.BluetoothAdapter; import android.bluetooth.BluetoothDevice; import android.content.Intent; import android.os.Bundle; import android.os.Handler; import android.os.Message; import android.support.v7.app.AppCompatActivity; import android.view.View; import android.widget.Button; import android.widget.TextView; import android.widget.Toast; import java.util.Set; import io.github.georgiosgoniotakis.bluetoothwrapper.library.core.BTExplorer; import io.github.georgiosgoniotakis.bluetoothwrapper.library.exceptions.BTDeviceNotFoundException; import io.github.georgiosgoniotakis.bluetoothwrapper.library.interfaces.BTNotifiable; import io.github.georgiosgoniotakis.bluetoothwrapper.library.interfaces.MessageCodes; import io.github.georgiosgoniotakis.bluetoothwrapper.library.properties.Mode; import io.github.georgiosgoniotakis.bluetoothwrapper.library.receivers.BTReceivers; /** * This is a demo activity for the BluetoothWrapper Android library. * Here, you can find a comprehensive example with all of the library's utilities. * <p> * Do not forget to implement {@link BTNotifiable} to receive updates by * the connection's {@link android.content.BroadcastReceiver} * * @author Georgios Goniotakis */ public class MainActivity extends AppCompatActivity implements BTNotifiable, View.OnClickListener { /** * The connection's flag. Can be any number greater than zero. */ private final static int REQUEST_ENABLE_BT = 1; /** * A {@link BTExplorer} instance to communicate with * the library */ private BTExplorer btExplorer; /* UI components */ private TextView currentMessage; /** * Create an instance of this class wherever you want * notifications about the state of the Bluetooth * adapter and connection. */ private BTReceivers btReceivers; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); Button sendButton = (Button) findViewById(R.id.sendButton); Button connectButton = (Button) findViewById(R.id.connectButton); Button disconnectButton = (Button) findViewById(R.id.disconnectButton); currentMessage = (TextView) findViewById(R.id.currentMessage); sendButton.setOnClickListener(this); connectButton.setOnClickListener(this); disconnectButton.setOnClickListener(this); /* Initialize receivers */ btReceivers = new BTReceivers(this, true); btReceivers.registerReceivers(); btExplorer = BTExplorer.getInstance(btHandler); // Get Singleton Instance /* The user's device does not support Bluetooth functionality. Please disable all Bluetooth-related features. */ if(!btExplorer.isSupported()){ Toast.makeText(this, "Your device does not support Bluetooth functionality.", Toast.LENGTH_LONG).show(); } /* Currently, the user has their Bluetooth disabled. Show them a popup message to enable it. Do not continue calling the library's methods if the user insists on having the connection disabled. */ if(!btExplorer.isEnabled()){ Intent enableBT = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBT, REQUEST_ENABLE_BT); } /* This line outputs a list with the available devices in the information logcat and stores it into a String array */ String[][] info = btExplorer.deviceList(true); /* Here you can store all the paired devices if you want to use them in any other place inside your code. */ Set<BluetoothDevice> pairedDevices = btExplorer.pairedDevices(); } /** * Implements a handler to let the two classes communicate. In this way * the logic class can notify this class when an incoming message is * available and thus the UI is updated. */ private final Handler btHandler = new Handler() { @Override public void handleMessage(Message msg) { switch (msg.what) { case MessageCodes.MESSAGE_READ: currentMessage.setText(msg.getData().getString(MessageCodes.INCOMING_MESSAGE)); break; } } }; /** * The interaction with the Bluetooth connection popup is going to * trigger this method. * * @param requestCode * @param resultCode * @param intent */ protected void onActivityResult(int requestCode, int resultCode, Intent intent) { if (resultCode == 0) { Toast.makeText(this, "Bluetooth has to be enabled in order to use this application.", Toast.LENGTH_LONG).show(); } else { Toast.makeText(this, "User successfully enabled his/her Bluetooth connection.", Toast.LENGTH_LONG).show(); } } /** * Gives four basic examples of connecting, disconnecting, sending a message * and restarting a connection with a device. * * @param v */ @Override public void onClick(View v) { int id = v.getId(); switch (id) { case R.id.connectButton: /* Perform a new secure connection to a device giving the MAC address */ try { if (!btExplorer.isSupported()) { Toast.makeText(this, "Bluetooth not supported", Toast.LENGTH_SHORT).show(); } else if (!btExplorer.isEnabled()) { Intent enableBT = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE); startActivityForResult(enableBT, REQUEST_ENABLE_BT); } else { btExplorer.connect("00:00:00:00:00:00", Mode.SECURE); } } catch (BTDeviceNotFoundException e) { /* Device not available any more, inform the user*/ Toast.makeText(this, "Please choose another device from the list.", Toast.LENGTH_LONG).show(); } break; case R.id.disconnectButton: btExplorer.disconnect(); // Terminate the current connection break; case R.id.sendButton: btExplorer.send("OPEN"); // Send a message to the device break; } } /** * Always remember to unregister receivers on stop. Also, consider * controlling the receivers' state when {@link Activity#onPause()} * {@link Activity#onResume()} etc. */ @Override protected void onStop() { super.onStop(); btReceivers.unregisterReceivers(); } /** * This is called whenever an update on the adapter's * state occurs. * * @param adapterState The status code of the BT adapter */ @Override public void onAdapterStateChange(int adapterState) { if (adapterState == BluetoothAdapter.STATE_TURNING_OFF) { Toast.makeText(this, "Please re-enable bluetooth.", Toast.LENGTH_LONG).show(); btExplorer.disconnect(); } else if (adapterState == BluetoothAdapter.STATE_TURNING_ON) { Toast.makeText(this, "Thank you for enabling you bluetooth.", Toast.LENGTH_LONG).show(); } } /** * This is called whenever an update on the connection's * state occurs. * * @param deviceState The status code of the connection */ @Override public void onDeviceStateChange(String deviceState) { if (deviceState.equals(BluetoothDevice.ACTION_ACL_CONNECTED)) { Toast.makeText(this, "BT Device connected", Toast.LENGTH_LONG).show(); } else if (deviceState.equals(BluetoothDevice.ACTION_ACL_DISCONNECTED)) { Toast.makeText(this, "BT Device disconnected", Toast.LENGTH_LONG).show(); btExplorer.disconnect(); } } }
mpl-2.0
zamojski/TowerCollector
app/src/main/java/info/zamojski/soft/towercollector/collector/converters/CellIdentityConverter.java
7256
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package info.zamojski.soft.towercollector.collector.converters; import android.os.Build; import android.telephony.CellIdentityCdma; import android.telephony.CellIdentityGsm; import android.telephony.CellIdentityLte; import android.telephony.CellIdentityNr; import android.telephony.CellIdentityTdscdma; import android.telephony.CellIdentityWcdma; import android.telephony.CellInfo; import android.telephony.CellInfoCdma; import android.telephony.CellInfoGsm; import android.telephony.CellInfoLte; import android.telephony.CellInfoNr; import android.telephony.CellInfoTdscdma; import android.telephony.CellInfoWcdma; import info.zamojski.soft.towercollector.MyApplication; import info.zamojski.soft.towercollector.collector.validators.specific.WcdmaCellValidator; import info.zamojski.soft.towercollector.model.Cell; import timber.log.Timber; public class CellIdentityConverter { private final WcdmaCellValidator wcdmaValidator; public CellIdentityConverter(WcdmaCellValidator wcdmaValidator) { this.wcdmaValidator = wcdmaValidator; } public Cell convert(CellInfo cellInfo) { Cell cell = new Cell(); cell.setNeighboring(!cellInfo.isRegistered()); if (cellInfo instanceof CellInfoGsm) { CellInfoGsm gsmCellInfo = (CellInfoGsm) cellInfo; CellIdentityGsm identity = gsmCellInfo.getCellIdentity(); if (wcdmaValidator.isValid(identity)) { Timber.d("update(): Updating WCDMA reported by API 17 as GSM"); cell.setWcdmaCellInfo(identity.getMcc(), identity.getMnc(), identity.getLac(), identity.getCid(), identity.getPsc()); } else { cell.setGsmCellInfo(identity.getMcc(), identity.getMnc(), identity.getLac(), identity.getCid()); } } else if (cellInfo instanceof CellInfoWcdma) { CellInfoWcdma wcdmaCellInfo = (CellInfoWcdma) cellInfo; CellIdentityWcdma identity = wcdmaCellInfo.getCellIdentity(); cell.setWcdmaCellInfo(identity.getMcc(), identity.getMnc(), identity.getLac(), identity.getCid(), identity.getPsc()); } else if (cellInfo instanceof CellInfoLte) { CellInfoLte lteCellInfo = (CellInfoLte) cellInfo; CellIdentityLte identity = lteCellInfo.getCellIdentity(); cell.setLteCellInfo(identity.getMcc(), identity.getMnc(), identity.getTac(), identity.getCi(), identity.getPci()); } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && cellInfo instanceof CellInfoNr) { CellInfoNr lteCellInfo = (CellInfoNr) cellInfo; CellIdentityNr identity = (CellIdentityNr) lteCellInfo.getCellIdentity(); cell.setNrCellInfo(identity.getMccString(), identity.getMncString(), identity.getTac(), identity.getNci(), identity.getPci()); } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && cellInfo instanceof CellInfoTdscdma) { CellInfoTdscdma lteCellInfo = (CellInfoTdscdma) cellInfo; CellIdentityTdscdma identity = lteCellInfo.getCellIdentity(); cell.setTdscdmaCellInfo(identity.getMccString(), identity.getMncString(), identity.getLac(), identity.getCid(), identity.getCpid()); } else if (cellInfo instanceof CellInfoCdma) { CellInfoCdma cdmaCellInfo = (CellInfoCdma) cellInfo; CellIdentityCdma identity = cdmaCellInfo.getCellIdentity(); cell.setCdmaCellInfo(identity.getSystemId(), identity.getNetworkId(), identity.getBasestationId()); } else { throw new UnsupportedOperationException("Cell identity type not supported `" + cellInfo.getClass().getName() + "`"); } return cell; } public String createCellKey(Cell cell) { StringBuilder sb = new StringBuilder(); sb.append(cell.getMcc()) .append("_").append(cell.getMnc()) .append("_").append(cell.getLac()) .append("_").append(cell.getCid()); return sb.toString(); } public String createCellKey(CellInfo cellInfo) { StringBuilder sb = new StringBuilder(); if (cellInfo instanceof CellInfoGsm) { CellInfoGsm gsmCellInfo = (CellInfoGsm) cellInfo; CellIdentityGsm identity = gsmCellInfo.getCellIdentity(); sb.append(identity.getMcc()) .append("_").append(identity.getMnc()) .append("_").append(identity.getLac()) .append("_").append(identity.getCid()); } else if (cellInfo instanceof CellInfoWcdma) { CellInfoWcdma wcdmaCellInfo = (CellInfoWcdma) cellInfo; CellIdentityWcdma identity = wcdmaCellInfo.getCellIdentity(); sb.append(identity.getMcc()) .append("_").append(identity.getMnc()) .append("_").append(identity.getLac()) .append("_").append(identity.getCid()); } else if (cellInfo instanceof CellInfoLte) { CellInfoLte lteCellInfo = (CellInfoLte) cellInfo; CellIdentityLte identity = lteCellInfo.getCellIdentity(); sb.append(identity.getMcc()) .append("_").append(identity.getMnc()) .append("_").append(identity.getTac()) .append("_").append(identity.getCi()); } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && cellInfo instanceof CellInfoNr) { CellInfoNr nrCellInfo = (CellInfoNr) cellInfo; CellIdentityNr identity = (CellIdentityNr) nrCellInfo.getCellIdentity(); sb.append(identity.getMccString()) .append("_").append(identity.getMncString()) .append("_").append(identity.getTac()) .append("_").append(identity.getNci()); } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && cellInfo instanceof CellInfoTdscdma) { CellInfoTdscdma tdscdmaCellInfo = (CellInfoTdscdma) cellInfo; CellIdentityTdscdma identity = tdscdmaCellInfo.getCellIdentity(); sb.append(identity.getMccString()) .append("_").append(identity.getMncString()) .append("_").append(identity.getLac()) .append("_").append(identity.getCid()); } else if (cellInfo instanceof CellInfoCdma) { CellInfoCdma cdmaCellInfo = (CellInfoCdma) cellInfo; CellIdentityCdma identity = cdmaCellInfo.getCellIdentity(); sb.append(Cell.UNKNOWN_CID) .append("_").append(identity.getSystemId()) .append("_").append(identity.getNetworkId()) .append("_").append(identity.getBasestationId()); } else { Exception ex = new UnsupportedOperationException("Cell identity type not supported `" + cellInfo.getClass().getName() + "` = `" + cellInfo.toString() + "`"); Timber.e(ex); MyApplication.handleSilentException(ex); } return sb.toString(); } }
mpl-2.0
syncthing/syncthing-android
app/src/main/java/com/nutomic/syncthingandroid/service/EventProcessor.java
12325
package com.nutomic.syncthingandroid.service; import android.app.PendingIntent; import android.content.ContentResolver; import android.content.Context; import android.content.Intent; import android.content.SharedPreferences; import android.media.MediaScannerConnection; import android.net.Uri; import android.os.Handler; import android.os.Looper; import android.provider.MediaStore; import android.util.Log; import androidx.core.util.Consumer; import com.annimon.stream.Stream; import com.nutomic.syncthingandroid.BuildConfig; import com.nutomic.syncthingandroid.R; import com.nutomic.syncthingandroid.SyncthingApp; import com.nutomic.syncthingandroid.activities.DeviceActivity; import com.nutomic.syncthingandroid.activities.FolderActivity; import com.nutomic.syncthingandroid.model.CompletionInfo; import com.nutomic.syncthingandroid.model.Device; import com.nutomic.syncthingandroid.model.Event; import com.nutomic.syncthingandroid.model.Folder; import java.io.File; import java.util.List; import java.util.Map; import java.util.concurrent.TimeUnit; import javax.inject.Inject; /** * Run by the syncthing service to convert syncthing events into local broadcasts. * * It uses {@link RestApi#getEvents} to read the pending events and wait for new events. */ public class EventProcessor implements Runnable, RestApi.OnReceiveEventListener { private static final String TAG = "EventProcessor"; private static final String PREF_LAST_SYNC_ID = "last_sync_id"; /** * Minimum interval in seconds at which the events are polled from syncthing and processed. * This intervall will not wake up the device to save battery power. */ private static final long EVENT_UPDATE_INTERVAL = TimeUnit.SECONDS.toMillis(15); /** * Use the MainThread for all callbacks and message handling * or we have to track down nasty threading problems. */ private final Handler mMainThreadHandler = new Handler(Looper.getMainLooper()); private volatile long mLastEventId = 0; private volatile boolean mShutdown = true; private final Context mContext; private final RestApi mApi; @Inject SharedPreferences mPreferences; @Inject NotificationHandler mNotificationHandler; public EventProcessor(Context context, RestApi api) { ((SyncthingApp) context.getApplicationContext()).component().inject(this); mContext = context; mApi = api; } @Override public void run() { // Restore the last event id if the event processor may have been restarted. if (mLastEventId == 0) { mLastEventId = mPreferences.getLong(PREF_LAST_SYNC_ID, 0); } // First check if the event number ran backwards. // If that's the case we've to start at zero because syncthing was restarted. mApi.getEvents(0, 1, new RestApi.OnReceiveEventListener() { @Override public void onEvent(Event event) { } @Override public void onDone(long lastId) { if (lastId < mLastEventId) mLastEventId = 0; Log.d(TAG, "Reading events starting with id " + mLastEventId); mApi.getEvents(mLastEventId, 0, EventProcessor.this); } }); } /** * Performs the actual event handling. */ @Override public void onEvent(Event event) { switch (event.type) { case "ConfigSaved": if (mApi != null) { Log.v(TAG, "Forwarding ConfigSaved event to RestApi to get the updated config."); mApi.reloadConfig(); } break; case "PendingDevicesChanged": mapNullable((List<Map<String,String>>) event.data.get("added"), this::onPendingDevicesChanged); break; case "FolderCompletion": CompletionInfo completionInfo = new CompletionInfo(); completionInfo.completion = (Double) event.data.get("completion"); mApi.setCompletionInfo( (String) event.data.get("device"), // deviceId (String) event.data.get("folder"), // folderId completionInfo ); break; case "PendingFoldersChanged": mapNullable((List<Map<String,String>>) event.data.get("added"), this::onPendingFoldersChanged); break; case "ItemFinished": String folder = (String) event.data.get("folder"); String folderPath = null; for (Folder f : mApi.getFolders()) { if (f.id.equals(folder)) { folderPath = f.path; } } File updatedFile = new File(folderPath, (String) event.data.get("item")); if (!"delete".equals(event.data.get("action"))) { Log.i(TAG, "Rescanned file via MediaScanner: " + updatedFile.toString()); MediaScannerConnection.scanFile(mContext, new String[]{updatedFile.getPath()}, null, null); } else { // https://stackoverflow.com/a/29881556/1837158 Log.i(TAG, "Deleted file from MediaStore: " + updatedFile.toString()); Uri contentUri = MediaStore.Files.getContentUri("external"); ContentResolver resolver = mContext.getContentResolver(); resolver.delete(contentUri, MediaStore.Images.ImageColumns.DATA + " LIKE ?", new String[]{updatedFile.getPath()}); } break; case "Ping": // Ignored. break; case "DeviceConnected": case "DeviceDisconnected": case "DeviceDiscovered": case "DownloadProgress": case "FolderPaused": case "FolderScanProgress": case "FolderSummary": case "ItemStarted": case "LocalIndexUpdated": case "LoginAttempt": case "RemoteDownloadProgress": case "RemoteIndexUpdated": case "Starting": case "StartupComplete": case "StateChanged": if (BuildConfig.DEBUG) { Log.v(TAG, "Ignored event " + event.type + ", data " + event.data); } break; default: Log.v(TAG, "Unhandled event " + event.type); } } @Override public void onDone(long id) { if (mLastEventId < id) { mLastEventId = id; // Store the last EventId in case we get killed mPreferences.edit().putLong(PREF_LAST_SYNC_ID, mLastEventId).apply(); } synchronized (mMainThreadHandler) { if (!mShutdown) { mMainThreadHandler.removeCallbacks(this); mMainThreadHandler.postDelayed(this, EVENT_UPDATE_INTERVAL); } } } public void start() { Log.d(TAG, "Starting event processor."); // Remove all pending callbacks and add a new one. This makes sure that only one // event poller is running at any given time. synchronized (mMainThreadHandler) { mShutdown = false; mMainThreadHandler.removeCallbacks(this); mMainThreadHandler.postDelayed(this, EVENT_UPDATE_INTERVAL); } } public void stop() { Log.d(TAG, "Stopping event processor."); synchronized (mMainThreadHandler) { mShutdown = true; mMainThreadHandler.removeCallbacks(this); } } private void onPendingDevicesChanged(Map<String, String> added) { String deviceId = added.get("deviceID"); String deviceName = added.get("name"); String deviceAddress = added.get("address"); if (deviceId == null) { return; } Log.d(TAG, "Unknown device " + deviceName + "(" + deviceId + ") wants to connect"); String title = mContext.getString(R.string.device_rejected, deviceName.isEmpty() ? deviceId.substring(0, 7) : deviceName); int notificationId = mNotificationHandler.getNotificationIdFromText(title); // Prepare "accept" action. Intent intentAccept = new Intent(mContext, DeviceActivity.class) .putExtra(DeviceActivity.EXTRA_NOTIFICATION_ID, notificationId) .putExtra(DeviceActivity.EXTRA_IS_CREATE, true) .putExtra(DeviceActivity.EXTRA_DEVICE_ID, deviceId) .putExtra(DeviceActivity.EXTRA_DEVICE_NAME, deviceName); PendingIntent piAccept = PendingIntent.getActivity(mContext, notificationId, intentAccept, PendingIntent.FLAG_UPDATE_CURRENT); // Prepare "ignore" action. Intent intentIgnore = new Intent(mContext, SyncthingService.class) .putExtra(SyncthingService.EXTRA_NOTIFICATION_ID, notificationId) .putExtra(SyncthingService.EXTRA_DEVICE_ID, deviceId) .putExtra(SyncthingService.EXTRA_DEVICE_NAME, deviceName) .putExtra(SyncthingService.EXTRA_DEVICE_ADDRESS, deviceAddress); intentIgnore.setAction(SyncthingService.ACTION_IGNORE_DEVICE); PendingIntent piIgnore = PendingIntent.getService(mContext, 0, intentIgnore, PendingIntent.FLAG_UPDATE_CURRENT); // Show notification. mNotificationHandler.showConsentNotification(notificationId, title, piAccept, piIgnore); } private void onPendingFoldersChanged(Map<String, String> added) { String deviceId = added.get("deviceID"); String folderId = added.get("folderID"); String folderLabel = added.get("folderLabel"); if (deviceId == null || folderId == null) { return; } Log.d(TAG, "Device " + deviceId + " wants to share folder " + folderLabel + " (" + folderId + ")"); // Find the deviceName corresponding to the deviceId String deviceName = null; for (Device d : mApi.getDevices(false)) { if (d.deviceID.equals(deviceId)) { deviceName = d.getDisplayName(); break; } } String title = mContext.getString(R.string.folder_rejected, deviceName, folderLabel.isEmpty() ? folderId : folderLabel + " (" + folderId + ")"); int notificationId = mNotificationHandler.getNotificationIdFromText(title); // Prepare "accept" action. boolean isNewFolder = Stream.of(mApi.getFolders()) .noneMatch(f -> f.id.equals(folderId)); Intent intentAccept = new Intent(mContext, FolderActivity.class) .putExtra(FolderActivity.EXTRA_NOTIFICATION_ID, notificationId) .putExtra(FolderActivity.EXTRA_IS_CREATE, isNewFolder) .putExtra(FolderActivity.EXTRA_DEVICE_ID, deviceId) .putExtra(FolderActivity.EXTRA_FOLDER_ID, folderId) .putExtra(FolderActivity.EXTRA_FOLDER_LABEL, folderLabel); PendingIntent piAccept = PendingIntent.getActivity(mContext, notificationId, intentAccept, PendingIntent.FLAG_UPDATE_CURRENT); // Prepare "ignore" action. Intent intentIgnore = new Intent(mContext, SyncthingService.class) .putExtra(SyncthingService.EXTRA_NOTIFICATION_ID, notificationId) .putExtra(SyncthingService.EXTRA_DEVICE_ID, deviceId) .putExtra(SyncthingService.EXTRA_FOLDER_ID, folderId) .putExtra(SyncthingService.EXTRA_FOLDER_LABEL, folderLabel); intentIgnore.setAction(SyncthingService.ACTION_IGNORE_FOLDER); PendingIntent piIgnore = PendingIntent.getService(mContext, 0, intentIgnore, PendingIntent.FLAG_UPDATE_CURRENT); // Show notification. mNotificationHandler.showConsentNotification(notificationId, title, piAccept, piIgnore); } private <T> void mapNullable(List<T> l, Consumer<T> c) { if (l != null) { for (T m : l) { c.accept(m); } } } }
mpl-2.0
pfschwartz/openelisglobal-core
app/src/us/mn/state/health/lims/result/action/BatchResultsEntryViewAction.java
20712
/** * The contents of this file are subject to the Mozilla Public License * Version 1.1 (the "License"); you may not use this file except in * compliance with the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" * basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the * License for the specific language governing rights and limitations under * the License. * * The Original Code is OpenELIS code. * * Copyright (C) The Minnesota Department of Health. All Rights Reserved. */ package us.mn.state.health.lims.result.action; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Collections; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.apache.commons.beanutils.PropertyUtils; import org.apache.struts.Globals; import org.apache.struts.action.ActionForm; import org.apache.struts.action.ActionForward; import org.apache.struts.action.ActionMapping; import org.apache.struts.action.ActionMessages; import us.mn.state.health.lims.analysis.dao.AnalysisDAO; import us.mn.state.health.lims.analysis.daoimpl.AnalysisDAOImpl; import us.mn.state.health.lims.analysis.valueholder.Analysis; import us.mn.state.health.lims.common.action.BaseAction; import us.mn.state.health.lims.common.action.BaseActionForm; import us.mn.state.health.lims.common.exception.LIMSRuntimeException; import us.mn.state.health.lims.common.log.LogEvent; import us.mn.state.health.lims.common.util.DateUtil; import us.mn.state.health.lims.common.util.StringUtil; import us.mn.state.health.lims.common.util.SystemConfiguration; import us.mn.state.health.lims.common.util.validator.ActionError; import us.mn.state.health.lims.dictionary.dao.DictionaryDAO; import us.mn.state.health.lims.dictionary.daoimpl.DictionaryDAOImpl; import us.mn.state.health.lims.dictionary.valueholder.Dictionary; import us.mn.state.health.lims.login.dao.UserTestSectionDAO; import us.mn.state.health.lims.login.daoimpl.UserTestSectionDAOImpl; import us.mn.state.health.lims.note.dao.NoteDAO; import us.mn.state.health.lims.note.daoimpl.NoteDAOImpl; import us.mn.state.health.lims.note.valueholder.Note; import us.mn.state.health.lims.patient.dao.PatientDAO; import us.mn.state.health.lims.patient.daoimpl.PatientDAOImpl; import us.mn.state.health.lims.patient.valueholder.Patient; import us.mn.state.health.lims.person.dao.PersonDAO; import us.mn.state.health.lims.person.daoimpl.PersonDAOImpl; import us.mn.state.health.lims.person.valueholder.Person; import us.mn.state.health.lims.referencetables.valueholder.ReferenceTables; import us.mn.state.health.lims.result.dao.ResultDAO; import us.mn.state.health.lims.result.daoimpl.ResultDAOImpl; import us.mn.state.health.lims.result.valueholder.Result; import us.mn.state.health.lims.result.valueholder.ResultsEntryTestResultComparator; import us.mn.state.health.lims.result.valueholder.Sample_TestAnalyte; import us.mn.state.health.lims.result.valueholder.TestAnalyte_TestResults; import us.mn.state.health.lims.sample.dao.SampleDAO; import us.mn.state.health.lims.sample.daoimpl.SampleDAOImpl; import us.mn.state.health.lims.sample.valueholder.Sample; import us.mn.state.health.lims.samplehuman.dao.SampleHumanDAO; import us.mn.state.health.lims.samplehuman.daoimpl.SampleHumanDAOImpl; import us.mn.state.health.lims.samplehuman.valueholder.SampleHuman; import us.mn.state.health.lims.sampleitem.dao.SampleItemDAO; import us.mn.state.health.lims.sampleitem.daoimpl.SampleItemDAOImpl; import us.mn.state.health.lims.sampleitem.valueholder.SampleItem; import us.mn.state.health.lims.sampleorganization.dao.SampleOrganizationDAO; import us.mn.state.health.lims.sampleorganization.daoimpl.SampleOrganizationDAOImpl; import us.mn.state.health.lims.sampleorganization.valueholder.SampleOrganization; import us.mn.state.health.lims.test.dao.TestDAO; import us.mn.state.health.lims.test.daoimpl.TestDAOImpl; import us.mn.state.health.lims.test.valueholder.Test; import us.mn.state.health.lims.test.valueholder.TestComparator; import us.mn.state.health.lims.test.valueholder.TestSectionComparator; import us.mn.state.health.lims.testanalyte.dao.TestAnalyteDAO; import us.mn.state.health.lims.testanalyte.daoimpl.TestAnalyteDAOImpl; import us.mn.state.health.lims.testanalyte.valueholder.TestAnalyte; import us.mn.state.health.lims.testresult.dao.TestResultDAO; import us.mn.state.health.lims.testresult.daoimpl.TestResultDAOImpl; import us.mn.state.health.lims.testresult.valueholder.TestResult; /** * @author diane benz * //AIS - bugzilla 1863 * //AIS - bugzilla 1891 * To change this generated comment edit the template variable "typecomment": * Window>Preferences>Java>Templates. To enable and disable the creation of type * comments go to Window>Preferences>Java>Code Generation. * bugzilla 1992 - cleanup (remove counter definitions to stay consistent) * bugzilla 2614 - fix to work for NB samples */ public class BatchResultsEntryViewAction extends BaseAction { private boolean isNew = false; protected ActionForward performAction(ActionMapping mapping, ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception { // The first job is to determine if we are coming to this action with an // ID parameter in the request. If there is no parameter, we are // creating a new Result. // If there is a parameter present, we should bring up an existing // Result to edit. String id = request.getParameter(ID); String forward = FWD_SUCCESS; request.setAttribute(ALLOW_EDITS_KEY, "true"); request.setAttribute(PREVIOUS_DISABLED, "true"); request.setAttribute(NEXT_DISABLED, "true"); BaseActionForm dynaForm = (BaseActionForm) form; //bugzilla 2028 sub bugzilla 2036 if coming back from Qa Events selectedTestId will be request parameter //bugzilla 2053 naming of static variable changed String selectedTestId = (String)request.getParameter("QA_EVENTS_ENTRY_ROUTING_FROM_BATCH_RESULTS_ENTRY_PARAM_TEST_ID");; if (StringUtil.isNullorNill(selectedTestId)) { selectedTestId = (String) dynaForm.get("selectedTestId"); } String receivedDateForDisplay = (String) dynaForm .get("receivedDateForDisplay"); String currentDate = (String) dynaForm.get("currentDate"); List testSections = (List) dynaForm.get("testSections"); List tests = (List) dynaForm.get("tests"); //bugzilla 2379 String selectedTestSectionId = (String)dynaForm.get("selectedTestSectionId"); //bugzilla 2379 TestDAO testDAO = new TestDAOImpl(); UserTestSectionDAO userTestSectionDAO = new UserTestSectionDAOImpl(); if (!StringUtil.isNullorNill(selectedTestSectionId)) { tests = testDAO.getTestsByTestSection(selectedTestSectionId); } else { testSections = userTestSectionDAO.getAllUserTestSections(request); tests = userTestSectionDAO.getAllUserTests(request, true); } ActionMessages errors = null; // bugzilla #1346 add ability to hover over accession number and // view patient/person information (first and last name and external id) //bugzilla 1387 renamed so more generic //bugzilla 2614 allow for NB domain samples // initialize the form dynaForm.initialize(mapping); List sample_Tas = new ArrayList(); List sample_Tasv = new ArrayList(); List sample_Tasvt = new ArrayList(); List testAnalyte_TestResults = new ArrayList(); if (!StringUtil.isNullorNill(selectedTestId)) { Test test = new Test(); test.setId(selectedTestId); testDAO.getData(test); List testAnalytes = new ArrayList(); TestAnalyteDAO testAnalyteDAO = new TestAnalyteDAOImpl(); testAnalytes = testAnalyteDAO.getAllTestAnalytesPerTest(test); try { List analyses = new ArrayList(); AnalysisDAO analysisDAO = new AnalysisDAOImpl(); //bugzilla 2227 analyses = analysisDAO.getAllMaxRevisionAnalysesPerTest(test); SampleDAO sampleDAO = new SampleDAOImpl(); ResultDAO resultDAO = new ResultDAOImpl(); PatientDAO patientDAO = new PatientDAOImpl(); PersonDAO personDAO = new PersonDAOImpl(); SampleItemDAO sampleItemDAO = new SampleItemDAOImpl(); SampleHumanDAO sampleHumanDAO = new SampleHumanDAOImpl(); SampleOrganizationDAO sampleOrganizationDAO = new SampleOrganizationDAOImpl(); NoteDAO noteDAO = new NoteDAOImpl(); Patient patient = new Patient(); Person person = new Person(); SampleHuman sampleHuman = new SampleHuman(); SampleOrganization sampleOrganization = new SampleOrganization(); Analysis analysis = null; SampleItem sampleItem = null; //bugzilla 2227 String sampleHasTestRevisions = "false"; for (int i = 0; i < analyses.size(); i++) { analysis = (Analysis) analyses.get(i); //bugzilla 2227 sampleHasTestRevisions = "false"; //bugzilla 1942 status results verified changed to released (logic is to say if analysis status is not yet released then go ahead) if(!StringUtil.isNullorNill(analysis.getStatus()) && !analysis.getStatus().equals(SystemConfiguration.getInstance() .getAnalysisStatusReleased()) ) { sampleItem = (SampleItem) analysis.getSampleItem(); //System.out.println("This is sampleItem " + sampleItem); if (sampleItem != null) { //bugzilla 1773 need to store sample not sampleId for use in sorting String sampleId = sampleItem.getSample().getId(); Sample sample = new Sample(); //bgm - bugzilla 1639 check sampleId first before using... if(sampleId !=null){ sample.setId(sampleId); sampleDAO.getData(sample); //bugzilla 2227 if (!analysis.getRevision().equals("0")) { sampleHasTestRevisions = "true"; } // bugzilla #1346 add ability to hover over accession // number and // view patient/person information (first and last name // and external id) //bugzilla 2614 allow for NB domain samples // bugzilla #1346 add ability to hover over // accession number and // view patient/person information (first and last // name and external id) if (!StringUtil.isNullorNill(sample.getId())) { //bugzilla 2252 sampleHuman = new SampleHuman(); patient = new Patient(); person = new Person(); sampleHuman.setSampleId(sample.getId()); sampleHumanDAO.getDataBySample(sampleHuman); sampleOrganization.setSample(sample); sampleOrganizationDAO.getDataBySample(sampleOrganization); if(sampleHuman !=null){ patient.setId(sampleHuman.getPatientId()); if(patient.getId() !=null) { patientDAO.getData(patient); person = patient.getPerson(); personDAO.getData(person); } } Sample_TestAnalyte sample_Ta = new Sample_TestAnalyte(); Sample_TestAnalyte sample_Tav = new Sample_TestAnalyte(); Sample_TestAnalyte sample_Tavt = new Sample_TestAnalyte(); // System.out.println("This is // sample.getReceivedDate " // + sample.getReceivedDate()); // System.out.println("This is // receivedDateForDisplay " // + receivedDateForDisplay); String locale = SystemConfiguration.getInstance() .getDefaultLocale().toString(); java.sql.Date convertedReceivedDate = DateUtil.convertStringDateToSqlDate( receivedDateForDisplay, locale); if (sample.getReceivedDate().equals(convertedReceivedDate) || StringUtil.isNullorNill(receivedDateForDisplay)) { // exclude samples for which results have been // entered // (status code?? in analysis or sample) sample_Ta.setSample(sample); // bugzilla #1346 add ability to hover over // accession number and // view patient/person information (first and // last name and external id) // display N/A if no first, last name if (person.getFirstName() == null && person.getLastName() == null) { person.setFirstName(NOT_APPLICABLE); person.setLastName(BLANK); } if (person.getFirstName() != null && person.getLastName() == null) { person.setLastName(BLANK); } if (person.getFirstName() == null && person.getLastName() != null) { person.setFirstName(BLANK); } sample_Ta.setPerson(person); // display N/A if no externalId if (patient.getExternalId() == null) { patient.setExternalId(NOT_APPLICABLE); } sample_Ta.setPatient(patient); sample_Ta.setAnalysis(analysis); sample_Ta.setTestAnalytes(testAnalytes); List results = new ArrayList(); List resultValues = new ArrayList(); List resultValuesn = new ArrayList(); List resultValuest = new ArrayList(); List resultIds = new ArrayList(); List resultLastupdatedList = new ArrayList(); List sampleResultHasNotesList = new ArrayList(); for (int j = 0; j < testAnalytes.size(); j++) { TestAnalyte ta = (TestAnalyte) testAnalytes .get(j); Result result = new Result(); resultDAO.getResultByAnalysisAndAnalyte( result, analysis, ta); if (result != null) { if (result.getTestResult() != null) { resultIds.add(result.getId()); TestResult tr = result .getTestResult(); String trId = tr.getId(); results.add(trId); if (tr.getTestResultType().equalsIgnoreCase(SystemConfiguration.getInstance().getNumericType())){ resultValues.add(result.getValue()); resultValuesn.add(result.getValue()); resultValuest.add(""); }else if(tr.getTestResultType().equalsIgnoreCase(SystemConfiguration.getInstance().getTiterType())){ String resultValue = result.getValue(); resultValue = resultValue.substring(2,resultValue.length()); resultValues.add(resultValue); resultValuest.add(resultValue); resultValuesn.add(""); }else{ resultValues.add(""); resultValuesn.add(""); resultValuest.add(""); } resultLastupdatedList.add(result .getLastupdated()); } else { results.add(""); resultIds.add("0"); resultValues.add(""); resultValuesn.add(""); resultValuest.add(""); resultLastupdatedList .add(new Timestamp( System.currentTimeMillis())); } } else { results.add(""); resultIds.add("0"); resultValues.add(""); resultValuesn.add(""); resultValuest.add(""); resultLastupdatedList .add(new Timestamp( System.currentTimeMillis())); } // bugzilla 1942 now get the Notes for this result if // exist/ we need to know about notes on batch result entry // in order to determine whether an existing result is allowed to be deleted if (result != null && result.getTestResult() != null) { Note note = new Note(); List notesByResult = new ArrayList(); note.setReferenceId(result.getId()); //bugzilla 1922 //bugzilla 2571 go through ReferenceTablesDAO to get reference tables info ReferenceTables referenceTables = new ReferenceTables(); referenceTables.setId(SystemConfiguration .getInstance() .getResultReferenceTableId()); //bugzilla 2571 go through ReferenceTablesDAO to get reference tables info note .setReferenceTables(referenceTables); notesByResult = noteDAO .getAllNotesByRefIdRefTable(note); if (notesByResult != null && notesByResult.size() > 0) { sampleResultHasNotesList.add(true); } else { sampleResultHasNotesList.add(false); } } else {//no result sampleResultHasNotesList.add(false); } //END 1942 } sample_Ta.setSampleTestResultIds(results); sample_Ta.setResultLastupdatedList(resultLastupdatedList); sample_Ta.setTestResultValues(resultValues); sample_Ta.setResultIds(resultIds); sample_Ta.setResultHasNotesList(sampleResultHasNotesList); //bugzilla 2227 sample_Ta.setSampleHasTestRevisions(sampleHasTestRevisions); sample_Tav.setTestResultValues(resultValuesn); sample_Tavt.setTestResultValues(resultValuest); sample_Tas.add(sample_Ta); sample_Tasv.add(sample_Tav); sample_Tasvt.add(sample_Tavt); } } // bugzilla #1346 add ability to hover over // accession number and // view patient/person information (first and last // name and external id) } } }//end if analysisStatus check }//end for loop // Load list of TestAnalyte_TestResults for display TestResultDAO testResultDAO = new TestResultDAOImpl(); DictionaryDAO dictDAO = new DictionaryDAOImpl(); TestAnalyte ta = null; TestAnalyte_TestResults ta_Trs = null; List listOfTestResults = null; for (int i = 0; i < testAnalytes.size(); i++) { ta = (TestAnalyte) testAnalytes.get(i); ta_Trs = new TestAnalyte_TestResults(); ta_Trs.setTestAnalyte(ta); listOfTestResults = new ArrayList(); listOfTestResults = testResultDAO .getTestResultsByTestAndResultGroup(ta); // fill in dictionary values for (int j = 0; j < listOfTestResults.size(); j++) { TestResult tr = (TestResult) listOfTestResults.get(j); if (tr.getTestResultType().equals( SystemConfiguration.getInstance() .getDictionaryType())) { // get from dictionary Dictionary dictionary = new Dictionary(); dictionary.setId(tr.getValue()); dictDAO.getData(dictionary); //bugzilla 1847: use dictEntryDisplayValue tr.setValue(dictionary.getDictEntryDisplayValue()); } } //bugzilla 1845 Collections.sort(listOfTestResults, ResultsEntryTestResultComparator.SORTORDER_VALUE_COMPARATOR); ta_Trs.setTestResults(listOfTestResults); testAnalyte_TestResults.add(ta_Trs); } } catch (LIMSRuntimeException lre) { // if error then forward to fail and don't update to blank // page // = false //bugzilla 2154 LogEvent.logError("BatchResultsEntryViewAction","performAction()",lre.toString()); errors = new ActionMessages(); ActionError error = null; error = new ActionError("errors.GetException", null, null); errors.add(ActionMessages.GLOBAL_MESSAGE, error); saveErrors(request, errors); request.setAttribute(Globals.ERROR_KEY, errors); request.setAttribute(ALLOW_EDITS_KEY, "false"); return mapping.findForward(FWD_FAIL); } } // #1347 sort dropdown values Collections.sort(testSections, TestSectionComparator.NAME_COMPARATOR); //bugzilla 1844 Collections.sort(tests, TestComparator.DESCRIPTION_COMPARATOR); PropertyUtils.setProperty(form, "sample_TestAnalytes", sample_Tas); PropertyUtils.setProperty(form, "resultValueN", sample_Tasv); PropertyUtils.setProperty(form, "resultValueT", sample_Tasvt); PropertyUtils.setProperty(form, "testAnalyte_TestResults", testAnalyte_TestResults); PropertyUtils.setProperty(form, "selectedTestId", selectedTestId); //bugzilla 2379 PropertyUtils.setProperty(form, "selectedTestSectionId", selectedTestSectionId); PropertyUtils.setProperty(form, "receivedDateForDisplay", receivedDateForDisplay); PropertyUtils.setProperty(form, "tests", tests); PropertyUtils.setProperty(form, "testSections", testSections); PropertyUtils.setProperty(form, "currentDate", currentDate); return mapping.findForward(forward); } protected String getPageTitleKey() { if (isNew) { return "batchresultsentry.add.title"; } else { return "batchresultsentry.edit.title"; } } protected String getPageSubtitleKey() { if (isNew) { return "batchresultsentry.add.subtitle"; } else { return "batchresultsentry.edit.subtitle"; } } }
mpl-2.0
servinglynk/hmis-lynk-open-source
sync-years/src/main/java/com/servinglynk/hmis/warehouse/SyncPostgresProcessor.java
12845
package com.servinglynk.hmis.warehouse; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Calendar; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.UUID; import org.apache.commons.lang3.StringUtils; import org.apache.log4j.Logger; public class SyncPostgresProcessor extends Logging{ public static int batchSize = 1000; private static Connection connection = null; static final Logger logger = Logger.getLogger(SyncPostgresProcessor.class); static Connection getConnection() throws SQLException { if (connection == null) { connection = DriverManager.getConnection( "jdbc:postgresql://" + Properties.POSTGRESQL_DB_HOST + ":" + Properties.POSTGRESQL_DB_PORT + "/" + Properties.POSTGRESQL_DB_DATABASE, Properties.POSTGRESQL_DB_USERNAME, Properties.POSTGRESQL_DB_PASSWORD); } if (connection.isClosed()) { throw new SQLException("connection could not initiated"); } return connection; } public static Map<String,String> getColumnsForTable(String tableName, String schema) { Map<String,String> columns = new HashMap<>(); ResultSet resultSet = null; PreparedStatement statement = null; Connection connection = null; try{ connection = getConnection(); statement = connection.prepareStatement("select column_name,data_type from information_schema.columns where table_schema=? and table_name=?"); statement.setString(1, schema); statement.setString(2, tableName); resultSet = statement.executeQuery(); while (resultSet.next()){ columns.put(resultSet.getString("column_name"),resultSet.getString("data_type")); } }catch (Exception ex){ logger.error(" Error getting metadata for table "+tableName + "schema :"+schema); } return columns; } public static List<String> getAllTablesFromPostgres(String schemaName) throws Exception{ List<String> tables = new ArrayList<>(); ResultSet resultSet = null; PreparedStatement statement = null; Connection connection = null; try{ connection = getConnection(); statement = connection.prepareStatement("SELECT table_name FROM information_schema.tables WHERE table_schema='"+schemaName+"'"); resultSet = statement.executeQuery(); while (resultSet.next()){ String tableName = resultSet.getString("table_name"); if(!StringUtils.equalsIgnoreCase(tableName, "question") && !StringUtils.equalsIgnoreCase(tableName, "hmis_type")) { tables.add(tableName); } } }catch (Exception ex){ throw ex; } return tables; } public static List<String> getAllProjectGroupCodes(Logger logger) { ResultSet resultSet = null; PreparedStatement statement = null; Connection connection = null; List<String> projectGroupCodes = new ArrayList<String>(); try { connection = getConnection(); statement = connection.prepareStatement("SELECT distinct(project_group_code) FROM base.hmis_project_group where active=true"); resultSet = statement.executeQuery(); while (resultSet.next()) { projectGroupCodes.add(resultSet.getString(1)); } return projectGroupCodes; } catch (SQLException e) { // TODO Auto-generated catch block logger.error(e); } finally { if (statement != null) { try { statement.close(); //connection.close(); } catch (SQLException e) { // TODO Auto-generated catch block logger.error(e); } } } return null; } public static List<BulkUpload> getExportIDFromBulkUpload(int schemaYear, Logger logger) { ResultSet resultSet = null; PreparedStatement statement = null; Connection connection = null; List<BulkUpload> uploads = new ArrayList<BulkUpload>(); try { connection = getConnection(); statement = connection.prepareStatement("SELECT export_id,project_group_code,id,year,status FROM base.bulk_upload WHERE year='"+ schemaYear +"'"); resultSet = statement.executeQuery(); int count = 0; while (resultSet.next()) { count++; if (!validateBulkUploadId(resultSet)) { continue; } Status status = Status.getEnum(resultSet.getString(5)); if (status == null) { continue; } BulkUpload upload = new BulkUpload(); upload.setExportId(UUID.fromString(resultSet.getString(1))); upload.setProjectGroupCode(resultSet.getString(2)); upload.setId(resultSet.getLong(3)); upload.setYear(resultSet.getLong(4)); upload.setStatus(status); uploads.add(upload); } System.out.println(count); return uploads; } catch (SQLException e) { // TODO Auto-generated catch block logger.error(e); } finally { if (statement != null) { try { statement.close(); //connection.close(); } catch (SQLException e) { // TODO Auto-generated catch block logger.error(e); } } } return null; } private static boolean validateBulkUploadId(ResultSet resultSet) throws SQLException { boolean valid = true; for (int i = 1; i < 6; i++) { if (resultSet.getString(1) == null) { valid = false; break; } } // TODO: if 'valid' is false set detailed error description return valid; } public static void updateCreateFlag(String groupCode, VERSION version, Logger logger) { PreparedStatement statement = null; Connection connection = null; try { connection = getConnection(); switch (version) { case V2017: statement = connection.prepareStatement("UPDATE base.hmis_project_group SET tables_v2016_in_hbase=TRUE where project_group_code=?"); statement.setString(1, groupCode); break; case V2016: statement = connection.prepareStatement("UPDATE base.hmis_project_group SET tables_v2016_in_hbase=TRUE where project_group_code=?"); statement.setString(1, groupCode); break; case V2015: statement = connection.prepareStatement("UPDATE base.hmis_project_group SET tables_v2015_in_hbase=TRUE where project_group_code=?"); statement.setString(1, groupCode); break; case V2014: statement = connection.prepareStatement("UPDATE base.hmis_project_group SET tables_v2014_in_hbase=TRUE where project_group_code=?"); statement.setString(1, groupCode); break; } if(version != VERSION.V2017) { int status = statement.executeUpdate(); } } catch (SQLException ex) { logger.error(ex); } finally { if (statement != null) { try { statement.close(); //connection.close(); } catch (SQLException e) { // TODO Auto-generated catch block logger.error(e); } } } } public static void updateSyncFlag(String tableName, UUID id, String schema, Logger logger) { PreparedStatement statement = null; Connection connection = null; try { connection = getConnection(); statement = connection.prepareStatement("UPDATE " + schema + "." + tableName + " SET date_updated=?, sync=?,active=? where export_id=?"); Timestamp currentTimestamp = getCUrrentTimestamp(); statement.setTimestamp(1, currentTimestamp); statement.setBoolean(2, true); statement.setBoolean(3, true); statement.setObject(4, id); int status = statement.executeUpdate(); } catch (SQLException e) { // TODO Auto-generated catch block logger.error(e); } finally { if (statement != null) { try { statement.close(); //connection.close(); } catch (SQLException e) { // TODO Auto-generated catch block logger.error(e); } } } } private static Timestamp getCUrrentTimestamp() { Calendar calendar = Calendar.getInstance(); java.sql.Timestamp currentTimestamp = new java.sql.Timestamp(calendar.getTime().getTime()); return currentTimestamp; } public static void updateBulkUploadStatusToLive(Long id, Logger logger) { PreparedStatement statement = null; Connection connection = null; try { connection = getConnection(); statement = connection.prepareStatement("UPDATE base.bulk_upload SET date_updated=?, status=? where id =?"); Timestamp currentTimestamp = getCUrrentTimestamp(); statement.setTimestamp(1, currentTimestamp); statement.setString(2, "LIVE"); statement.setLong(3, id); int status = statement.executeUpdate(); } catch (SQLException e) { // TODO Auto-generated catch block logger.error(e); } finally { if (statement != null) { try { statement.close(); //connection.close(); } catch (SQLException e) { // TODO Auto-generated catch block logger.error(e); } } } } public static void hydrateSyncTable(String schemaName,String tableName,String status,String message,String projectGroupCode){ PreparedStatement statement = null; Connection connection = null; try{ connection = getConnection(); statement = connection.prepareStatement("insert into "+schemaName+".sync (sync_table,status,description,project_group_code,date_created,date_updated) values (?,?,?,?,?,?)"); statement.setString(1, tableName); statement.setString(2,status); statement.setString(3,message); statement.setString(4,projectGroupCode); statement.setTimestamp(5, getCUrrentTimestamp()); statement.setTimestamp(6, getCUrrentTimestamp()); statement.executeUpdate(); }catch (SQLException ex) { logger.error(" Exception inserting sync table: "+ex.getMessage(), ex); } finally { try { if (statement != null) { statement.close(); } } catch (SQLException ex) { logger.error(" Exception inserting sync table: "+ex.getMessage(), ex); } } } public static void markRowsForDeletion(String fullTableName, String exportId, Logger logger) { PreparedStatement statement = null; Connection connection; try { connection = getConnection(); statement = connection.prepareStatement("UPDATE " + fullTableName + " SET deleted=TRUE where export_id =?"); statement.setObject(1, UUID.fromString(exportId)); int status = statement.executeUpdate(); } catch (SQLException e) { // TODO Auto-generated catch block logger.error(e); } finally { if (statement != null) { try { statement.close(); //connection.close(); } catch (SQLException e) { // TODO Auto-generated catch block logger.error(e); } } } } }
mpl-2.0
Orange-OpenSource/ocara
app/src/main/java/com/orange/ocara/business/interactor/CheckRulesetIsUpgradableTask.java
3273
/* * Software Name: OCARA * * SPDX-FileCopyrightText: Copyright (c) 2015-2020 Orange * SPDX-License-Identifier: MPL v2.0 * * This software is distributed under the Mozilla Public License v. 2.0, * the text of which is available at http://mozilla.org/MPL/2.0/ or * see the "license.txt" file for more details. */ package com.orange.ocara.business.interactor; import androidx.annotation.NonNull; import com.orange.ocara.business.model.RulesetModel; import com.orange.ocara.business.model.VersionableModel; import com.orange.ocara.business.repository.RulesetRepository; import lombok.Getter; import lombok.RequiredArgsConstructor; import timber.log.Timber; /** * a {@link UseCase} dedicated to check if a {@link RulesetModel} is upgradable or not. */ public class CheckRulesetIsUpgradableTask implements UseCase<CheckRulesetIsUpgradableTask.CheckRulesetIsUpgradableRequest, CheckRulesetIsUpgradableTask.CheckRulesetIsUpgradableResponse> { private final RulesetRepository repository; public CheckRulesetIsUpgradableTask(RulesetRepository repository) { this.repository = repository; } @Override public void executeUseCase(@NonNull CheckRulesetIsUpgradableRequest request, UseCaseCallback<CheckRulesetIsUpgradableResponse> callback) { CheckRulesetIsUpgradableResponse response; RulesetModel ruleset = repository.findOne(request.getReference(), request.getVersion()); if (ruleset != null && ruleset.isUpgradable()) { response = CheckRulesetIsUpgradableResponse.ok(); } else { response = CheckRulesetIsUpgradableResponse.ko(); } Timber.d("TaskMessage=Checking upgradability succeeded;TaskResponse=%s", response.getCode()); callback.onComplete(response); } /** * the request dedicated to the {@link CheckRulesetIsUpgradableTask} */ @RequiredArgsConstructor public static final class CheckRulesetIsUpgradableRequest implements UseCase.RequestValues { private final VersionableModel ruleset; public String getReference() { return ruleset.getReference(); } public Integer getVersion() { return Integer.valueOf(ruleset.getVersion()); } } /** * when the request is successful, the response contains the list of items to display */ @RequiredArgsConstructor public static final class CheckRulesetIsUpgradableResponse implements UseCase.ResponseValue { @Getter private final String code; public boolean isOk() { return "OK".equals(code); } /** * gives an instance of a positive {@link CheckRulesetIsUpgradableResponse} * * @return a valid {@link CheckRulesetIsUpgradableResponse} */ public static CheckRulesetIsUpgradableResponse ok() { return new CheckRulesetIsUpgradableResponse("OK"); } /** * gives an instance of a negative {@link CheckRulesetIsUpgradableResponse} * * @return a valid {@link CheckRulesetIsUpgradableResponse} */ public static CheckRulesetIsUpgradableResponse ko() { return new CheckRulesetIsUpgradableResponse("KO"); } } }
mpl-2.0
PharmGKB/pgkb-clinvar-submission
src/main/java/org/pharmgkb/io/exporter/clinvar/model/CoOccurrenceType.java
4323
// // This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802 // See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a> // Any modifications to this file will be lost upon recompilation of the source schema. // Generated on: 2017.10.16 at 09:04:14 AM PDT // package org.pharmgkb.io.exporter.clinvar.model; import java.util.ArrayList; import java.util.List; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlSchemaType; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for Co-occurrenceType complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType name="Co-occurrenceType"> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="Zygosity" type="{}ZygosityType" minOccurs="0"/> * &lt;element name="AlleleDescSet" type="{}AlleleDescType" maxOccurs="unbounded" minOccurs="0"/> * &lt;element name="Count" type="{http://www.w3.org/2001/XMLSchema}int" minOccurs="0"/> * &lt;/sequence> * &lt;attribute name="cv_id" type="{http://www.w3.org/2001/XMLSchema}int" default="0" /> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "Co-occurrenceType", propOrder = { "zygosity", "alleleDescSet", "count" }) public class CoOccurrenceType { @XmlElement(name = "Zygosity") @XmlSchemaType(name = "string") protected ZygosityType zygosity; @XmlElement(name = "AlleleDescSet") protected List<AlleleDescType> alleleDescSet; @XmlElement(name = "Count") protected Integer count; @XmlAttribute(name = "cv_id") protected Integer cvId; /** * Gets the value of the zygosity property. * * @return * possible object is * {@link ZygosityType } * */ public ZygosityType getZygosity() { return zygosity; } /** * Sets the value of the zygosity property. * * @param value * allowed object is * {@link ZygosityType } * */ public void setZygosity(ZygosityType value) { this.zygosity = value; } /** * Gets the value of the alleleDescSet property. * * <p> * This accessor method returns a reference to the live list, * not a snapshot. Therefore any modification you make to the * returned list will be present inside the JAXB object. * This is why there is not a <CODE>set</CODE> method for the alleleDescSet property. * * <p> * For example, to add a new item, do as follows: * <pre> * getAlleleDescSet().add(newItem); * </pre> * * * <p> * Objects of the following type(s) are allowed in the list * {@link AlleleDescType } * * */ public List<AlleleDescType> getAlleleDescSet() { if (alleleDescSet == null) { alleleDescSet = new ArrayList<AlleleDescType>(); } return this.alleleDescSet; } /** * Gets the value of the count property. * * @return * possible object is * {@link Integer } * */ public Integer getCount() { return count; } /** * Sets the value of the count property. * * @param value * allowed object is * {@link Integer } * */ public void setCount(Integer value) { this.count = value; } /** * Gets the value of the cvId property. * * @return * possible object is * {@link Integer } * */ public int getCvId() { if (cvId == null) { return 0; } else { return cvId; } } /** * Sets the value of the cvId property. * * @param value * allowed object is * {@link Integer } * */ public void setCvId(Integer value) { this.cvId = value; } }
mpl-2.0
Yukarumya/Yukarum-Redfoxes
mobile/android/geckoview/src/main/java/org/mozilla/gecko/util/ActivityUtils.java
2573
/* -*- Mode: Java; c-basic-offset: 4; tab-width: 4; indent-tabs-mode: nil; -*- * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.mozilla.gecko.util; import android.app.Activity; import android.content.Intent; import android.os.Build; import android.view.View; import android.view.Window; import android.view.WindowManager; public class ActivityUtils { private ActivityUtils() { } public static void setFullScreen(Activity activity, boolean fullscreen) { // Hide/show the system notification bar Window window = activity.getWindow(); if (Build.VERSION.SDK_INT >= 16) { int newVis; if (fullscreen) { newVis = View.SYSTEM_UI_FLAG_FULLSCREEN; if (Build.VERSION.SDK_INT >= 19) { newVis |= View.SYSTEM_UI_FLAG_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_STABLE | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY; } else { newVis |= View.SYSTEM_UI_FLAG_LOW_PROFILE; } } else { newVis = View.SYSTEM_UI_FLAG_VISIBLE; } window.getDecorView().setSystemUiVisibility(newVis); } else { window.setFlags(fullscreen ? WindowManager.LayoutParams.FLAG_FULLSCREEN : 0, WindowManager.LayoutParams.FLAG_FULLSCREEN); } } public static boolean isFullScreen(final Activity activity) { final Window window = activity.getWindow(); if (Build.VERSION.SDK_INT >= 16) { final int vis = window.getDecorView().getSystemUiVisibility(); return (vis & View.SYSTEM_UI_FLAG_FULLSCREEN) != 0; } final int flags = window.getAttributes().flags; return ((flags & WindowManager.LayoutParams.FLAG_FULLSCREEN) != 0); } /** * Finish this activity and launch the default home screen activity. */ public static void goToHomeScreen(Activity activity) { Intent intent = new Intent(Intent.ACTION_MAIN); intent.addCategory(Intent.CATEGORY_HOME); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); activity.startActivity(intent); } }
mpl-2.0
nomadeous/spring-batch-samples
src/main/java/prototypes/batches/listening/listener/CustomItemWriterListener.java
847
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package prototypes.batches.listening.listener; import java.util.List; import org.springframework.batch.core.ItemWriteListener; public class CustomItemWriterListener implements ItemWriteListener<Object> { @Override public void beforeWrite(List<? extends Object> items) { System.out.println("ItemWriteListener - beforeWrite"); } @Override public void afterWrite(List<? extends Object> items) { System.out.println("ItemWriteListener - afterWrite"); } @Override public void onWriteError(Exception exception, List<? extends Object> items) { System.out.println("ItemWriteListener - onWriteError"); } }
mpl-2.0
seedstack/samples
basics/business/src/test/java/org/seedstack/samples/business/domain/seller/SellerTest.java
1834
/* * Copyright © 2013-2018, The SeedStack authors <http://seedstack.org> * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ package org.seedstack.samples.business.domain.seller; import static org.assertj.core.api.Assertions.assertThat; import java.time.LocalDate; import java.time.temporal.ChronoUnit; import org.junit.Test; import org.seedstack.samples.business.domain.BonusPolicy; public class SellerTest { private static final Long SELLER_ID = 1L; private Seller underTest; @Test public void testInitialState() { underTest = new Seller(SELLER_ID, LocalDate.now().minus(30, ChronoUnit.DAYS)); assertThat(underTest.getBonusPolicy()).isEqualTo(BonusPolicy.PER_ITEM); assertThat(underTest.getMonthlyBonus()).isEqualTo(0); } @Test(expected = IllegalStateException.class) public void testPercentagePolicyIsForbiddenForJuniors() { underTest = new Seller(SELLER_ID, LocalDate.now().minus(30, ChronoUnit.DAYS)); underTest.enablePercentageBonusPolicy(); } @Test public void testPercentagePolicyIsAllowedForSeniors() { underTest = new Seller(SELLER_ID, LocalDate.now().minus(Seller.SENIORITY_THRESHOLD, ChronoUnit.DAYS)); underTest.enablePercentageBonusPolicy(); } @Test public void testBonusCompute() { underTest = new Seller(SELLER_ID, LocalDate.now().minus(Seller.SENIORITY_THRESHOLD, ChronoUnit.DAYS)); underTest.addToMonthlyBonus(450); underTest.addToMonthlyBonus(50); assertThat(underTest.getMonthlyBonus()).isEqualTo(500); underTest.resetMonthlyBonus(); assertThat(underTest.getMonthlyBonus()).isZero(); } }
mpl-2.0
William-Hai/SimpleDemo
src/org/demo/json/JsonDemo.java
1404
package org.demo.json; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import net.sf.json.JSONArray; import net.sf.json.JSONObject; /** * <p> * Json测试 * </p> * 2015年12月29日 * * @author <a href="http://weibo.com/u/5131020927">Q-WHai</a> * @see <a href="http://blog.csdn.net/lemon_tree12138">http://blog.csdn.net/lemon_tree12138</a> * @version 0.1 */ public class JsonDemo { public static void main(String[] args) { List<String> list = new ArrayList<>(); list.add("abd"); list.add("1215"); JSONArray array = JSONArray.fromObject(list); System.out.println(array); Map<String, Object> map = new HashMap<>(); map.put("name", "json"); map.put("bool", Boolean.TRUE); map.put("int", new Integer(1)); map.put("arr", new String[] { "a", "b" }); map.put("func", "function(i){ return this.arr[i]; }"); JSONObject json = JSONObject.fromObject(map); System.out.println(json); boolean[] boolArray = new boolean[] { true, false, true }; JSONArray jsonArray1 = JSONArray.fromObject(boolArray); System.out.println(jsonArray1); JSONArray jsonArray3 = JSONArray.fromObject("['json','is','easy']" ); System.out.println(jsonArray3); } }
agpl-3.0
stephaneperry/Silverpeas-Core
ejb-core/contact/src/main/java/com/stratelia/webactiv/util/contact/ejb/ContactEJB.java
12878
/** * Copyright (C) 2000 - 2011 Silverpeas * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * As a special exception to the terms and conditions of version 3.0 of * the GPL, you may redistribute this Program in connection with Free/Libre * Open Source Software ("FLOSS") applications as described in Silverpeas's * FLOSS exception. You should have received a copy of the text describing * the FLOSS exception, and it is also available here: * "http://repository.silverpeas.com/legal/licensing" * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.stratelia.webactiv.util.contact.ejb; import java.sql.Connection; import java.sql.SQLException; import java.util.Collection; import java.util.Date; import javax.ejb.EntityBean; import javax.ejb.EntityContext; import javax.ejb.FinderException; import com.stratelia.webactiv.util.DBUtil; import com.stratelia.webactiv.util.JNDINames; import com.stratelia.webactiv.util.contact.info.InfoDAO; import com.stratelia.webactiv.util.contact.model.CompleteContact; import com.stratelia.webactiv.util.contact.model.ContactDetail; import com.stratelia.webactiv.util.contact.model.ContactPK; import com.stratelia.webactiv.util.contact.model.ContactRuntimeException; import com.stratelia.webactiv.util.exception.SilverpeasRuntimeException; import com.stratelia.webactiv.util.node.model.NodePK; public class ContactEJB implements EntityBean { private static final long serialVersionUID = -5005219904431811704L; private EntityContext context; private ContactPK pk; private String firstName; private String lastName; private String email; private String phone; private String fax; private String userId; private Date creationDate; private String creatorId; private boolean isModified = false; public ContactEJB() { } private Connection getConnection() { try { return DBUtil.makeConnection(JNDINames.CONTACT_DATASOURCE); } catch (Exception re) { throw new ContactRuntimeException("ContactEJB.getConnection()", SilverpeasRuntimeException.ERROR, "root.EX_CONNECTION_OPEN_FAILED", re); } } private void closeConnection(Connection con) { try { if (con != null) con.close(); } catch (SQLException re) { throw new ContactRuntimeException("ContactEJB.closeConnection()", SilverpeasRuntimeException.ERROR, "root.EX_CONNECTION_CLOSE_FAILED", re); } } /** * Get the attributes of THIS contact * @return a ContactDetail * @see com.stratelia.webactiv.util.contact.model.ContactDetail * @exception java.sql.SQLException * @since 1.0 */ public ContactDetail getDetail() { return new ContactDetail(pk, firstName, lastName, email, phone, fax, userId, creationDate, creatorId); } /** * Update the attributes of the contact * @param pubDetail the ContactDetail which contains updated data * @see com.stratelia.webactiv.util.contact.model.ContactDetail * @since 1.0 */ public void setDetail(ContactDetail pubDetail) { if (pubDetail.getPK().equals(pk)) { if (pubDetail.getFirstName() != null) firstName = pubDetail.getFirstName(); if (pubDetail.getLastName() != null) lastName = pubDetail.getLastName(); if (pubDetail.getEmail() != null) email = pubDetail.getEmail(); if (pubDetail.getPhone() != null) phone = pubDetail.getPhone(); if (pubDetail.getFax() != null) fax = pubDetail.getFax(); userId = pubDetail.getUserId(); if (pubDetail.getCreationDate() != null) creationDate = pubDetail.getCreationDate(); if (pubDetail.getCreatorId() != null) creatorId = pubDetail.getCreatorId(); isModified = true; } else { throw new ContactRuntimeException("ContactEJB.setDetail()", SilverpeasRuntimeException.ERROR, "contact.EX_SET_CONTACT_DETAIL_FAILED"); } } /** * Add a new father to this contact * @param fatherPK the father NodePK * @see com.stratelia.webactiv.util.node.model.NodePK * @exception java.sql.SQLException * @since 1.0 */ public void addFather(NodePK fatherPK) { Connection con = getConnection(); try { ContactDAO.addFather(con, pk, fatherPK); } catch (Exception re) { throw new ContactRuntimeException("ContactEJB.addFather()", SilverpeasRuntimeException.ERROR, "contact.EX_CONTACT_ADD_TO_FATHER_FAILED", re); } finally { closeConnection(con); } } /** * Remove a father to this contact * @param fatherPK the father NodePK to remove * @see com.stratelia.webactiv.util.node.model.NodePK * @exception java.sql.SQLException * @since 1.0 */ public void removeFather(NodePK fatherPK) { Connection con = getConnection(); try { ContactDAO.removeFather(con, pk, fatherPK); } catch (Exception re) { throw new ContactRuntimeException("ContactEJB.removeFather()", SilverpeasRuntimeException.ERROR, "contact.EX_CONTACT_REMOVE_FROM_FATHER_FAILED", re); } finally { closeConnection(con); } } /** * Remove all fathers to this contact - this contact will be linked to no Node * @exception java.sql.SQLException * @since 1.0 */ public void removeAllFather() { Connection con = getConnection(); try { ContactDAO.removeAllFather(con, pk); } catch (Exception re) { throw new ContactRuntimeException("ContactEJB.removeAllFather()", SilverpeasRuntimeException.ERROR, "contact.EX_CONTACT_REMOVE_FROM_ALLFATHERS_FAILED", re); } finally { closeConnection(con); } } /** * Get all fathers of this contact * @return A collection of NodePK * @see com.stratelia.webactiv.util.node.model.NodePK * @see java.util.Collection * @exception java.sql.SQLException * @since 1.0 */ public Collection getAllFatherPK() { Connection con = getConnection(); try { return ContactDAO.getAllFatherPK(con, pk); } catch (Exception re) { throw new ContactRuntimeException("ContactEJB.getAllFatherPK()", SilverpeasRuntimeException.ERROR, "contact.EX_GET_CONTACT_FATHERS_FAILED", re); } finally { closeConnection(con); } } /** * Create or update info to this contact * @param modelId The modelId corresponding to the choosen model * @exception java.sql.SQLException * @since 1.0 */ public void createInfo(String modelId) { Connection con = getConnection(); try { InfoDAO.createInfo(con, modelId, this.pk); } catch (Exception re) { throw new ContactRuntimeException("ContactEJB.createInfoDetail()", SilverpeasRuntimeException.ERROR, "contact.EX_CONTACT_INFOMODEL_CREATE_FAILED", re); } finally { closeConnection(con); } } /** * Get all info on contact * @return A completeContact * @see com.stratelia.webactiv.util.contact.model.CompleteContact * @exception java.sql.SQLException * @since 1.0 */ public CompleteContact getCompleteContact(String modelId) { Connection con = getConnection(); try { // get detail ContactDetail pubDetail = ContactDAO.loadRow(con, this.pk); return new CompleteContact(pubDetail, modelId); } catch (Exception re) { throw new ContactRuntimeException("ContactEJB.getCompleteContact()", SilverpeasRuntimeException.ERROR, "contact.EX_GET_CONTACT_DETAIL_FAILED", re); } finally { closeConnection(con); } } /** * Create a new Contact object * @param pubDetail the ContactDetail which contains data * @return the ContactPK of the new Contact * @see com.stratelia.webactiv.util.contact.model.ContactDetail * @exception javax.ejb.CreateException * @exception java.sql.SQLException * @since 1.0 */ public ContactPK ejbCreate(ContactDetail pubDetail) { Connection con = getConnection(); try { int id = 0; id = DBUtil.getNextId(pubDetail.getPK().getTableName(), "contactId"); pubDetail.getPK().setId(String.valueOf(id)); ContactDAO.insertRow(con, pubDetail); } catch (Exception re) { throw new ContactRuntimeException("ContactEJB.ejbCreate()", SilverpeasRuntimeException.ERROR, "contact.EX_CONTACT_CREATE_FAILED", re); } finally { closeConnection(con); } pk = pubDetail.getPK(); firstName = pubDetail.getFirstName(); lastName = pubDetail.getLastName(); email = pubDetail.getEmail(); phone = pubDetail.getPhone(); fax = pubDetail.getFax(); userId = pubDetail.getUserId(); creationDate = pubDetail.getCreationDate(); creatorId = pubDetail.getCreatorId(); return pk; } public void ejbPostCreate(ContactDetail pubDetail) { } /** * Create an instance of a Contact object * @param pk the PK of the Contact to instanciate * @return the ContactPK of the instanciated Contact if it exists in database * @see com.stratelia.webactiv.util.contact.model.ContactDetail * @exception javax.ejb.FinderException * @exception java.sql.SQLException * @since 1.0 */ public ContactPK ejbFindByPrimaryKey(ContactPK pk) throws FinderException { Connection con = getConnection(); try { ContactPK primary = ContactDAO.selectByPrimaryKey(con, pk); if (primary != null) { return primary; } else { throw new ContactRuntimeException("ContactEJB.ejbFindByPrimaryKey()", SilverpeasRuntimeException.ERROR, "contact.EX_CONTACT_NOT_FOUND"); } } catch (Exception re) { throw new ContactRuntimeException("ContactEJB.ejbFindByPrimaryKey()", SilverpeasRuntimeException.ERROR, "contact.EX_CONTACT_NOT_FOUND", re); } finally { closeConnection(con); } } /** * Load contact attributes from database * @since 1.0 */ public void ejbLoad() { if (pk == null) return; ContactDetail pubDetail = null; Connection con = null; try { if (pk.pubDetail != null) { pubDetail = pk.pubDetail; } else { con = getConnection(); pubDetail = ContactDAO.loadRow(con, pk); } firstName = pubDetail.getFirstName(); lastName = pubDetail.getLastName(); email = pubDetail.getEmail(); phone = pubDetail.getPhone(); fax = pubDetail.getFax(); userId = pubDetail.getUserId(); creationDate = pubDetail.getCreationDate(); creatorId = pubDetail.getCreatorId(); isModified = false; } catch (Exception re) { throw new ContactRuntimeException("ContactEJB.ejbLoad()", SilverpeasRuntimeException.ERROR, "contact.EX_CONTACT_NOT_FOUND", re); } finally { closeConnection(con); } } /** * Store contact attributes into database * @since 1.0 */ public void ejbStore() { if (!isModified) return; if (pk == null) return; ContactDetail detail = new ContactDetail(pk, firstName, lastName, email, phone, fax, userId, creationDate, creatorId); Connection con = getConnection(); try { ContactDAO.storeRow(con, detail); isModified = false; } catch (Exception re) { throw new ContactRuntimeException("ContactEJB.ejbStore()", SilverpeasRuntimeException.ERROR, "contact.EX_CONTACT_RECORD_FAILED", re); } finally { closeConnection(con); } } /** * Delete this Contact and all info associated * @since 1.0 */ public void ejbRemove() { Connection con = getConnection(); try { // delete all info associated from database InfoDAO.deleteInfoDetailByContactPK(con, this.pk); // delete contact from database ContactDAO.deleteRow(con, pk); } catch (Exception re) { throw new ContactRuntimeException("ContactEJB.ejbRemove()", SilverpeasRuntimeException.ERROR, "contact.EX_CONTACT_DELETE_FAILED", re); } finally { closeConnection(con); } } public void ejbActivate() { pk = (ContactPK) context.getPrimaryKey(); } public void ejbPassivate() { pk = null; } public void setEntityContext(EntityContext ec) { context = ec; } public void unsetEntityContext() { context = null; } }
agpl-3.0
simonzhangsm/voltdb
src/frontend/org/voltdb/importer/formatter/builtin/VoltCSVFormatter.java
3849
/* This file is part of VoltDB. * Copyright (C) 2008-2018 VoltDB Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with VoltDB. If not, see <http://www.gnu.org/licenses/>. */ package org.voltdb.importer.formatter.builtin; import java.io.IOException; import java.util.Properties; import org.voltdb.common.Constants; import org.voltdb.importer.formatter.FormatException; import org.voltdb.importer.formatter.Formatter; import au.com.bytecode.opencsv_voltpatches.CSVParser; import java.nio.ByteBuffer; import java.nio.charset.StandardCharsets; public class VoltCSVFormatter implements Formatter { final CSVParser m_parser; public VoltCSVFormatter (String formatName, Properties prop) { if (!("csv".equalsIgnoreCase(formatName) || "tsv".equalsIgnoreCase(formatName))) { throw new IllegalArgumentException("Invalid format " + formatName + ", choices are either \"csv\" or \"tsv\"."); } char separator = "csv".equalsIgnoreCase(formatName) ? ',' : '\t'; String separatorProp = prop.getProperty("separator", ""); if (!separatorProp.isEmpty() && separatorProp.length() == 1) { separator = separatorProp.charAt(0); } char quotechar = CSVParser.DEFAULT_QUOTE_CHARACTER; String quoteCharProp = prop.getProperty("quotechar", ""); if (!quoteCharProp.isEmpty() && quoteCharProp.length() == 1) { quotechar = quoteCharProp.charAt(0); } char escape = CSVParser.DEFAULT_ESCAPE_CHARACTER; String escapeProp = prop.getProperty("escape", ""); if (!escapeProp.isEmpty() && escapeProp.length() == 1) { escape = escapeProp.charAt(0); } boolean strictQuotes = CSVParser.DEFAULT_STRICT_QUOTES; String strictQuotesProp = prop.getProperty("strictquotes", ""); if (!strictQuotesProp.isEmpty()) { strictQuotes = Boolean.parseBoolean(strictQuotesProp); } boolean ignoreLeadingWhiteSpace = CSVParser.DEFAULT_IGNORE_LEADING_WHITESPACE; String ignoreLeadingWhiteSpaceProp = prop.getProperty("ignoreleadingwhitespace", ""); if (!ignoreLeadingWhiteSpaceProp.isEmpty()) { ignoreLeadingWhiteSpace = Boolean.parseBoolean(ignoreLeadingWhiteSpaceProp); } m_parser = new CSVParser(separator, quotechar, escape, strictQuotes, ignoreLeadingWhiteSpace); } @Override public Object[] transform(ByteBuffer payload) throws FormatException { String line = null; try { if (payload == null) { return null; } line = new String(payload.array(), payload.arrayOffset(), payload.limit(), StandardCharsets.UTF_8); Object list[] = m_parser.parseLine(line); if (list != null) { for (int i = 0; i < list.length; i++) { if ("NULL".equals(list[i]) || Constants.CSV_NULL.equals(list[i]) || Constants.QUOTED_CSV_NULL.equals(list[i])) { list[i] = null; } } } return list; } catch (IOException e) { throw new FormatException("failed to format " + line, e); } } }
agpl-3.0
subshare/subshare
org.subshare/org.subshare.core/src/main/java/org/subshare/core/dto/jaxb/PlainHistoCryptoRepoFileDtoIo.java
242
package org.subshare.core.dto.jaxb; import org.subshare.core.dto.PlainHistoCryptoRepoFileDto; import co.codewizards.cloudstore.core.dto.jaxb.DtoIo; public class PlainHistoCryptoRepoFileDtoIo extends DtoIo<PlainHistoCryptoRepoFileDto> { }
agpl-3.0
pangshaoxing/UserDemo
src/test/java/com/user/dao/mapper/test/UserMapperTest.java
1604
package com.user.dao.mapper.test; import com.register.model.Sex; import com.register.model.User; import com.user.dao.mapper.UserMapper; import javax.transaction.Transactional; import junit.framework.TestCase; import org.junit.AfterClass; import org.junit.Before; import org.junit.BeforeClass; import org.junit.Test; import org.junit.runner.RunWith; import static org.mockito.Mockito.mock; import org.mockito.junit.MockitoJUnitRunner; /** * Test mapper for UserMapper * * @Shaoxing Pang */ //add test @RunWith(MockitoJUnitRunner.class) public class UserMapperTest extends TestCase { private static UserMapper userMapper; public UserMapperTest() { } //add test changfe @BeforeClass public static void setUpClass() { } @AfterClass public static void tearDownClass() { } @Before public void setUp() { userMapper = mock(UserMapper.class); } @Test public void testAddUserMapper(){ User user = new User(); user.setUserName("user-test"); user.setPassWord("123456"); user.setSex(Sex.MALE); int result = userMapper.addUser(user); assertEquals(0,result); } //@Test public void testJudgeUserMapper(){ String username="123456"; User user = userMapper.userJudge(username); assertNotNull(user); } //@Test public void testLoginUserMapper(){ String username = "123456"; String password = "123456"; User user = userMapper.userLogin(username,password); assertNotNull(user); } }
agpl-3.0
NicolasEYSSERIC/Silverpeas-Core
lib-core/src/main/java/com/stratelia/silverpeas/selection/SelectionJdbcParams.java
2671
/** * Copyright (C) 2000 - 2012 Silverpeas * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * As a special exception to the terms and conditions of version 3.0 of * the GPL, you may redistribute this Program in connection with Free/Libre * Open Source Software ("FLOSS") applications as described in Silverpeas's * FLOSS exception. You should have received a copy of the text describing * the FLOSS exception, and it is also available here: * "http://www.silverpeas.org/docs/core/legal/floss_exception.html" * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.stratelia.silverpeas.selection; public class SelectionJdbcParams implements SelectionExtraParams { private String driverClassName = ""; private String url = ""; private String login = ""; private String password = ""; private String tableName = ""; private String columnsNames = ""; private String formIndex = ""; private String fieldsNames = ""; public SelectionJdbcParams(String driverClassName, String url, String login, String password, String tableName, String columnsNames, String formIndex, String fieldsNames) { this.driverClassName = driverClassName; this.url = url; this.login = login; this.password = password; this.tableName = tableName; this.columnsNames = columnsNames; this.formIndex = formIndex; this.fieldsNames = fieldsNames; } public String getDriverClassName() { return driverClassName; } public String getUrl() { return url; } public String getLogin() { return login; } public String getPassword() { return password; } public String getTableName() { return tableName; } public String getColumnsNames() { return columnsNames; } public String getParameter(String name) { if (name.equals("tableName")) { return tableName; } else if (name.equals("columnsNames")) { return columnsNames; } else if (name.equals("formIndex")) { return formIndex; } else if (name.equals("fieldsNames")) { return fieldsNames; } return null; } }
agpl-3.0
TMS-v113/server
src/tools/data/output/ByteBufferOutputstream.java
1757
/* This file is part of the OdinMS Maple Story Server Copyright (C) 2008 ~ 2010 Patrick Huy <patrick.huy@frz.cc> Matthias Butz <matze@odinms.de> Jan Christian Meyer <vimes@odinms.de> 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. You may not use, modify or distribute this program under any other version of the GNU Affero General Public License. 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 tools.data.output; import org.apache.mina.common.ByteBuffer; /** * Uses a bytebuffer as an underlying storage method to hold a stream of bytes. * * @author Frz * @version 1.0 * @since Revision 323 */ public class ByteBufferOutputstream implements ByteOutputStream { private ByteBuffer bb; /** * Class constructor - Wraps this instance around ByteBuffer <code>bb</code> * * @param bb The <code>org.apache.mina.common.ByteBuffer</code> to wrap this * stream around. */ public ByteBufferOutputstream(final ByteBuffer bb) { super(); this.bb = bb; } /** * Writes a byte to the underlying buffer. * * @param b The byte to write. * @see org.apache.mina.common.ByteBuffer#put(byte) */ @Override public void writeByte(final byte b) { bb.put(b); } }
agpl-3.0
rafaelsisweb/restheart
src/test/java/org/restheart/test/integration/GetCollectionIT.java
18857
/* * RESTHeart - the Web API for MongoDB * Copyright (C) 2014 - 2015 SoftInstigate Srl * * 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.restheart.test.integration; import com.eclipsesource.json.JsonArray; import com.eclipsesource.json.JsonObject; import org.restheart.hal.Representation; import org.restheart.utils.HttpStatus; import java.net.URI; import java.net.URISyntaxException; import static org.junit.Assert.*; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.StatusLine; import org.apache.http.client.fluent.Request; import org.apache.http.client.fluent.Response; import org.apache.http.util.EntityUtils; import org.junit.Test; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * @author Andrea Di Cesare <andrea@softinstigate.com> */ public class GetCollectionIT extends AbstactIT { private static final Logger LOG = LoggerFactory.getLogger(GetCollectionIT.class); public GetCollectionIT() { } @Test public void testGetCollection() throws Exception { testGetCollection(collection1Uri); } @Test public void testGetCollectionRemappedAll() throws Exception { testGetCollection(collection1UriRemappedAll); } @Test public void testGetCollectionRemappedDb() throws Exception { testGetCollection(collection1UriRemappedDb); } @Test public void testGetCollectionRemappedCollection() throws Exception { testGetCollection(collection1UriRemappedCollection); } @Test public void testGetCollectionCountAndPaging() throws Exception { Response resp = adminExecutor.execute(Request.Get(docsCollectionUriCountAndPaging)); HttpResponse httpResp = resp.returnResponse(); assertNotNull(httpResp); HttpEntity entity = httpResp.getEntity(); assertNotNull(entity); StatusLine statusLine = httpResp.getStatusLine(); assertNotNull(statusLine); assertEquals("check status code", HttpStatus.SC_OK, statusLine.getStatusCode()); assertNotNull("content type not null", entity.getContentType()); assertEquals("check content type", Representation.HAL_JSON_MEDIA_TYPE, entity.getContentType().getValue()); String content = EntityUtils.toString(entity); assertNotNull("", content); JsonObject json = null; try { json = JsonObject.readFrom(content); } catch (Throwable t) { fail("@@@ Failed parsing received json"); } assertNotNull("check not null _link", json.get("_links")); assertTrue("check _link to be a json object", (json.get("_links") instanceof JsonObject)); assertEquals("check _returned value to be 2", 2, json.get("_returned").asInt()); assertEquals("check _size value to be 10", 10, json.get("_size").asInt()); assertEquals("check _total_pages value to be 5", 5, json.get("_total_pages").asInt()); JsonObject links = (JsonObject) json.get("_links"); assertNotNull("check not null self", links.get("self")); assertNotNull("check not null rh:db", links.get("rh:db")); assertNotNull("check not null rh:paging", links.get("rh:paging")); assertNotNull("check not null next", links.get("next")); assertNotNull("check not null first", links.get("first")); assertNotNull("check not null last", links.get("last")); assertNotNull("check not null previous", links.get("previous")); Response respSelf = adminExecutor.execute(Request.Get(docsCollectionUriCountAndPaging.resolve(links.get("self").asObject().get("href").asString()))); HttpResponse httpRespSelf = respSelf.returnResponse(); assertNotNull("check not null get self response", httpRespSelf); assertEquals("check get self response status code", HttpStatus.SC_OK, httpRespSelf.getStatusLine().getStatusCode()); Response respRhdb = adminExecutor.execute(Request.Get(docsCollectionUriCountAndPaging.resolve(links.get("rh:db").asObject().get("href").asString()))); HttpResponse httpRespRhdb = respRhdb.returnResponse(); assertNotNull("check not null rh:doc self response", httpRespRhdb); assertEquals("check get rh:doc response status code", HttpStatus.SC_OK, httpRespRhdb.getStatusLine().getStatusCode()); Response respNext = adminExecutor.execute(Request.Get(docsCollectionUriCountAndPaging.resolve(links.get("next").asObject().get("href").asString()))); HttpResponse httpRespNext = respNext.returnResponse(); assertNotNull("check not null get self response", httpRespNext); assertEquals("check get self response status code", HttpStatus.SC_OK, httpRespSelf.getStatusLine().getStatusCode()); Response respPrevious = adminExecutor.execute(Request.Get(docsCollectionUriCountAndPaging.resolve(links.get("previous").asObject().get("href").asString()))); HttpResponse httpRespPrevious = respPrevious.returnResponse(); assertNotNull("check not null get previous response", httpRespPrevious); assertEquals("check get self previous status code", HttpStatus.SC_OK, httpRespSelf.getStatusLine().getStatusCode()); Response respFirst = adminExecutor.execute(Request.Get(dbUriPaging.resolve(links.get("first").asObject().get("href").asString()))); HttpResponse respRespFirst = respFirst.returnResponse(); assertNotNull("check not null get first response", respRespFirst); assertEquals("check get self first status code", HttpStatus.SC_OK, respRespFirst.getStatusLine().getStatusCode()); Response respLast = adminExecutor.execute(Request.Get(dbUriPaging.resolve(links.get("last").asObject().get("href").asString()))); HttpResponse httpRespLast = respLast.returnResponse(); assertNotNull("check not null get last response", httpRespLast); assertEquals("check get last response status code", HttpStatus.SC_OK, httpRespLast.getStatusLine().getStatusCode()); } @Test public void testGetCollectionPaging() throws Exception { Response resp = adminExecutor.execute(Request.Get(docsCollectionUriPaging)); HttpResponse httpResp = resp.returnResponse(); assertNotNull(httpResp); HttpEntity entity = httpResp.getEntity(); assertNotNull(entity); StatusLine statusLine = httpResp.getStatusLine(); assertNotNull(statusLine); assertEquals("check status code", HttpStatus.SC_OK, statusLine.getStatusCode()); assertNotNull("content type not null", entity.getContentType()); assertEquals("check content type", Representation.HAL_JSON_MEDIA_TYPE, entity.getContentType().getValue()); String content = EntityUtils.toString(entity); assertNotNull("", content); JsonObject json = null; try { json = JsonObject.readFrom(content); } catch (Throwable t) { fail("@@@ Failed parsing received json"); } assertNotNull("check json not null", json); assertNotNull("check not null _link", json.get("_links")); assertTrue("check _link to be a json object", (json.get("_links") instanceof JsonObject)); assertNotNull("check not null _returned property", json.get("_returned")); assertNull("check null _size", json.get("_size")); assertNull("check null _total_pages", json.get("_total_pages")); assertEquals("check _returned value to be 2", 2, json.get("_returned").asInt()); JsonObject links = (JsonObject) json.get("_links"); assertNotNull("check not null self", links.get("self")); assertNotNull("check not null rh:db", links.get("rh:db")); assertNotNull("check not null rh:paging", links.get("rh:paging")); assertNotNull("check not null rh:filter", links.get("rh:filter")); assertNotNull("check not null rh:sort", links.get("rh:filter")); assertNotNull("check not null next", links.get("next")); assertNotNull("check not null first", links.get("first")); assertNull("check null last", links.get("last")); assertNull("check null previous", links.get("previous")); Response respSelf = adminExecutor.execute(Request.Get(docsCollectionUriPaging.resolve(links.get("self").asObject().get("href").asString()))); HttpResponse httpRespSelf = respSelf.returnResponse(); assertNotNull(httpRespSelf); Response respDb = adminExecutor.execute(Request.Get(docsCollectionUriPaging.resolve(links.get("rh:db").asObject().get("href").asString()))); HttpResponse httpRespDb = respDb.returnResponse(); assertNotNull(httpRespDb); Response respNext = adminExecutor.execute(Request.Get(docsCollectionUriPaging.resolve(links.get("next").asObject().get("href").asString()))); HttpResponse httpRespNext = respNext.returnResponse(); assertNotNull(httpRespNext); } private void testGetCollection(URI uri) throws Exception { Response resp = adminExecutor.execute(Request.Get(uri)); HttpResponse httpResp = resp.returnResponse(); assertNotNull(httpResp); HttpEntity entity = httpResp.getEntity(); assertNotNull(entity); StatusLine statusLine = httpResp.getStatusLine(); assertNotNull(statusLine); assertEquals("check status code", HttpStatus.SC_OK, statusLine.getStatusCode()); assertNotNull("content type not null", entity.getContentType()); assertEquals("check content type", Representation.HAL_JSON_MEDIA_TYPE, entity.getContentType().getValue()); String content = EntityUtils.toString(entity); assertNotNull(content); JsonObject json = null; try { json = JsonObject.readFrom(content); } catch (Throwable t) { fail("@@@ Failed parsing received json"); } assertNotNull("check json not null", json); assertNotNull("check not null _type property", json.get("_type")); assertNotNull("check not null _etag property", json.get("_etag")); assertNotNull("check not null _lastupdated_on property", json.get("_lastupdated_on")); assertNotNull("check not null _collection-props-cached property", json.get("_collection-props-cached")); assertNotNull("check not null _returned property", json.get("_returned")); assertNull("check null _size property", json.get("_size")); assertNull("check null _total_pages property", json.get("_total_pages")); assertNotNull("check not null _embedded", json.get("_embedded")); assertTrue("check _embedded to be a json object", (json.get("_embedded") instanceof JsonObject)); JsonObject embedded = (JsonObject) json.get("_embedded"); assertNotNull("check not null _embedded.rh:doc", embedded.get("rh:doc")); assertTrue("check _embedded.rh:doc to be a json array", (embedded.get("rh:doc") instanceof JsonArray)); JsonArray rhdoc = (JsonArray) embedded.get("rh:doc"); assertNotNull("check not null _embedded.rh:doc[0]", rhdoc.get(0)); assertTrue("check _embedded.rh:coll[0] to be a json object", (rhdoc.get(0) instanceof JsonObject)); JsonObject rhdoc0 = (JsonObject) rhdoc.get(0); assertNotNull("check not null _embedded.rh:doc[0]._id", rhdoc0.get("_id")); assertNotNull("check not null _embedded.rh:doc[0]._links", rhdoc0.get("_links")); assertTrue("check _embedded.rh:doc[0]._links to be a json object", (rhdoc0.get("_links") instanceof JsonObject)); JsonObject rhdoc0Links = (JsonObject) rhdoc0.get("_links"); assertNotNull("check not null _embedded.rh:doc[0]._links.self", rhdoc0Links.get("self")); assertTrue("check _embedded.rh:doc[0]._links.self to be a json object", (rhdoc0Links.get("self") instanceof JsonObject)); JsonObject rhdb0LinksSelf = (JsonObject) rhdoc0Links.get("self"); assertNotNull("check not null _embedded.rh:doc[0]._links.self.href", rhdb0LinksSelf.get("href")); assertTrue("check _embedded.rh:doc[0]._links.self.href to be a string", (rhdb0LinksSelf.get("href").isString())); try { URI _uri = new URI(rhdb0LinksSelf.get("href").asString()); } catch (URISyntaxException use) { fail("check _embedded.rh:doc[0]._links.self.href to be a valid URI"); } assertNotNull("check not null _link", json.get("_links")); assertTrue("check _link to be a json object", (json.get("_links") instanceof JsonObject)); JsonObject links = (JsonObject) json.get("_links"); assertNotNull("check not null self", links.get("self")); if (!uri.equals(collection1UriRemappedCollection)) { assertNotNull("check not null rh:db", links.get("rh:db")); } else { assertNull("check null rh:db", links.get("rh:db")); } assertNotNull("check not null rh:paging", links.get("rh:paging")); assertNotNull("check not null curies", links.get("curies")); } @Test public void testGetCollectionSort() throws Exception { Response resp = adminExecutor.execute(Request.Get(docsCollectionUriSort)); HttpResponse httpResp = resp.returnResponse(); assertNotNull(httpResp); HttpEntity entity = httpResp.getEntity(); assertNotNull(entity); StatusLine statusLine = httpResp.getStatusLine(); assertNotNull(statusLine); assertEquals("check status code", HttpStatus.SC_OK, statusLine.getStatusCode()); assertNotNull("content type not null", entity.getContentType()); assertEquals("check content type", Representation.HAL_JSON_MEDIA_TYPE, entity.getContentType().getValue()); String content = EntityUtils.toString(entity); assertNotNull("", content); JsonObject json = null; try { json = JsonObject.readFrom(content); } catch (Throwable t) { fail("@@@ Failed parsing received json"); } assertNotNull("check json not null", json); assertNotNull("check not null _embedded", json.get("_embedded")); assertTrue("check _embedded to be a json object", (json.get("_embedded") instanceof JsonObject)); JsonObject embedded = (JsonObject) json.get("_embedded"); assertNotNull("check not null _embedded.rh:doc", embedded.get("rh:doc")); assertTrue("check _embedded.rh:doc to be a json array", (embedded.get("rh:doc") instanceof JsonArray)); JsonArray rhdoc = (JsonArray) embedded.get("rh:doc"); assertNotNull("check not null _embedded.rh:doc[0]", rhdoc.get(0)); assertTrue("check _embedded.rh:coll[0] to be a json object", (rhdoc.get(0) instanceof JsonObject)); JsonObject rhdoc0 = (JsonObject) rhdoc.get(0); assertNotNull("check not null _embedded.rh:doc[0]._id", rhdoc0.get("_id")); assertNotNull("check not null _embedded.rh:doc[0].name", rhdoc0.get("name")); assertEquals("check not null _embedded.rh:doc[1].name", "Morrissey", rhdoc0.get("name").asString()); JsonObject rhdoc1 = (JsonObject) rhdoc.get(1); assertNotNull("check not null _embedded.rh:doc[1]._id", rhdoc1.get("_id")); assertNotNull("check not null _embedded.rh:doc[1].name", rhdoc1.get("name")); assertEquals("check not null _embedded.rh:doc[1].name", "Ian", rhdoc1.get("name").asString()); } @Test public void testGetCollectionFilter() throws Exception { Response resp = adminExecutor.execute(Request.Get(docsCollectionUriFilter)); HttpResponse httpResp = resp.returnResponse(); assertNotNull(httpResp); HttpEntity entity = httpResp.getEntity(); assertNotNull(entity); StatusLine statusLine = httpResp.getStatusLine(); assertNotNull(statusLine); assertEquals("check status code", HttpStatus.SC_OK, statusLine.getStatusCode()); assertNotNull("content type not null", entity.getContentType()); assertEquals("check content type", Representation.HAL_JSON_MEDIA_TYPE, entity.getContentType().getValue()); String content = EntityUtils.toString(entity); assertNotNull("", content); JsonObject json = null; try { json = JsonObject.readFrom(content); } catch (Throwable t) { fail("@@@ Failed parsing received json"); } assertNotNull("check json not null", json); assertNotNull("check _size not null", json.get("_size")); assertEquals("check _size value to be 2", 2, json.get("_size").asInt()); assertNotNull("check _returned not null", json.get("_returned")); assertEquals("check _returned value to be 2", 2, json.get("_returned").asInt()); assertNotNull("check not null _embedded", json.get("_embedded")); assertTrue("check _embedded to be a json object", (json.get("_embedded") instanceof JsonObject)); JsonObject embedded = (JsonObject) json.get("_embedded"); assertNotNull("check not null _embedded.rh:doc", embedded.get("rh:doc")); assertTrue("check _embedded.rh:doc to be a json array", (embedded.get("rh:doc") instanceof JsonArray)); JsonArray rhdoc = (JsonArray) embedded.get("rh:doc"); assertNotNull("check not null _embedded.rh:doc[0]", rhdoc.get(0)); assertTrue("check _embedded.rh:coll[0] to be a json object", (rhdoc.get(0) instanceof JsonObject)); JsonObject rhdoc0 = (JsonObject) rhdoc.get(0); assertNotNull("check not null _embedded.rh:doc[0]._id", rhdoc0.get("_id")); assertNotNull("check not null _embedded.rh:doc[0].name", rhdoc0.get("name")); assertEquals("check _embedded.rh:doc[1].name value to be Mark", "Mark", rhdoc0.get("name").asString()); JsonObject rhdoc1 = (JsonObject) rhdoc.get(1); assertNotNull("check not null _embedded.rh:doc[1]._id", rhdoc1.get("_id")); assertNotNull("check not null _embedded.rh:doc[1].name", rhdoc1.get("name")); assertEquals("check _embedded.rh:doc[1].name value to be Nick", "Nick", rhdoc1.get("name").asString()); } }
agpl-3.0
rroart/aether
core/src/main/java/roart/util/MyAtomicLongFactory.java
348
package roart.util; import roart.common.config.MyConfig; public class MyAtomicLongFactory extends MyFactory { public MyAtomicLong create(String listid) { if (MyConfig.conf.wantDistributedTraverse()) { return new MyHazelcastAtomicLong(listid); } else { return new MyJavaAtomicLong(); } } }
agpl-3.0
opensourceBIM/BIMserver
PluginBase/generated/org/bimserver/models/ifc4/IfcPipeFittingTypeEnum.java
12059
/** * 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/>}. *****************************************************************************/ import java.util.Arrays; import java.util.Collections; import java.util.List; import org.eclipse.emf.common.util.Enumerator; /** * <!-- begin-user-doc --> * A representation of the literals of the enumeration '<em><b>Ifc Pipe Fitting Type Enum</b></em>', * and utility methods for working with them. * <!-- end-user-doc --> * @see org.bimserver.models.ifc4.Ifc4Package#getIfcPipeFittingTypeEnum() * @model * @generated */ public enum IfcPipeFittingTypeEnum implements Enumerator { /** * The '<em><b>NULL</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #NULL_VALUE * @generated * @ordered */ NULL(0, "NULL", "NULL"), /** * The '<em><b>TRANSITION</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #TRANSITION_VALUE * @generated * @ordered */ TRANSITION(1, "TRANSITION", "TRANSITION"), /** * The '<em><b>NOTDEFINED</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #NOTDEFINED_VALUE * @generated * @ordered */ NOTDEFINED(2, "NOTDEFINED", "NOTDEFINED"), /** * The '<em><b>ENTRY</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #ENTRY_VALUE * @generated * @ordered */ ENTRY(3, "ENTRY", "ENTRY"), /** * The '<em><b>BEND</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #BEND_VALUE * @generated * @ordered */ BEND(4, "BEND", "BEND"), /** * The '<em><b>OBSTRUCTION</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #OBSTRUCTION_VALUE * @generated * @ordered */ OBSTRUCTION(5, "OBSTRUCTION", "OBSTRUCTION"), /** * The '<em><b>USERDEFINED</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #USERDEFINED_VALUE * @generated * @ordered */ USERDEFINED(6, "USERDEFINED", "USERDEFINED"), /** * The '<em><b>EXIT</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #EXIT_VALUE * @generated * @ordered */ EXIT(7, "EXIT", "EXIT"), /** * The '<em><b>JUNCTION</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #JUNCTION_VALUE * @generated * @ordered */ JUNCTION(8, "JUNCTION", "JUNCTION"), /** * The '<em><b>CONNECTOR</b></em>' literal object. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @see #CONNECTOR_VALUE * @generated * @ordered */ CONNECTOR(9, "CONNECTOR", "CONNECTOR"); /** * The '<em><b>NULL</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>NULL</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #NULL * @model * @generated * @ordered */ public static final int NULL_VALUE = 0; /** * The '<em><b>TRANSITION</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>TRANSITION</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #TRANSITION * @model * @generated * @ordered */ public static final int TRANSITION_VALUE = 1; /** * The '<em><b>NOTDEFINED</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>NOTDEFINED</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #NOTDEFINED * @model * @generated * @ordered */ public static final int NOTDEFINED_VALUE = 2; /** * The '<em><b>ENTRY</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>ENTRY</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #ENTRY * @model * @generated * @ordered */ public static final int ENTRY_VALUE = 3; /** * The '<em><b>BEND</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>BEND</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #BEND * @model * @generated * @ordered */ public static final int BEND_VALUE = 4; /** * The '<em><b>OBSTRUCTION</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>OBSTRUCTION</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #OBSTRUCTION * @model * @generated * @ordered */ public static final int OBSTRUCTION_VALUE = 5; /** * The '<em><b>USERDEFINED</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>USERDEFINED</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #USERDEFINED * @model * @generated * @ordered */ public static final int USERDEFINED_VALUE = 6; /** * The '<em><b>EXIT</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>EXIT</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #EXIT * @model * @generated * @ordered */ public static final int EXIT_VALUE = 7; /** * The '<em><b>JUNCTION</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>JUNCTION</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #JUNCTION * @model * @generated * @ordered */ public static final int JUNCTION_VALUE = 8; /** * The '<em><b>CONNECTOR</b></em>' literal value. * <!-- begin-user-doc --> * <p> * If the meaning of '<em><b>CONNECTOR</b></em>' literal object isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @see #CONNECTOR * @model * @generated * @ordered */ public static final int CONNECTOR_VALUE = 9; /** * An array of all the '<em><b>Ifc Pipe Fitting Type Enum</b></em>' enumerators. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private static final IfcPipeFittingTypeEnum[] VALUES_ARRAY = new IfcPipeFittingTypeEnum[] { NULL, TRANSITION, NOTDEFINED, ENTRY, BEND, OBSTRUCTION, USERDEFINED, EXIT, JUNCTION, CONNECTOR, }; /** * A public read-only list of all the '<em><b>Ifc Pipe Fitting Type Enum</b></em>' enumerators. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ public static final List<IfcPipeFittingTypeEnum> VALUES = Collections.unmodifiableList(Arrays.asList(VALUES_ARRAY)); /** * Returns the '<em><b>Ifc Pipe Fitting Type Enum</b></em>' literal with the specified literal value. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param literal the literal. * @return the matching enumerator or <code>null</code>. * @generated */ public static IfcPipeFittingTypeEnum get(String literal) { for (int i = 0; i < VALUES_ARRAY.length; ++i) { IfcPipeFittingTypeEnum result = VALUES_ARRAY[i]; if (result.toString().equals(literal)) { return result; } } return null; } /** * Returns the '<em><b>Ifc Pipe Fitting Type Enum</b></em>' literal with the specified name. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param name the name. * @return the matching enumerator or <code>null</code>. * @generated */ public static IfcPipeFittingTypeEnum getByName(String name) { for (int i = 0; i < VALUES_ARRAY.length; ++i) { IfcPipeFittingTypeEnum result = VALUES_ARRAY[i]; if (result.getName().equals(name)) { return result; } } return null; } /** * Returns the '<em><b>Ifc Pipe Fitting Type Enum</b></em>' literal with the specified integer value. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the integer value. * @return the matching enumerator or <code>null</code>. * @generated */ public static IfcPipeFittingTypeEnum get(int value) { switch (value) { case NULL_VALUE: return NULL; case TRANSITION_VALUE: return TRANSITION; case NOTDEFINED_VALUE: return NOTDEFINED; case ENTRY_VALUE: return ENTRY; case BEND_VALUE: return BEND; case OBSTRUCTION_VALUE: return OBSTRUCTION; case USERDEFINED_VALUE: return USERDEFINED; case EXIT_VALUE: return EXIT; case JUNCTION_VALUE: return JUNCTION; case CONNECTOR_VALUE: return CONNECTOR; } return null; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private final int value; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private final String name; /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private final String literal; /** * Only this class can construct instances. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ private IfcPipeFittingTypeEnum(int value, String name, String literal) { this.value = value; this.name = name; this.literal = literal; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public int getValue() { return value; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String getName() { return name; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String getLiteral() { return literal; } /** * Returns the literal value of the enumerator, which is its string representation. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public String toString() { return literal; } } //IfcPipeFittingTypeEnum
agpl-3.0
automenta/narchy
lab/src/main/java/nars/experiment/minicraft/top/item/ToolType.java
569
package nars.experiment.minicraft.top.item; public class ToolType { public static final ToolType shovel = new ToolType("Shvl", 0); public static final ToolType hoe = new ToolType("Hoe", 1); public static final ToolType sword = new ToolType("Swrd", 2); public static final ToolType pickaxe = new ToolType("Pick", 3); public static final ToolType axe = new ToolType("Axe", 4); public final String name; public final int sprite; private ToolType(String name, int sprite) { this.name = name; this.sprite = sprite; } }
agpl-3.0
kaltura/KalturaGeneratedAPIClientsJava
src/main/java/com/kaltura/client/types/ESearchAggregationBucket.java
3045
// =================================================================================================== // _ __ _ _ // | |/ /__ _| | |_ _ _ _ _ __ _ // | ' </ _` | | _| || | '_/ _` | // |_|\_\__,_|_|\__|\_,_|_| \__,_| // // This file is part of the Kaltura Collaborative Media Suite which allows users // to do with audio, video, and animation what Wiki platforms allow them to do with // text. // // Copyright (C) 2006-2022 Kaltura 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/>. // // @ignore // =================================================================================================== package com.kaltura.client.types; import com.google.gson.JsonObject; import com.kaltura.client.Params; import com.kaltura.client.types.ObjectBase; import com.kaltura.client.utils.GsonParser; import com.kaltura.client.utils.request.MultiRequestBuilder; /** * This class was generated using generate.php * against an XML schema provided by Kaltura. * * MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN. */ @SuppressWarnings("serial") @MultiRequestBuilder.Tokenizer(ESearchAggregationBucket.Tokenizer.class) public class ESearchAggregationBucket extends ObjectBase { public interface Tokenizer extends ObjectBase.Tokenizer { String value(); String count(); } private String value; private Integer count; // value: public String getValue(){ return this.value; } public void setValue(String value){ this.value = value; } public void value(String multirequestToken){ setToken("value", multirequestToken); } // count: public Integer getCount(){ return this.count; } public void setCount(Integer count){ this.count = count; } public void count(String multirequestToken){ setToken("count", multirequestToken); } public ESearchAggregationBucket() { super(); } public ESearchAggregationBucket(JsonObject jsonObject) throws APIException { super(jsonObject); if(jsonObject == null) return; // set members values: value = GsonParser.parseString(jsonObject.get("value")); count = GsonParser.parseInt(jsonObject.get("count")); } public Params toParams() { Params kparams = super.toParams(); kparams.add("objectType", "KalturaESearchAggregationBucket"); kparams.add("value", this.value); kparams.add("count", this.count); return kparams; } }
agpl-3.0
o2oa/o2oa
o2server/x_program_center/src/main/java/com/x/program/center/jaxrs/code/ActionListPaging.java
1618
package com.x.program.center.jaxrs.code; import com.x.base.core.container.EntityManagerContainer; import com.x.base.core.container.factory.EntityManagerContainerFactory; import com.x.base.core.entity.JpaObject; import com.x.base.core.project.bean.WrapCopier; import com.x.base.core.project.bean.WrapCopierFactory; import com.x.base.core.project.http.ActionResult; import com.x.base.core.project.http.EffectivePerson; import com.x.program.center.core.entity.Code; import javax.persistence.EntityManager; import javax.persistence.criteria.CriteriaBuilder; import javax.persistence.criteria.Predicate; import java.util.List; class ActionListPaging extends BaseAction { ActionResult<List<Wo>> execute(EffectivePerson effectivePerson, Integer page, Integer size) throws Exception { try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) { ActionResult<List<Wo>> result = new ActionResult<>(); EntityManager em = emc.get(Code.class); CriteriaBuilder cb = em.getCriteriaBuilder(); Predicate p = cb.conjunction(); List<Wo> wos = emc.fetchDescPaging(Code.class, Wo.copier, p, page, size, Code.sequence_FIELDNAME); result.setData(wos); result.setCount(emc.count(Code.class, p)); return result; } } public static class Wo extends Code { private static final long serialVersionUID = 9141971868817571577L; static WrapCopier<Code, Wo> copier = WrapCopierFactory.wo(Code.class, Wo.class, null, JpaObject.FieldsInvisible); private Long rank; public Long getRank() { return rank; } public void setRank(Long rank) { this.rank = rank; } } }
agpl-3.0
MCBans/MCBansAssetGatway
src/com/mcbans/firestar/mcbans/request/BaseRequest.java
1801
package com.mcbans.firestar.mcbans.request; import java.util.HashMap; import com.mcbans.firestar.mcbans.ActionLog; import com.mcbans.firestar.mcbans.MCBans; import com.mcbans.firestar.mcbans.callBacks.BaseCallback; import com.mcbans.firestar.mcbans.org.json.JSONObject; public abstract class BaseRequest<Callback extends BaseCallback> implements Runnable{ protected final MCBans plugin; protected final ActionLog log; protected HashMap<String, String> items; protected Callback callback; public BaseRequest(final MCBans plugin, final Callback callback){ this.plugin = plugin; this.log = plugin.getLog(); this.callback = callback; this.items = new HashMap<String, String>(); } @Override public void run(){ if (!checkServer()){ callback.error("&cCould not select MCBans API Server!"); return; } execute(); } protected abstract void execute(); private boolean checkServer(){ while (plugin.apiServer == null) { // waiting for server select try { Thread.sleep(1000); } catch (InterruptedException e) {} } return (plugin.apiServer != null); } protected void request(){ JsonHandler webHandle = new JsonHandler(plugin); webHandle.mainRequest(items); } protected String request_String(){ JsonHandler webHandle = new JsonHandler(plugin); String urlReq = webHandle.urlparse(items); return webHandle.request_from_api(urlReq); } protected JSONObject request_JOBJ(){ JsonHandler webHandle = new JsonHandler(plugin); return webHandle.hdl_jobj(items); } }
agpl-3.0
laurent-fr/MyZimbra-Cloud
src/net/myzimbra/cloud/soap/NotifyFolders.java
4520
/* * MyZimbra Cloud - Owncloud clients synchronized directly with Zimbra briefcase * Copyright (C) 2016-2017 Laurent FRANCOISE * * 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.myzimbra.cloud.soap; import com.zimbra.common.service.ServiceException; import com.zimbra.common.soap.Element; import com.zimbra.cs.account.Account; import com.zimbra.cs.mailbox.Folder; import com.zimbra.cs.mailbox.MailItem; import com.zimbra.cs.mailbox.MailItem.CustomMetadata; import com.zimbra.cs.mailbox.Mailbox; import com.zimbra.cs.mailbox.OperationContext; import com.zimbra.soap.DocumentHandler; import static com.zimbra.soap.DocumentHandler.getOperationContext; import static com.zimbra.soap.DocumentHandler.getRequestedAccount; import static com.zimbra.soap.DocumentHandler.getRequestedMailbox; import static com.zimbra.soap.DocumentHandler.getZimbraSoapContext; import com.zimbra.soap.ZimbraSoapContext; import java.util.Map; import org.apache.commons.lang.RandomStringUtils; import org.dom4j.Namespace; import org.dom4j.QName; /** * * cf cs/service/mail/SetCustomMetadata.java * * @author Laurent FRANCOISE */ public class NotifyFolders extends DocumentHandler { static QName REQUEST_QNAME = new QName("NotifyFoldersRequest", Namespace.get("urn:zimbraCloud")); static QName RESPONSE_QNAME = new QName("NotifyFoldersResponse", Namespace.get("urn:zimbraCloud")); @Override public Element handle(Element request, Map<String, Object> context) throws ServiceException { ZimbraSoapContext zsc = getZimbraSoapContext(context); Account account = getRequestedAccount(zsc); Mailbox mbox = getRequestedMailbox(zsc); OperationContext octxt = getOperationContext(zsc, context); if (!canAccessAccount(zsc, account)) { throw ServiceException.PERM_DENIED("can not access account"); } Folder folder; Element pathElt = request.getOptionalElement("path"); if (pathElt != null) { String path = pathElt.getText(); folder = mbox.getFolderByPath(octxt, path); if (folder == null) { throw ServiceException.NOT_FOUND("folder" + path + " not found"); } } else { Element folderIdElt = request.getElement("id"); String folderId = folderIdElt.getTextTrim(); folder = mbox.getFolderById(octxt, Integer.valueOf(folderId)); if (folder == null) { throw ServiceException.NOT_FOUND("folder id " + folderId + " not found"); } } if (folder.getDefaultView() != MailItem.Type.DOCUMENT) { throw ServiceException.NOT_FOUND("folder " + folder.getName() + " (" + folder.getId() + ") is not in Document view."); } int id = -1; int limit = 30; String ids = ""; while (id != 1) { ids = ids + " " + folder.getId(); CustomMetadata custom = new CustomMetadata("oc"); String oc = RandomStringUtils.randomAscii(8); custom.put("ocid", oc); mbox.setCustomData(octxt, folder.getId(), MailItem.Type.UNKNOWN, custom); folder = (Folder) folder.getParent(); id = folder.getId(); limit = limit - 1; if (limit < 0) { throw ServiceException.INTERRUPTED("Cannot find root folder for " + folder.getName()); } } Element response = zsc.createElement(RESPONSE_QNAME); Element replyElt = response.addElement("reply"); replyElt.setText("Folder " + ids + ", account " + account.getMail() + "!"); return response; } /* @Override public boolean needsAuth(Map<String, Object> context) { return true; }*/ }
agpl-3.0
migue/voltdb
src/frontend/org/voltdb/jdbc/JDBC4DatabaseMetaData.java
57351
/* This file is part of VoltDB. * Copyright (C) 2008-2017 VoltDB Inc. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with VoltDB. If not, see <http://www.gnu.org/licenses/>. */ package org.voltdb.jdbc; import java.sql.CallableStatement; import java.sql.Connection; import java.sql.ResultSet; import java.sql.RowIdLifetime; import java.sql.SQLException; import java.util.Arrays; import java.util.List; import java.util.regex.Matcher; import java.util.regex.Pattern; import org.voltdb.VoltTable; import org.voltdb.VoltTable.ColumnInfo; import org.voltdb.VoltType; public class JDBC4DatabaseMetaData implements java.sql.DatabaseMetaData { /* * Two types of tables the metadata generator generates. It has to match the * table types generated in JdbcDatabaseMetaDataGenerator. */ static final String tableTypes[] = new String[] {"TABLE", "VIEW"}; private final CallableStatement sysInfo; private final CallableStatement sysCatalog; private final JDBC4Connection sourceConnection; JDBC4DatabaseMetaData(JDBC4Connection connection) throws SQLException { this.sourceConnection = connection; this.sysInfo = connection.prepareCall("{call @SystemInformation}"); this.sysCatalog = connection.prepareCall("{call @SystemCatalog(?)}"); // Initialize system information loadSystemInformation(); } private String buildString = null; private String versionString = null; private String catalogString = null; private void loadSystemInformation() throws SQLException { ResultSet res = this.sysInfo.executeQuery(); while (res.next()) { if (res.getString(2).equals("BUILDSTRING")) buildString = res.getString(3); else if (res.getString(2).equals("VERSION")) versionString = res.getString(3); else if (res.getString(2).equals("CATALOG")) catalogString = res.getString(3); } res.close(); } private void checkClosed() throws SQLException { if (this.sourceConnection.isClosed()) throw SQLError.get(SQLError.CONNECTION_CLOSED); } // Retrieves whether the current user can call all the procedures returned by the method getProcedures. @Override public boolean allProceduresAreCallable() throws SQLException { checkClosed(); return true; } // Retrieves whether the current user can use all the tables returned by the method getTables in a SELECT statement. @Override public boolean allTablesAreSelectable() throws SQLException { checkClosed(); return true; } // Retrieves whether a SQLException while autoCommit is true indicates that all open ResultSets are closed, even ones that are holdable. @Override public boolean autoCommitFailureClosesAllResultSets() throws SQLException { checkClosed(); return true; } // Retrieves whether a data definition statement within a transaction forces the transaction to commit. @Override public boolean dataDefinitionCausesTransactionCommit() throws SQLException { checkClosed(); return true; } // Retrieves whether this database ignores a data definition statement within a transaction. @Override public boolean dataDefinitionIgnoredInTransactions() throws SQLException { checkClosed(); return true; } // Retrieves whether or not a visible row delete can be detected by calling the method ResultSet.rowDeleted. @Override public boolean deletesAreDetected(int type) throws SQLException { checkClosed(); return false; } // Retrieves whether the return value for the method getMaxRowSize includes the SQL data types LONGVARCHAR and LONGVARBINARY. @Override public boolean doesMaxRowSizeIncludeBlobs() throws SQLException { checkClosed(); return true; } // Retrieves a description of the given attribute of the given type for a user-defined type (UDT) that is available in the given schema and catalog. @Override public ResultSet getAttributes(String catalog, String schemaPattern, String typeNamePattern, String attributeNamePattern) throws SQLException { checkClosed(); throw SQLError.noSupport(); } // Retrieves a description of a table's optimal set of columns that uniquely identifies a row. @Override public ResultSet getBestRowIdentifier(String catalog, String schema, String table, int scope, boolean nullable) throws SQLException { checkClosed(); throw SQLError.noSupport(); } // Retrieves the catalog names available in this database. @Override public ResultSet getCatalogs() throws SQLException { checkClosed(); VoltTable result = new VoltTable(new VoltTable.ColumnInfo("TABLE_CAT",VoltType.STRING)); result.addRow(new Object[] { catalogString }); return new JDBC4ResultSet(null, result); } // Retrieves the String that this database uses as the separator between a catalog and table name. @Override public String getCatalogSeparator() throws SQLException { return "."; } // Retrieves the database vendor's preferred term for "catalog". @Override public String getCatalogTerm() throws SQLException { checkClosed(); return "catalog"; } // Retrieves a list of the client info properties that the driver supports. @Override public ResultSet getClientInfoProperties() throws SQLException { checkClosed(); throw SQLError.noSupport(); } // Retrieves a description of the access rights for a table's columns. @Override public ResultSet getColumnPrivileges(String catalog, String schema, String table, String columnNamePattern) throws SQLException { checkClosed(); throw SQLError.noSupport(); } // Retrieves a description of table columns available in the specified catalog. @Override public ResultSet getColumns(String catalog, String schemaPattern, String tableNamePattern, String columnNamePattern) throws SQLException { checkClosed(); this.sysCatalog.setString(1, "COLUMNS"); JDBC4ResultSet res = (JDBC4ResultSet) this.sysCatalog.executeQuery(); VoltTable vtable = res.getVoltTable().clone(0); // If no pattern is specified, default to matching any/all. if (tableNamePattern == null || tableNamePattern.length() == 0) { tableNamePattern = "%"; } Pattern table_pattern = computeJavaPattern(tableNamePattern); if (columnNamePattern == null || columnNamePattern.length() == 0) { columnNamePattern = "%"; } Pattern column_pattern = computeJavaPattern(columnNamePattern); // Filter columns based on table name and column name while (res.next()) { Matcher table_matcher = table_pattern.matcher(res.getString("TABLE_NAME")); if (table_matcher.matches()) { Matcher column_matcher = column_pattern.matcher(res.getString("COLUMN_NAME")); if (column_matcher.matches()) { vtable.addRow(res.getRowData()); } } } return new JDBC4ResultSet(this.sysCatalog, vtable); } // Retrieves the connection that produced this metadata object. @Override public Connection getConnection() throws SQLException { checkClosed(); return sourceConnection; } // Retrieves a description of the foreign key columns in the given foreign key table that reference the primary key or the columns representing a unique constraint of the parent table (could be the same or a different table). @Override public ResultSet getCrossReference(String parentCatalog, String parentSchema, String parentTable, String foreignCatalog, String foreignSchema, String foreignTable) throws SQLException { checkClosed(); throw SQLError.noSupport(); } // Retrieves the major version number of the underlying database. @Override public int getDatabaseMajorVersion() throws SQLException { checkClosed(); System.out.println("\n\n\nVERSION: " + versionString); return Integer.valueOf(versionString.split("\\.")[0]); } // Retrieves the minor version number of the underlying database. @Override public int getDatabaseMinorVersion() throws SQLException { checkClosed(); return Integer.valueOf(versionString.split("\\.")[1]); } // Retrieves the name of this database product. @Override public String getDatabaseProductName() throws SQLException { checkClosed(); return "VoltDB"; } // Retrieves the version number of this database product. @Override public String getDatabaseProductVersion() throws SQLException { checkClosed(); return buildString; } // Retrieves this database's default transaction isolation level. @Override public int getDefaultTransactionIsolation() throws SQLException { checkClosed(); return Connection.TRANSACTION_SERIALIZABLE; } // Retrieves this JDBC driver's major version number. @Override public int getDriverMajorVersion() { return 1; } // Retrieves this JDBC driver's minor version number. @Override public int getDriverMinorVersion() { return 1; } // Retrieves the name of this JDBC driver. @Override public String getDriverName() throws SQLException { checkClosed(); return "voltdb"; } // Retrieves the version number of this JDBC driver as a String. @Override public String getDriverVersion() throws SQLException { checkClosed(); return new String(getDriverMajorVersion() + "." + getDriverMinorVersion()); } /** * Retrieves a description of the foreign key columns that reference the * given table's primary key columns (the foreign keys exported by a table). */ @Override public ResultSet getExportedKeys(String catalog, String schema, String table) throws SQLException { checkClosed(); VoltTable vtable = new VoltTable( new ColumnInfo("PKTABLE_CAT", VoltType.STRING), new ColumnInfo("PKTABLE_SCHEM", VoltType.STRING), new ColumnInfo("PKTABLE_NAME", VoltType.STRING), new ColumnInfo("PKCOLUMN_NAME", VoltType.STRING), new ColumnInfo("FKTABLE_CAT", VoltType.STRING), new ColumnInfo("FKTABLE_SCHEM", VoltType.STRING), new ColumnInfo("FKTABLE_NAME", VoltType.STRING), new ColumnInfo("FKCOLUMN_NAME", VoltType.STRING), new ColumnInfo("KEY_SEQ", VoltType.SMALLINT), new ColumnInfo("UPDATE_RULE", VoltType.SMALLINT), new ColumnInfo("DELETE_RULE", VoltType.SMALLINT), new ColumnInfo("FK_NAME", VoltType.STRING), new ColumnInfo("PK_NAME", VoltType.STRING), new ColumnInfo("DEFERRABILITY", VoltType.SMALLINT) ); //NB: @SystemCatalog(?) will need additional support if we want to // populate the table. JDBC4ResultSet res = new JDBC4ResultSet(this.sysCatalog, vtable); return res; } /** * Retrieves all the "extra" characters that can be used in unquoted identifier * names (those beyond a-z, A-Z, 0-9 and _). */ @Override public String getExtraNameCharacters() throws SQLException { checkClosed(); return ""; } // Retrieves a description of the given catalog's system or user function parameters and return type. @Override public ResultSet getFunctionColumns(String catalog, String schemaPattern, String functionNamePattern, String columnNamePattern) throws SQLException { checkClosed(); throw SQLError.noSupport(); } // Retrieves a description of the system and user functions available in the given catalog. @Override public ResultSet getFunctions(String catalog, String schemaPattern, String functionNamePattern) throws SQLException { checkClosed(); throw SQLError.noSupport(); } // Retrieves the string used to quote SQL identifiers. @Override public String getIdentifierQuoteString() throws SQLException { checkClosed(); return "\""; } // Retrieves a description of the primary key columns that are referenced by the given table's foreign key columns (the primary keys imported by a table) throws SQLException. @Override public ResultSet getImportedKeys(String catalog, String schema, String table) throws SQLException { checkClosed(); VoltTable vtable = new VoltTable( new ColumnInfo("PKTABLE_CAT", VoltType.STRING), new ColumnInfo("PKTABLE_SCHEM", VoltType.STRING), new ColumnInfo("PKTABLE_NAME", VoltType.STRING), new ColumnInfo("PKCOLUMN_NAME", VoltType.STRING), new ColumnInfo("FKTABLE_CAT", VoltType.STRING), new ColumnInfo("FKTABLE_SCHEM", VoltType.STRING), new ColumnInfo("FKTABLE_NAME", VoltType.STRING), new ColumnInfo("FKCOLUMN_NAME", VoltType.STRING), new ColumnInfo("KEY_SEQ", VoltType.SMALLINT), new ColumnInfo("UPDATE_RULE", VoltType.SMALLINT), new ColumnInfo("DELETE_RULE", VoltType.SMALLINT), new ColumnInfo("FK_NAME", VoltType.STRING), new ColumnInfo("PK_NAME", VoltType.STRING), new ColumnInfo("DEFERRABILITY", VoltType.SMALLINT) ); //NB: @SystemCatalog(?) will need additional support if we want to // populate the table. JDBC4ResultSet res = new JDBC4ResultSet(this.sysCatalog, vtable); return res; } // Retrieves a description of the given table's indices and statistics. // NOTE: currently returns the NON_UNIQUE column as a TINYINT due // to lack of boolean support in VoltTable schemas. @Override public ResultSet getIndexInfo(String catalog, String schema, String table, boolean unique, boolean approximate) throws SQLException { assert(table != null && !table.isEmpty()); checkClosed(); this.sysCatalog.setString(1, "INDEXINFO"); JDBC4ResultSet res = (JDBC4ResultSet) this.sysCatalog.executeQuery(); VoltTable vtable = res.getVoltTable().clone(0); // Filter the indexes by table name while (res.next()) { if (res.getString("TABLE_NAME").equals(table)) { if (!unique || res.getShort("NON_UNIQUE") == 0) { vtable.addRow(res.getRowData()); } } } return new JDBC4ResultSet(sysCatalog, vtable); } // Retrieves the major JDBC version number for this driver. @Override public int getJDBCMajorVersion() throws SQLException { checkClosed(); return 4; } // Retrieves the minor JDBC version number for this driver. @Override public int getJDBCMinorVersion() throws SQLException { checkClosed(); return 0; } // Retrieves the maximum number of hex characters this database allows in an inline binary literal. @Override public int getMaxBinaryLiteralLength() throws SQLException { checkClosed(); return VoltType.MAX_VALUE_LENGTH; } // Retrieves the maximum number of characters that this database allows in a catalog name. @Override public int getMaxCatalogNameLength() throws SQLException { checkClosed(); throw SQLError.noSupport(); } // Retrieves the maximum number of characters this database allows for a character literal. @Override public int getMaxCharLiteralLength() throws SQLException { checkClosed(); return VoltType.MAX_VALUE_LENGTH; } // Retrieves the maximum number of characters this database allows for a column name. @Override public int getMaxColumnNameLength() throws SQLException { checkClosed(); throw SQLError.noSupport(); } // Retrieves the maximum number of columns this database allows in a GROUP BY clause. @Override public int getMaxColumnsInGroupBy() throws SQLException { checkClosed(); throw SQLError.noSupport(); } // Retrieves the maximum number of columns this database allows in an index. @Override public int getMaxColumnsInIndex() throws SQLException { checkClosed(); throw SQLError.noSupport(); } // Retrieves the maximum number of columns this database allows in an ORDER BY clause. @Override public int getMaxColumnsInOrderBy() throws SQLException { checkClosed(); throw SQLError.noSupport(); } // Retrieves the maximum number of columns this database allows in a SELECT list. @Override public int getMaxColumnsInSelect() throws SQLException { checkClosed(); throw SQLError.noSupport(); } // Retrieves the maximum number of columns this database allows in a table. @Override public int getMaxColumnsInTable() throws SQLException { checkClosed(); throw SQLError.noSupport(); } // Retrieves the maximum number of concurrent connections to this database that are possible. @Override public int getMaxConnections() throws SQLException { checkClosed(); throw SQLError.noSupport(); } // Retrieves the maximum number of characters that this database allows in a cursor name. @Override public int getMaxCursorNameLength() throws SQLException { checkClosed(); throw SQLError.noSupport(); } // Retrieves the maximum number of bytes this database allows for an index, including all of the parts of the index. @Override public int getMaxIndexLength() throws SQLException { checkClosed(); throw SQLError.noSupport(); } // Retrieves the maximum number of characters that this database allows in a procedure name. @Override public int getMaxProcedureNameLength() throws SQLException { checkClosed(); throw SQLError.noSupport(); } // Retrieves the maximum number of bytes this database allows in a single row. @Override public int getMaxRowSize() throws SQLException { checkClosed(); return 2 * 1024 * 1024; // 2 MB } // Retrieves the maximum number of characters that this database allows in a schema name. @Override public int getMaxSchemaNameLength() throws SQLException { checkClosed(); throw SQLError.noSupport(); } // Retrieves the maximum number of characters this database allows in an SQL statement. @Override public int getMaxStatementLength() throws SQLException { checkClosed(); throw SQLError.noSupport(); } // Retrieves the maximum number of active statements to this database that can be open at the same time. @Override public int getMaxStatements() throws SQLException { checkClosed(); throw SQLError.noSupport(); } // Retrieves the maximum number of characters this database allows in a table name. @Override public int getMaxTableNameLength() throws SQLException { checkClosed(); throw SQLError.noSupport(); } // Retrieves the maximum number of tables this database allows in a SELECT statement. @Override public int getMaxTablesInSelect() throws SQLException { checkClosed(); throw SQLError.noSupport(); } // Retrieves the maximum number of characters this database allows in a user name. @Override public int getMaxUserNameLength() throws SQLException { checkClosed(); throw SQLError.noSupport(); } // Retrieves a comma-separated list of math functions available with this database. @Override public String getNumericFunctions() throws SQLException { checkClosed(); return "ABS,BITAND,BITNOT,BITOR,BIT_SHIFT_LEFT,BIT_SHIFT_RIGHT,BITXOR,CEILING,COS,COT,CSC,EXP,FLOOR,LN,LOG,LOG10,PI,POWER,ROUND,SEC,SIN,SQRT,TAN"; } // Retrieves a description of the given table's primary key columns. @Override public ResultSet getPrimaryKeys(String catalog, String schema, String table) throws SQLException { assert(table != null && !table.isEmpty()); checkClosed(); this.sysCatalog.setString(1, "PRIMARYKEYS"); JDBC4ResultSet res = (JDBC4ResultSet) this.sysCatalog.executeQuery(); VoltTable vtable = res.getVoltTable().clone(0); // Filter the primary keys based on table name while (res.next()) { if (res.getString("TABLE_NAME").equals(table)) { vtable.addRow(res.getRowData()); } } return new JDBC4ResultSet(sysCatalog, vtable); } // Retrieves a description of the given catalog's stored procedure parameter and result columns. // TODO: implement pattern filtering somewhere (preferably server-side) @Override public ResultSet getProcedureColumns(String catalog, String schemaPattern, String procedureNamePattern, String columnNamePattern) throws SQLException { assert(procedureNamePattern != null && !procedureNamePattern.isEmpty()); checkClosed(); this.sysCatalog.setString(1, "PROCEDURECOLUMNS"); JDBC4ResultSet res = (JDBC4ResultSet) this.sysCatalog.executeQuery(); VoltTable vtable = res.getVoltTable().clone(0); // Filter the results based on procedure name and column name while (res.next()) { if (res.getString("PROCEDURE_NAME").equals(procedureNamePattern)) { if (columnNamePattern == null || columnNamePattern.equals("%") || res.getString("COLUMN_NAME").equals(columnNamePattern)) { vtable.addRow(res.getRowData()); } } } return new JDBC4ResultSet(sysCatalog, vtable); } // Retrieves a description of the stored procedures available in the given catalog. // TODO: implement pattern filtering somewhere (preferably server-side) @Override public ResultSet getProcedures(String catalog, String schemaPattern, String procedureNamePattern) throws SQLException { if (procedureNamePattern != null && !procedureNamePattern.equals("%")) throw new SQLException(String.format("getProcedures('%s','%s','%s') does not support pattern filtering", catalog, schemaPattern, procedureNamePattern)); checkClosed(); this.sysCatalog.setString(1, "PROCEDURES"); ResultSet res = this.sysCatalog.executeQuery(); return res; } // Retrieves the database vendor's preferred term for "procedure". @Override public String getProcedureTerm() throws SQLException { checkClosed(); throw SQLError.noSupport(); } // Retrieves this database's default holdability for ResultSet objects. @Override public int getResultSetHoldability() throws SQLException { checkClosed(); throw SQLError.noSupport(); } // Indicates whether or not this data source supports the SQL ROWID type, and if so the lifetime for which a RowId object remains valid. @Override public RowIdLifetime getRowIdLifetime() throws SQLException { checkClosed(); throw SQLError.noSupport(); } // Retrieves the schema names available in this database. @Override public ResultSet getSchemas() throws SQLException { checkClosed(); VoltTable vtable = new VoltTable( new ColumnInfo("TABLE_SCHEM", VoltType.STRING), new ColumnInfo("TABLE_CATALOG", VoltType.STRING)); JDBC4ResultSet res = new JDBC4ResultSet(this.sysCatalog, vtable); return res; } // Retrieves the schema names available in this database. @Override public ResultSet getSchemas(String catalog, String schemaPattern) throws SQLException { return getSchemas(); // empty } // Retrieves the database vendor's preferred term for "schema". @Override public String getSchemaTerm() throws SQLException { checkClosed(); throw SQLError.noSupport(); } // Retrieves the string that can be used to escape wildcard characters. @Override public String getSearchStringEscape() throws SQLException { checkClosed(); throw SQLError.noSupport(); } // Retrieves a comma-separated list of all of this database's SQL keywords that are NOT also SQL:2003 keywords. @Override public String getSQLKeywords() throws SQLException { checkClosed(); return ""; } // Indicates whether the SQLSTATE returned by SQLException.getSQLState is X/Open (now known as Open Group) SQL CLI or SQL:2003. @Override public int getSQLStateType() throws SQLException { checkClosed(); return sqlStateXOpen; } // Retrieves a comma-separated list of string functions available with this database. @Override public String getStringFunctions() throws SQLException { checkClosed(); // TODO: find a more suitable place for COALESCE return "BIN,COALESCE,CHAR,CHAR_LENGTH,CONCAT,FORMAT_CURRENCY,HEX,STR,INSERT,LCASE,LEFT,LOWER,LTRIM," + "OCTET_LENGTH,OVERLAY,POSITION,REGEXP_POSITION,REPEAT,REPLACE,RIGHT,RTRIM,SPACE,SUBSTRING,SUBSTR,"+ "TRIM,UCASE,UPPER"; } // Retrieves a description of the table hierarchies defined in a particular schema in this database. @Override public ResultSet getSuperTables(String catalog, String schemaPattern, String tableNamePattern) throws SQLException { checkClosed(); throw SQLError.noSupport(); } // Retrieves a description of the user-defined type (UDT) hierarchies defined in a particular schema in this database. @Override public ResultSet getSuperTypes(String catalog, String schemaPattern, String typeNamePattern) throws SQLException { checkClosed(); throw SQLError.noSupport(); } // Retrieves a comma-separated list of system functions available with this database. @Override public String getSystemFunctions() throws SQLException { checkClosed(); throw SQLError.noSupport(); } // Retrieves a description of the access rights for each table available in a catalog. @Override public ResultSet getTablePrivileges(String catalog, String schemaPattern, String tableNamePattern) throws SQLException { checkClosed(); VoltTable vtable = new VoltTable( new ColumnInfo("TABLE_CAT", VoltType.STRING), new ColumnInfo("TABLE_SCHEM", VoltType.STRING), new ColumnInfo("TABLE_NAME", VoltType.STRING), new ColumnInfo("GRANTOR", VoltType.STRING), new ColumnInfo("GRANTEE", VoltType.STRING), new ColumnInfo("PRIVILEGE", VoltType.STRING), new ColumnInfo("IS_GRANTABLE", VoltType.STRING) ); //NB: @SystemCatalog(?) will need additional support if we want to // populate the table. JDBC4ResultSet res = new JDBC4ResultSet(this.sysCatalog, vtable); return res; } // Convert the users VoltDB SQL pattern into a regex pattern public static Pattern computeJavaPattern(String sqlPattern) { StringBuffer pattern_buff = new StringBuffer(); // Replace "_" with "." (match exactly 1 character) // Replace "%" with ".*" (match 0 or more characters) for (int i=0; i<sqlPattern.length(); i++) { char c = sqlPattern.charAt(i); if (c == '_') { pattern_buff.append('.'); } else if (c == '%') { pattern_buff.append(".*"); } else pattern_buff.append(c); } return Pattern.compile(pattern_buff.toString()); } // Retrieves a description of the tables available in the given catalog. @Override public ResultSet getTables(String catalog, String schemaPattern, String tableNamePattern, String[] types) throws SQLException { checkClosed(); this.sysCatalog.setString(1, "TABLES"); JDBC4ResultSet res = (JDBC4ResultSet) this.sysCatalog.executeQuery(); VoltTable vtable = res.getVoltTable().clone(0); List<String> typeStrings = null; if (types != null) { typeStrings = Arrays.asList(types); } // If no pattern is specified, default to matching any/all. if (tableNamePattern == null || tableNamePattern.length() == 0) { tableNamePattern = "%"; } Pattern table_pattern = computeJavaPattern(tableNamePattern); // Filter tables based on type and pattern while (res.next()) { if (typeStrings == null || typeStrings.contains(res.getString("TABLE_TYPE"))) { Matcher table_matcher = table_pattern.matcher(res.getString("TABLE_NAME")); if (table_matcher.matches()) { vtable.addRow(res.getRowData()); } } } return new JDBC4ResultSet(this.sysCatalog, vtable); } // Retrieves the table types available in this database. @Override public ResultSet getTableTypes() throws SQLException { checkClosed(); VoltTable vtable = new VoltTable(new ColumnInfo("TABLE_TYPE", VoltType.STRING)); for (String type : tableTypes) { vtable.addRow(type); } JDBC4ResultSet res = new JDBC4ResultSet(this.sysCatalog, vtable); return res; } // Retrieves a comma-separated list of the time and date functions available with this database. @Override public String getTimeDateFunctions() throws SQLException { checkClosed(); return "CURRENT_TIMESTAMP,DATEADD,DAY,DAYOFMONTH,DAYOFWEEK,DAYOFYEAR,EXTRACT,FROM_UNIXTIME,HOUR," + "IS_VALID_TIMESTAMP,MAX_VALID_TIMESTAMP,MIN_VALID_TIMESTAMP," + "MINUTE,MONTH,NOW,QUARTER,SECOND,SINCE_EPOCH,TO_TIMESTAMP,TRUNCATE,WEEK,WEEKOFYEAR,"+ "WEEKDAY,YEAR"; } // Retrieves a description of all the data types supported by this database. @Override public ResultSet getTypeInfo() throws SQLException { checkClosed(); this.sysCatalog.setString(1, "TYPEINFO"); ResultSet res = this.sysCatalog.executeQuery(); return res; } // Retrieves a description of the user-defined types (UDTs) defined in a particular schema. @Override public ResultSet getUDTs(String catalog, String schemaPattern, String typeNamePattern, int[] types) throws SQLException { checkClosed(); throw SQLError.noSupport(); } // Retrieves the URL for this DBMS. @Override public String getURL() throws SQLException { checkClosed(); return "http://voltdb.com/"; } // Retrieves the user name as known to this database. @Override public String getUserName() throws SQLException { checkClosed(); return this.sourceConnection.User; } // Retrieves a description of a table's columns that are automatically updated when any value in a row is updated. @Override public ResultSet getVersionColumns(String catalog, String schema, String table) throws SQLException { checkClosed(); throw SQLError.noSupport(); } // Retrieves whether or not a visible row insert can be detected by calling the method ResultSet.rowInserted. @Override public boolean insertsAreDetected(int type) throws SQLException { checkClosed(); return false; } // Retrieves whether a catalog appears at the start of a fully qualified table name. @Override public boolean isCatalogAtStart() throws SQLException { checkClosed(); return false; } // Retrieves whether this database is in read-only mode. @Override public boolean isReadOnly() throws SQLException { checkClosed(); return false; } // Indicates whether updates made to a LOB are made on a copy or directly to the LOB. @Override public boolean locatorsUpdateCopy() throws SQLException { checkClosed(); return false; } // Retrieves whether this database supports concatenations between NULL and non-NULL values being NULL. @Override public boolean nullPlusNonNullIsNull() throws SQLException { checkClosed(); return true; } // Retrieves whether NULL values are sorted at the end regardless of sort order. @Override public boolean nullsAreSortedAtEnd() throws SQLException { checkClosed(); return false; } // Retrieves whether NULL values are sorted at the start regardless of sort order. @Override public boolean nullsAreSortedAtStart() throws SQLException { checkClosed(); return false; } // Retrieves whether NULL values are sorted high. @Override public boolean nullsAreSortedHigh() throws SQLException { checkClosed(); return false; } // Retrieves whether NULL values are sorted low. @Override public boolean nullsAreSortedLow() throws SQLException { checkClosed(); return true; } // Retrieves whether deletes made by others are visible. @Override public boolean othersDeletesAreVisible(int type) throws SQLException { checkClosed(); return false; } // Retrieves whether inserts made by others are visible. @Override public boolean othersInsertsAreVisible(int type) throws SQLException { checkClosed(); return false; } // Retrieves whether updates made by others are visible. @Override public boolean othersUpdatesAreVisible(int type) throws SQLException { checkClosed(); return false; } // Retrieves whether a result set's own deletes are visible. @Override public boolean ownDeletesAreVisible(int type) throws SQLException { checkClosed(); return false; } // Retrieves whether a result set's own inserts are visible. @Override public boolean ownInsertsAreVisible(int type) throws SQLException { checkClosed(); return false; } // Retrieves whether for the given type of ResultSet object, the result set's own updates are visible. @Override public boolean ownUpdatesAreVisible(int type) throws SQLException { checkClosed(); return false; } // Retrieves whether this database treats mixed case unquoted SQL identifiers as case insensitive and stores them in lower case. @Override public boolean storesLowerCaseIdentifiers() throws SQLException { checkClosed(); return false; // Note: Proc names are sensitive, but not tables/columns! } // Retrieves whether this database treats mixed case quoted SQL identifiers as case insensitive and stores them in lower case. @Override public boolean storesLowerCaseQuotedIdentifiers() throws SQLException { checkClosed(); return false; // Note: Proc names are sensitive, but not tables/columns! } // Retrieves whether this database treats mixed case unquoted SQL identifiers as case insensitive and stores them in mixed case. @Override public boolean storesMixedCaseIdentifiers() throws SQLException { checkClosed(); return false; // Note: Proc names are sensitive, but not tables/columns! } // Retrieves whether this database treats mixed case quoted SQL identifiers as case insensitive and stores them in mixed case. @Override public boolean storesMixedCaseQuotedIdentifiers() throws SQLException { checkClosed(); return false; // Note: Proc names are sensitive, but not tables/columns! } // Retrieves whether this database treats mixed case unquoted SQL identifiers as case insensitive and stores them in upper case. @Override public boolean storesUpperCaseIdentifiers() throws SQLException { checkClosed(); return true; // Note: Proc names are sensitive, but not tables/columns! } // Retrieves whether this database treats mixed case quoted SQL identifiers as case insensitive and stores them in upper case. @Override public boolean storesUpperCaseQuotedIdentifiers() throws SQLException { checkClosed(); return true; // Note: Proc names are sensitive, but not tables/columns! } // Retrieves whether this database supports ALTER TABLE with add column. @Override public boolean supportsAlterTableWithAddColumn() throws SQLException { checkClosed(); return false; } // Retrieves whether this database supports ALTER TABLE with drop column. @Override public boolean supportsAlterTableWithDropColumn() throws SQLException { checkClosed(); return false; } // Retrieves whether this database supports the ANSI92 entry level SQL grammar. @Override public boolean supportsANSI92EntryLevelSQL() throws SQLException { checkClosed(); return false; } // Retrieves whether this database supports the ANSI92 full SQL grammar supported. @Override public boolean supportsANSI92FullSQL() throws SQLException { checkClosed(); return false; } // Retrieves whether this database supports the ANSI92 intermediate SQL grammar supported. @Override public boolean supportsANSI92IntermediateSQL() throws SQLException { checkClosed(); return false; } // Retrieves whether this database supports batch updates. @Override public boolean supportsBatchUpdates() throws SQLException { checkClosed(); return true; } // Retrieves whether a catalog name can be used in a data manipulation statement. @Override public boolean supportsCatalogsInDataManipulation() throws SQLException { checkClosed(); return false; } // Retrieves whether a catalog name can be used in an index definition statement. @Override public boolean supportsCatalogsInIndexDefinitions() throws SQLException { checkClosed(); return false; } // Retrieves whether a catalog name can be used in a privilege definition statement. @Override public boolean supportsCatalogsInPrivilegeDefinitions() throws SQLException { checkClosed(); return false; } // Retrieves whether a catalog name can be used in a procedure call statement. @Override public boolean supportsCatalogsInProcedureCalls() throws SQLException { checkClosed(); return false; } // Retrieves whether a catalog name can be used in a table definition statement. @Override public boolean supportsCatalogsInTableDefinitions() throws SQLException { checkClosed(); return false; } // Retrieves whether this database supports column aliasing. @Override public boolean supportsColumnAliasing() throws SQLException { checkClosed(); return true; } // Retrieves whether this database supports the JDBC scalar function CONVERT for the conversion of one JDBC type to another. @Override public boolean supportsConvert() throws SQLException { checkClosed(); return false; } // Retrieves whether this database supports the JDBC scalar function CONVERT for conversions between the JDBC types fromType and toType. @Override public boolean supportsConvert(int fromType, int toType) throws SQLException { checkClosed(); switch (fromType) { /* * ALL types can be converted to VARCHAR /VoltType.String */ case java.sql.Types.VARCHAR: case java.sql.Types.VARBINARY: case java.sql.Types.TIMESTAMP: case java.sql.Types.OTHER: switch (toType) { case java.sql.Types.VARCHAR: return true; default: return false; } case java.sql.Types.TINYINT: case java.sql.Types.SMALLINT: case java.sql.Types.INTEGER: case java.sql.Types.BIGINT: case java.sql.Types.FLOAT: case java.sql.Types.DECIMAL: switch (toType) { case java.sql.Types.VARCHAR: case java.sql.Types.TINYINT: case java.sql.Types.SMALLINT: case java.sql.Types.INTEGER: case java.sql.Types.BIGINT: case java.sql.Types.FLOAT: case java.sql.Types.DECIMAL: return true; default: return false; } default: return false; } } // Retrieves whether this database supports the ODBC Core SQL grammar. @Override public boolean supportsCoreSQLGrammar() throws SQLException { checkClosed(); return false; } // Retrieves whether this database supports correlated subqueries. @Override public boolean supportsCorrelatedSubqueries() throws SQLException { checkClosed(); return false; } // Retrieves whether this database supports both data definition and data manipulation statements within a transaction. @Override public boolean supportsDataDefinitionAndDataManipulationTransactions() throws SQLException { checkClosed(); return false; } // Retrieves whether this database supports only data manipulation statements within a transaction. @Override public boolean supportsDataManipulationTransactionsOnly() throws SQLException { checkClosed(); return false; } // Retrieves whether, when table correlation names are supported, they are restricted to being different from the names of the tables. @Override public boolean supportsDifferentTableCorrelationNames() throws SQLException { checkClosed(); return false; // Alias may be same as the table name } // Retrieves whether this database supports expressions in ORDER BY lists. @Override public boolean supportsExpressionsInOrderBy() throws SQLException { checkClosed(); return false; } // Retrieves whether this database supports the ODBC Extended SQL grammar. @Override public boolean supportsExtendedSQLGrammar() throws SQLException { checkClosed(); return false; // Only assuming based on currently limited set } // Retrieves whether this database supports full nested outer joins. @Override public boolean supportsFullOuterJoins() throws SQLException { checkClosed(); return false; } // Retrieves whether auto-generated keys can be retrieved after a statement has been executed @Override public boolean supportsGetGeneratedKeys() throws SQLException { checkClosed(); return false; } // Retrieves whether this database supports some form of GROUP BY clause. @Override public boolean supportsGroupBy() throws SQLException { checkClosed(); return true; } // Retrieves whether this database supports using columns not included in the SELECT statement in a GROUP BY clause provided that all of the columns in the SELECT statement are included in the GROUP BY clause. @Override public boolean supportsGroupByBeyondSelect() throws SQLException { checkClosed(); return false; } // Retrieves whether this database supports using a column that is not in the SELECT statement in a GROUP BY clause. @Override public boolean supportsGroupByUnrelated() throws SQLException { checkClosed(); return false; } // Retrieves whether this database supports the SQL Integrity Enhancement Facility. @Override public boolean supportsIntegrityEnhancementFacility() throws SQLException { checkClosed(); return false; // Does support DEFAULT, but not CHECK and UNIQUE constraints get violated over partition boundaries! } // Retrieves whether this database supports specifying a LIKE escape clause. @Override public boolean supportsLikeEscapeClause() throws SQLException { checkClosed(); return false; } // Retrieves whether this database provides limited support for outer joins. @Override public boolean supportsLimitedOuterJoins() throws SQLException { checkClosed(); return true; } // Retrieves whether this database supports the ODBC Minimum SQL grammar. @Override public boolean supportsMinimumSQLGrammar() throws SQLException { checkClosed(); return false; } // Retrieves whether this database treats mixed case unquoted SQL identifiers as case sensitive and as a result stores them in mixed case. @Override public boolean supportsMixedCaseIdentifiers() throws SQLException { checkClosed(); return false; // Note: Proc names are sensitive, but not tables/columns! } // Retrieves whether this database treats mixed case quoted SQL identifiers as case sensitive and as a result stores them in mixed case. @Override public boolean supportsMixedCaseQuotedIdentifiers() throws SQLException { checkClosed(); return false; // Note: Proc names are sensitive, but not tables/columns! } // Retrieves whether it is possible to have multiple ResultSet objects returned from a CallableStatement object simultaneously. @Override public boolean supportsMultipleOpenResults() throws SQLException { checkClosed(); return true; } // Retrieves whether this database supports getting multiple ResultSet objects from a single call to the method execute. @Override public boolean supportsMultipleResultSets() throws SQLException { checkClosed(); return true; } // Retrieves whether this database allows having multiple transactions open at once (on different connections) throws SQLException. @Override public boolean supportsMultipleTransactions() throws SQLException { checkClosed(); return false; } // Retrieves whether this database supports named parameters to callable statements. @Override public boolean supportsNamedParameters() throws SQLException { checkClosed(); return false; } // Retrieves whether columns in this database may be defined as non-nullable. @Override public boolean supportsNonNullableColumns() throws SQLException { checkClosed(); return true; } // Retrieves whether this database supports keeping cursors open across commits. @Override public boolean supportsOpenCursorsAcrossCommit() throws SQLException { checkClosed(); return false; } // Retrieves whether this database supports keeping cursors open across rollbacks. @Override public boolean supportsOpenCursorsAcrossRollback() throws SQLException { checkClosed(); return false; } // Retrieves whether this database supports keeping statements open across commits. @Override public boolean supportsOpenStatementsAcrossCommit() throws SQLException { checkClosed(); return true; } // Retrieves whether this database supports keeping statements open across rollbacks. @Override public boolean supportsOpenStatementsAcrossRollback() throws SQLException { checkClosed(); return true; } // Retrieves whether this database supports using a column that is not in the SELECT statement in an ORDER BY clause. @Override public boolean supportsOrderByUnrelated() throws SQLException { checkClosed(); return true; } // Retrieves whether this database supports some form of outer join. @Override public boolean supportsOuterJoins() throws SQLException { checkClosed(); return true; } // Retrieves whether this database supports positioned DELETE statements. @Override public boolean supportsPositionedDelete() throws SQLException { checkClosed(); return false; } // Retrieves whether this database supports positioned UPDATE statements. @Override public boolean supportsPositionedUpdate() throws SQLException { checkClosed(); return false; } // Retrieves whether this database supports the given concurrency type in combination with the given result set type. @Override public boolean supportsResultSetConcurrency(int type, int concurrency) throws SQLException { checkClosed(); if (type == ResultSet.TYPE_SCROLL_INSENSITIVE && concurrency == ResultSet.CONCUR_READ_ONLY) return true; return false; } // Retrieves whether this database supports the given result set holdability. @Override public boolean supportsResultSetHoldability(int holdability) throws SQLException { checkClosed(); return false; } // Retrieves whether this database supports the given result set type. @Override public boolean supportsResultSetType(int type) throws SQLException { checkClosed(); if (type == ResultSet.TYPE_SCROLL_INSENSITIVE) return true; return false; } // Retrieves whether this database supports savepoints. @Override public boolean supportsSavepoints() throws SQLException { checkClosed(); return false; } // Retrieves whether a schema name can be used in a data manipulation statement. @Override public boolean supportsSchemasInDataManipulation() throws SQLException { checkClosed(); return false; } // Retrieves whether a schema name can be used in an index definition statement. @Override public boolean supportsSchemasInIndexDefinitions() throws SQLException { checkClosed(); return false; } // Retrieves whether a schema name can be used in a privilege definition statement. @Override public boolean supportsSchemasInPrivilegeDefinitions() throws SQLException { checkClosed(); return false; } // Retrieves whether a schema name can be used in a procedure call statement. @Override public boolean supportsSchemasInProcedureCalls() throws SQLException { checkClosed(); return false; } // Retrieves whether a schema name can be used in a table definition statement. @Override public boolean supportsSchemasInTableDefinitions() throws SQLException { checkClosed(); return false; } // Retrieves whether this database supports SELECT FOR UPDATE statements. @Override public boolean supportsSelectForUpdate() throws SQLException { checkClosed(); return false; } // Retrieves whether this database supports statement pooling. @Override public boolean supportsStatementPooling() throws SQLException { checkClosed(); return false; } // Retrieves whether this database supports invoking user-defined or vendor functions using the stored procedure escape syntax. @Override public boolean supportsStoredFunctionsUsingCallSyntax() throws SQLException { checkClosed(); return false; } // Retrieves whether this database supports stored procedure calls that use the stored procedure escape syntax. @Override public boolean supportsStoredProcedures() throws SQLException { checkClosed(); return true; } // Retrieves whether this database supports subqueries in comparison expressions. @Override public boolean supportsSubqueriesInComparisons() throws SQLException { checkClosed(); return false; } // Retrieves whether this database supports subqueries in EXISTS expressions. @Override public boolean supportsSubqueriesInExists() throws SQLException { checkClosed(); return false; } // Retrieves whether this database supports subqueries in IN expressions. @Override public boolean supportsSubqueriesInIns() throws SQLException { checkClosed(); return false; } // Retrieves whether this database supports subqueries in quantified expressions. @Override public boolean supportsSubqueriesInQuantifieds() throws SQLException { checkClosed(); return false; } // Retrieves whether this database supports table correlation names. @Override public boolean supportsTableCorrelationNames() throws SQLException { checkClosed(); return true; } // Retrieves whether this database supports the given transaction isolation level. @Override public boolean supportsTransactionIsolationLevel(int level) throws SQLException { checkClosed(); if (level == Connection.TRANSACTION_SERIALIZABLE) return true; return false; } // Retrieves whether this database supports transactions. @Override public boolean supportsTransactions() throws SQLException { checkClosed(); return false; } // Retrieves whether this database supports SQL UNION. @Override public boolean supportsUnion() throws SQLException { checkClosed(); return false; } // Retrieves whether this database supports SQL UNION ALL. @Override public boolean supportsUnionAll() throws SQLException { checkClosed(); return false; } // Retrieves whether or not a visible row update can be detected by calling the method ResultSet.rowUpdated. @Override public boolean updatesAreDetected(int type) throws SQLException { checkClosed(); return false; } // Retrieves whether this database uses a file for each table. @Override public boolean usesLocalFilePerTable() throws SQLException { checkClosed(); return false; } // Retrieves whether this database stores tables in a local file. @Override public boolean usesLocalFiles() throws SQLException { checkClosed(); return false; } // Returns true if this either implements the interface argument or is directly or indirectly a wrapper for an object that does. @Override public boolean isWrapperFor(Class<?> iface) throws SQLException { checkClosed(); return iface.isInstance(this); } // Returns an object that implements the given interface to allow access to non-standard methods, or standard methods not exposed by the proxy. @Override public <T> T unwrap(Class<T> iface) throws SQLException { checkClosed(); try { return iface.cast(this); } catch (ClassCastException cce) { throw SQLError.get(SQLError.ILLEGAL_ARGUMENT, iface.toString()); } } @Override public ResultSet getPseudoColumns(String catalog, String schemaPattern, String tableNamePattern, String columnNamePattern) throws SQLException { checkClosed(); throw SQLError.noSupport(); } @Override public boolean generatedKeyAlwaysReturned() throws SQLException { throw SQLError.noSupport(); } }
agpl-3.0
repos-bitcoin/thundernetwork
thunder-client/src/main/java/network/thunder/client/wallet/TransactionStorage.java
6267
/* * ThunderNetwork - Server Client Architecture to send Off-Chain Bitcoin Payments * Copyright (C) 2015 Mats Jerratsch <matsjj@gmail.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 network.thunder.client.wallet; import java.nio.channels.NotYetConnectedException; import java.sql.Connection; import java.sql.SQLException; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Timer; import network.thunder.client.api.ThunderContext; import network.thunder.client.database.MySQLConnection; import network.thunder.client.database.objects.Channel; import network.thunder.client.database.objects.Output; import network.thunder.client.etc.Constants; import org.bitcoinj.core.Coin; import org.bitcoinj.core.ECKey; import org.bitcoinj.core.Peer; import org.bitcoinj.core.PeerGroup; import org.bitcoinj.core.Transaction; import org.bitcoinj.core.TransactionConfidence; import org.bitcoinj.core.TransactionConfidence.ConfidenceType; import org.bitcoinj.core.TransactionInput; import org.bitcoinj.core.TransactionOutput; import org.bitcoinj.core.Wallet; import org.bitcoinj.core.WalletEventListener; import org.bitcoinj.script.Script; public class TransactionStorage implements WalletEventListener { Connection conn; PeerGroup peerGroup; private static boolean first = true; ArrayList<Channel> openingTransactions = new ArrayList<Channel>(); ArrayList<Channel> channelTransactions = new ArrayList<Channel>(); HashMap<Integer, ArrayList<TransactionTimerTask>> additionalTransactionList = new HashMap<Integer, ArrayList<TransactionTimerTask>>(); HashMap<Integer, TransactionTimerTask> refundTransactionList = new HashMap<Integer, TransactionTimerTask>(); HashMap<Integer, TransactionTimerTask> channelTransactionList = new HashMap<Integer, TransactionTimerTask>(); Timer timer; ArrayList<Output> outputList = new ArrayList<>(); private TransactionStorage() {} public static TransactionStorage initialize(Connection conn, ArrayList<Output> outputList) throws SQLException { TransactionStorage storage = new TransactionStorage(); storage.conn = conn; storage.outputList = outputList; storage.channelTransactions = MySQLConnection.getChannelTransactions(conn); storage.openingTransactions = MySQLConnection.getOpeningTransactions(conn); return storage; } public void rebroadcastOpeningTransactions(Peer peer) throws NotYetConnectedException, SQLException { for(Channel c : openingTransactions) { peer.sendMessage(c.getOpeningTx()); } } public void addOpenedChannel(Channel channel) { openingTransactions.add(channel); } private void addFinishedChannel(Channel channel) throws SQLException { channelTransactions.add(channel); int i=0; for(Channel c : openingTransactions) { if(c.getPubKeyClient().equals(channel.getPubKeyClient())) { openingTransactions.remove(i); c.setReady(true); c.setEstablishPhase(0); MySQLConnection.updateChannel(conn, channel); return; } i++; } } public void updateOutputs(Wallet wallet, boolean forceUpdate) { boolean update = forceUpdate; for (TransactionOutput o : wallet.calculateAllSpendCandidates()) { if(o.getParentTransaction().getConfidence().getDepthInBlocks() < 10) { update = true; } } if(!update && !first) return; first = false; outputList.clear(); for (TransactionOutput o : wallet.calculateAllSpendCandidates()) { if(o.getParentTransaction().getConfidence().getDepthInBlocks() >= Constants.MIN_CONFIRMATION_TIME) { outputList.add(new Output(o, wallet)); } } } public void onTransaction(Transaction transaction) throws SQLException { for(Channel c : openingTransactions) { if(transaction.getHashAsString().equals(c.getOpeningTxHash())) { TransactionConfidence confidence = transaction.getConfidence(); if(confidence.getConfidenceType() == ConfidenceType.DEAD) { //TODO: Remove this transaction and the channel, somehow it got overwritten.. } if(confidence.getDepthInBlocks() >= Constants.MIN_CONFIRMATION_TIME_FOR_CHANNEL) { c.setOpeningTx(transaction); addFinishedChannel(c); return; } } } boolean channelOutput = false; for(TransactionInput input : transaction.getInputs()) { if(input.getOutpoint().getIndex() == 0) { for(Channel c : channelTransactions) { if(c.getChannelTxServer() != null) { if(input.getOutpoint().getHash().toString().equals(c.getChannelTxServer().getHashAsString())) { //TODO: Somehow the channel got closed, find out how (correctly?) and act accordingly.. } } } } } } @Override public void onKeysAdded(List<ECKey> arg0) { // TODO Auto-generated method stub } @Override public void onCoinsReceived(Wallet arg0, Transaction arg1, Coin arg2, Coin arg3) { // TODO Auto-generated method stub } @Override public void onCoinsSent(Wallet arg0, Transaction arg1, Coin arg2, Coin arg3) { // TODO Auto-generated method stub } @Override public void onReorganize(Wallet arg0) { // TODO Auto-generated method stub } @Override public void onScriptsChanged(Wallet arg0, List<Script> arg1, boolean arg2) { // TODO Auto-generated method stub } @Override public void onTransactionConfidenceChanged(Wallet arg0, Transaction arg1) { try { onTransaction(arg1); } catch (SQLException e) { // TODO Auto-generated catch block e.printStackTrace(); } } @Override public void onWalletChanged(Wallet arg0) { // TODO Auto-generated method stub updateOutputs(arg0, false); } }
agpl-3.0
ebonnet/Silverpeas-Core
core-war/src/main/java/org/silverpeas/web/joborganization/control/JobOrganizationPeasSessionController.java
15514
/* * Copyright (C) 2000 - 2016 Silverpeas * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * As a special exception to the terms and conditions of version 3.0 of * the GPL, you may redistribute this Program in connection with Free/Libre * Open Source Software ("FLOSS") applications as described in Silverpeas's * FLOSS exception. You should have received a copy of the text describing * the FLOSS exception, and it is also available here: * "http://www.silverpeas.org/docs/core/legal/floss_exception.html" * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.silverpeas.web.joborganization.control; import org.silverpeas.core.admin.component.model.WAComponent; import org.silverpeas.core.util.URLUtil; import org.silverpeas.web.joborganization.JobOrganizationPeasException; import org.silverpeas.core.web.mvc.controller.AbstractComponentSessionController; import org.silverpeas.core.web.mvc.controller.ComponentContext; import org.silverpeas.core.web.mvc.controller.MainSessionController; import org.silverpeas.core.web.selection.Selection; import org.silverpeas.core.silvertrace.SilverTrace; import org.silverpeas.core.admin.service.AdminController; import org.silverpeas.core.admin.service.AdminException; import org.silverpeas.core.admin.component.model.ComponentInst; import org.silverpeas.core.admin.user.model.Group; import org.silverpeas.core.admin.user.model.ProfileInst; import org.silverpeas.core.admin.service.RightAssignationContext; import org.silverpeas.core.admin.space.SpaceInstLight; import org.silverpeas.core.admin.user.model.UserFull; import org.silverpeas.core.util.Pair; import org.silverpeas.core.util.ServiceProvider; import org.silverpeas.core.util.StringUtil; import org.silverpeas.core.exception.SilverpeasException; import java.util.ArrayList; import java.util.List; import java.util.Map; /** * Class declaration * @author Thierry Leroi */ public class JobOrganizationPeasSessionController extends AbstractComponentSessionController { // View Group or User private String currentUserId = null; private String currentGroupId = null; private AdminController myAdminController = ServiceProvider.getService(AdminController.class); private UserFull currentUser = null; private Group currentGroup = null; private String[][] currentGroups = null; private String[] currentSpaces = null; private List<String[]> currentProfiles = null; private Map<String, WAComponent> componentOfficialNames = getAdminController().getAllComponents(); public static final String REPLACE_RIGHTS = "1"; public static final String ADD_RIGHTS = "2"; /** * Standard Session Controller Constructeur * @param mainSessionCtrl The user's profile * @param componentContext The component's profile * @see */ public JobOrganizationPeasSessionController( MainSessionController mainSessionCtrl, ComponentContext componentContext) { super( mainSessionCtrl, componentContext, "org.silverpeas.jobOrganizationPeas.multilang.jobOrganizationPeasBundle", "org.silverpeas.jobOrganizationPeas.settings.jobOrganizationPeasIcons", "org.silverpeas.jobOrganizationPeas.settings.jobOrganizationPeasSettings"); setComponentRootName(URLUtil.CMP_JOBORGANIZATIONPEAS); } public boolean isRightCopyReplaceActivated() { return getSettings().getBoolean("admin.profile.rights.copyReplace.activated", false); } // #################### // View User or Group private void resetCurrentArrays() { currentGroups = null; currentUser = null; currentGroup = null; currentSpaces = null; currentProfiles = null; } public AdminController getAdminController() { return myAdminController; } public void setCurrentUserId(String userId) { if (currentUserId != null && !currentUserId.equals(userId)) { resetCurrentUser(); } currentUserId = userId; if (currentUserId != null) { resetCurrentGroup(); } } private void resetCurrentUser() { currentUserId = null; resetCurrentArrays(); } public void setCurrentGroupId(String groupId) { if (currentGroupId != null && !currentGroupId.equals(groupId)) { resetCurrentGroup(); } currentGroupId = groupId; if (currentGroupId != null) { resetCurrentUser(); } } public void resetCurrentGroup() { currentGroupId = null; resetCurrentArrays(); } public String getCurrentUserId() { return currentUserId; } public String getCurrentGroupId() { return currentGroupId; } /** * @return an array of (id, name, number of users, description). */ public String[][] getCurrentUserGroups() { if (currentGroups == null) { if (getCurrentUserId() == null) { return null; } String[] groupIds = getAdminController().getDirectGroupsIdsOfUser( getCurrentUserId()); if (groupIds == null || groupIds.length == 0) { return null; } currentGroups = new String[groupIds.length][4]; for (int iGrp = 0; iGrp < groupIds.length; iGrp++) { Group theCurrentGroup = getOrganisationController().getGroup(groupIds[iGrp]); currentGroups[iGrp][0] = theCurrentGroup.getId(); currentGroups[iGrp][1] = theCurrentGroup.getName(); currentGroups[iGrp][2] = String.valueOf(theCurrentGroup.getUserIds().length); currentGroups[iGrp][3] = theCurrentGroup.getDescription(); } } return currentGroups; } /** * @return UserFull */ public UserFull getCurrentUser() { if (currentUser == null) { if (getCurrentUserId() == null) { return null; } currentUser = getAdminController().getUserFull(getCurrentUserId()); } return currentUser; } /** * @return Group */ public Group getCurrentGroup() { if (currentGroup == null) { if (getCurrentGroupId() == null) { return null; } currentGroup = getAdminController().getGroupById(getCurrentGroupId()); } return currentGroup; } /** * @return String */ public String getCurrentSuperGroupName() { String currentSuperGroupName = "-"; if (currentGroup != null) { String parentId = currentGroup.getSuperGroupId(); if (StringUtil.isDefined(parentId)) { currentSuperGroupName = getAdminController().getGroupName(parentId); } } return currentSuperGroupName; } /** * @return array of space names (manageable by the current group or user) */ public String[] getCurrentSpaces() { if (currentSpaces == null) { String[] spaceIds = null; if (getCurrentGroupId() != null) { spaceIds = getAdminController().getGroupManageableSpaceIds( getCurrentGroupId()); } if (getCurrentUserId() != null) { spaceIds = getAdminController().getUserManageableSpaceIds( getCurrentUserId()); } if (spaceIds == null) { return null; } String[] spaceIdsBIS = new String[spaceIds.length]; for (int j = 0; j < spaceIds.length; j++) { if ((spaceIds[j] != null) && (spaceIds[j].startsWith("WA"))) { spaceIdsBIS[j] = spaceIds[j]; } else { spaceIdsBIS[j] = "WA" + spaceIds[j]; } } currentSpaces = getAdminController().getSpaceNames(spaceIdsBIS); } return currentSpaces; } /** * @return list of (array[space name, component id, component label, component name, profile * name]) */ public List<String[]> getCurrentProfiles() { if (currentProfiles == null) { List<String> distinctProfiles = new ArrayList<String>(); String[] profileIds = null; if (getCurrentGroupId() != null) { profileIds = getAdminController().getProfileIdsOfGroup( getCurrentGroupId()); } if (getCurrentUserId() != null) { profileIds = getAdminController().getProfileIds(getCurrentUserId()); } if (profileIds == null) { return null; } currentProfiles = new ArrayList<String[]>(); ProfileInst currentProfile; ComponentInst currentComponent; List<String> spaceIds = new ArrayList<String>(); for (String profileId : profileIds) { currentProfile = getAdminController().getProfileInst(profileId); currentComponent = getAdminController().getComponentInst( currentProfile.getComponentFatherId()); String spaceId = currentComponent.getDomainFatherId(); SpaceInstLight spaceInst = getAdminController().getSpaceInstLight(spaceId); if (currentComponent.getStatus() == null && !spaceInst.isPersonalSpace()) {// on n'affiche // pas les // composants de // l'espace // personnel String dProfile = currentComponent.getId() + currentProfile.getName(); if (!distinctProfiles.contains(dProfile)) { String[] profile2Display = new String[6]; profile2Display[1] = currentComponent.getId(); profile2Display[2] = currentComponent.getName(); profile2Display[3] = currentComponent.getLabel(); profile2Display[4] = getComponentOfficialName(currentComponent.getName()); profile2Display[5] = currentProfile.getLabel(); if (!StringUtil.isDefined(profile2Display[5])) { profile2Display[5] = getAdminController().getProfileLabelfromName( currentComponent.getName(), currentProfile.getName(), getLanguage()); } currentProfiles.add(profile2Display); spaceIds.add(spaceId); distinctProfiles.add(dProfile); } } } String[] spaceNames = getAdminController().getSpaceNames(spaceIds.toArray(new String[spaceIds. size()])); for (int iProfile = 0; iProfile < currentProfiles.size(); iProfile++) { String[] profile2Display = currentProfiles.get(iProfile); profile2Display[0] = spaceNames[iProfile]; } } return currentProfiles; } /** * @return the official component name given the internal name */ private String getComponentOfficialName(String internalName) { try { WAComponent component = componentOfficialNames.get(internalName); if (component != null) { return component.getLabel().get(getLanguage()); } return internalName; } catch (Exception e) { SilverTrace.error("jobOrganizationPeas", "JobOrganizationPeasSessionController.getComponentOfficialName", "root.MSG_GEN_PARAM_VALUE", "!!!!! ERROR getting official name=" + internalName, e); return internalName; } } /* * UserPanel initialization : a user or (exclusive) a group */ public String initSelectionUserOrGroup() { String m_context = URLUtil.getApplicationURL(); String hostSpaceName = getString("JOP.pseudoSpace"); String cancelUrl = m_context + Selection.getSelectionURL(Selection.TYPE_USERS_GROUPS); Pair<String, String> hostComponentName = new Pair<>(getString("JOP.pseudoPeas"), cancelUrl); String hostUrl = m_context + getComponentUrl() + "ViewUserOrGroup"; Selection sel = getSelection(); sel.resetAll(); sel.setFilterOnDeactivatedState(false); sel.setHostSpaceName(hostSpaceName); sel.setHostComponentName(hostComponentName); sel.setHostPath(null); sel.setGoBackURL(hostUrl); sel.setCancelURL(cancelUrl); sel.setMultiSelect(false); sel.setPopupMode(false); sel.setFirstPage(Selection.FIRST_PAGE_BROWSE); return Selection.getSelectionURL(Selection.TYPE_USERS_GROUPS); } /* * Back from UserPanel */ public void backSelectionUserOrGroup() { Selection sel = getSelection(); String id; id = sel.getFirstSelectedElement(); setCurrentUserId(id); id = sel.getFirstSelectedSet(); setCurrentGroupId(id); } /* * UserPanel initialization : a user or (exclusive) a group */ public String initSelectionRightsUserOrGroup() { String hostSpaceName = getString("JOP.pseudoSpace"); String cancelUrl = ""; Pair<String, String> hostComponentName = new Pair<>(getString("JOP.pseudoPeas"), cancelUrl); String hostUrl = ""; Selection sel = getSelection(); sel.resetAll(); sel.setFilterOnDeactivatedState(false); sel.setHostSpaceName(hostSpaceName); sel.setHostComponentName(hostComponentName); sel.setHostPath(null); sel.setGoBackURL(hostUrl); sel.setCancelURL(cancelUrl); sel.setHtmlFormName("rightsForm"); sel.setHtmlFormElementName("sourceRightsName"); sel.setHtmlFormElementId("sourceRightsId"); sel.setHtmlFormElementType("sourceRightsType"); sel.setMultiSelect(false); sel.setPopupMode(true); sel.setFirstPage(Selection.FIRST_PAGE_BROWSE); return Selection.getSelectionURL(Selection.TYPE_USERS_GROUPS); } /* * Assign rights to current selected user or group */ public void assignRights(String choiceAssignRights, String sourceRightsId, String sourceRightsType, boolean nodeAssignRights) throws JobOrganizationPeasException { try { if (JobOrganizationPeasSessionController.REPLACE_RIGHTS.equals(choiceAssignRights) || JobOrganizationPeasSessionController.ADD_RIGHTS.equals(choiceAssignRights)) { RightAssignationContext.MODE operationMode = JobOrganizationPeasSessionController.REPLACE_RIGHTS.equals(choiceAssignRights) ? RightAssignationContext.MODE.REPLACE : RightAssignationContext.MODE.COPY; if (Selection.TYPE_SELECTED_ELEMENT.equals(sourceRightsType)) { if (getCurrentUserId() != null) { getAdminController() .assignRightsFromUserToUser(operationMode, sourceRightsId, getCurrentUserId(), nodeAssignRights, getUserId()); } else if (getCurrentGroupId() != null) { getAdminController() .assignRightsFromUserToGroup(operationMode, sourceRightsId, getCurrentGroupId(), nodeAssignRights, getUserId()); } } else if (Selection.TYPE_SELECTED_SET.equals(sourceRightsType)) { if (getCurrentUserId() != null) { getAdminController() .assignRightsFromGroupToUser(operationMode, sourceRightsId, getCurrentUserId(), nodeAssignRights, getUserId()); } else if (getCurrentGroupId() != null) { getAdminController() .assignRightsFromGroupToGroup(operationMode, sourceRightsId, getCurrentGroupId(), nodeAssignRights, getUserId()); } } //force to refresh currentProfiles = null; } } catch (AdminException e) { throw new JobOrganizationPeasException("JobOrganizationPeasSessionController.assignRights", SilverpeasException.ERROR, "", e); } } }
agpl-3.0
NicolasEYSSERIC/Silverpeas-Core
lib-core/src/test/java/org/silverpeas/quota/model/QuotaTest.java
3444
package org.silverpeas.quota.model; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import java.math.BigDecimal; import org.junit.Test; import org.silverpeas.quota.contant.QuotaLoad; import org.silverpeas.quota.contant.QuotaType; import org.silverpeas.quota.exception.QuotaException; import com.stratelia.webactiv.util.exception.SilverpeasException; public class QuotaTest { @Test public void testValidate() { Quota quota = initializeQuota(); assertValidate(quota, true); quota = initializeQuota(); quota.setId(null); assertValidate(quota, true); quota = initializeQuota(); quota.setSaveDate(null); assertValidate(quota, true); quota = initializeQuota(); quota.setCount(-100); assertValidate(quota, true); quota = initializeQuota(); quota.setType(null); assertValidate(quota, false); quota = initializeQuota(); quota.setResourceId(null); assertValidate(quota, false); quota = initializeQuota(); quota.setResourceId(""); assertValidate(quota, false); quota = initializeQuota(); quota.setResourceId(" "); assertValidate(quota, false); quota = initializeQuota(); quota.setMinCount(-1); assertValidate(quota, false); quota = initializeQuota(); quota.setMaxCount(-1); assertValidate(quota, false); quota = initializeQuota(); quota.setMinCount(2); quota.setMaxCount(1); assertValidate(quota, false); } private <T extends SilverpeasException> void assertValidate(final Quota quota, final boolean isValid) { boolean isException = false; try { quota.validate(); } catch (final QuotaException qe) { isException = true; } assertThat(isException, is(!isValid)); } @Test public void testGetLoad() { Quota quota = initializeQuota(); quota.setMaxCount(0); assertThat(quota.getLoad(), is(QuotaLoad.UNLIMITED)); quota = initializeQuota(); quota.setCount(0); assertThat(quota.getLoad(), is(QuotaLoad.EMPTY)); quota = initializeQuota(); quota.setCount(1); assertThat(quota.getLoad(), is(QuotaLoad.NOT_ENOUGH)); quota = initializeQuota(); quota.setCount(quota.getMaxCount() - 1); assertThat(quota.getLoad(), is(QuotaLoad.NOT_FULL)); quota = initializeQuota(); quota.setCount(quota.getMaxCount()); assertThat(quota.getLoad(), is(QuotaLoad.FULL)); quota = initializeQuota(); quota.setMinCount(0); quota.setCount(0); assertThat(quota.getLoad(), is(QuotaLoad.EMPTY)); quota = initializeQuota(); quota.setCount(1000); assertThat(quota.getLoad(), is(QuotaLoad.OUT_OF_BOUNDS)); } @Test public void testGetLoadRate() { Quota quota = initializeQuota(); BigDecimal loadRate = quota.getLoadRate(); assertThat(loadRate, is(new BigDecimal("0.60869565217391304348"))); } @Test public void testGetLoadPercentage() { Quota quota = initializeQuota(); BigDecimal loadPercentage = quota.getLoadPercentage(); assertThat(loadPercentage, is(new BigDecimal("60.87"))); } private Quota initializeQuota() { final Quota quota = new Quota(); quota.setId(26L); quota.setType(QuotaType.USERS_IN_DOMAIN); quota.setResourceId("26"); quota.setMinCount(10); quota.setMaxCount(23); quota.setCount(14); quota.setSaveDate(java.sql.Date.valueOf("2012-01-01")); return quota; } }
agpl-3.0
acontes/scheduling_portal
src/org/ow2/proactive_grid_cloud_portal/rm/client/RMService.java
9162
/* * ################################################################ * * 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): * * ################################################################ * $$PROACTIVE_INITIAL_DEV$$ */ package org.ow2.proactive_grid_cloud_portal.rm.client; import java.util.List; import java.util.Map; import java.util.Set; import org.ow2.proactive_grid_cloud_portal.common.shared.RestServerException; import org.ow2.proactive_grid_cloud_portal.common.shared.ServiceException; import com.google.gwt.user.client.rpc.RemoteService; import com.google.gwt.user.client.rpc.RemoteServiceRelativePath; /** * Client side stub for server calls * * * * @author mschnoor * */ @RemoteServiceRelativePath("rm") public interface RMService extends RemoteService { /** * Default configuration is read by the server * @return a list of configuration properties read by * the server used to configure the client */ Map<String, String> getProperties(); /** * Logout the current session * @param sessionId id of the current session * @throws ServiceException */ void logout(String sessionId) throws ServiceException; /** * Limited info about the current RM State : freeNodesNumber, totalAliveNodesNumber, totalNodesNumber * @param sessionId the current session * @return freeNodesNumber, totalAliveNodesNumber, totalNodesNumber in a JSON string * @throws RestServerException * @throws ServiceException */ String getState(String sessionId) throws RestServerException, ServiceException; /** * Detailed info about the nodes currently held by the RM * presented as two arrays of nodes and nodesources referencing each others * @param sessionId current session * @return a JSON object containing two arrays named nodesList and nodeSources, that contain all info about current * nodes and nodesources in the RM * @throws RestServerException * @throws ServiceException */ String getMonitoring(String sessionId) throws RestServerException, ServiceException; /** * List of all supported Infrastructure Managers, and their parameters * @param sessionId current session * @return a JSON array containing all supported infrastructures * @throws ServiceException */ String getInfrastructures(String sessionId) throws RestServerException, ServiceException; /** * List of all supported Policies, and their parameters * @param sessionId current session * @return a JSON array containing all supported policies * @throws RestServerException * @throws ServiceException */ String getPolicies(String sessionId) throws RestServerException, ServiceException; /** * Creates a NodeSource * @param sessionId current session * @param nodeSourceName name of the new NS * @param infrastructureType infrastructure manager full class name * @param infrastructureParameters IM String parameters, null value for files * @param infrastructureFileParamaters file parameters * @param policyType policy full class name * @param policyParameters String parameters, null value for files * @param policyFileParameters file parameters * @throws RestServerException * @throws ServiceException */ String createNodeSource(String sessionId, String nodeSourceName, String infrastructureType, String[] infrastructureParameters, String[] infrastructureFileParameters, String policyType, String[] policyParameters, String[] policyFileParameters) throws RestServerException, ServiceException; /** * lock a set of nodes * @param sessionId current session * @param nodeUrls nodes to lock * @return true upon success * @throws RestServerException * @throws ServiceException */ String lockNodes(String sessionId, Set<String> nodeUrls) throws RestServerException, ServiceException; /** * Unlock a set of nodes * @param sessionId current session * @param nodeUrls nodes to unlock * @return true upon success * @throws RestServerException * @throws ServiceException */ String unlockNodes(String sessionId, Set<String> nodeUrls) throws RestServerException, ServiceException; /** * Release a node * @param sessionId currend session * @param url complete unique url of the node * @return true when ok * @throws RestServerException * @throws ServiceException */ String releaseNode(String sessionId, String url) throws RestServerException, ServiceException; /** * Remove a node * @param sessionId currend session * @param url complete unique url of the node * @param force do not wait for task completion * @return true when ok * @throws RestServerException * @throws ServiceException */ String removeNode(String sessionId, String url, boolean force) throws RestServerException, ServiceException; /** * Remove a node * @param sessionId currend session * @param name complete unique name of the nodesource * @param preempt don't wait for tasks if true * @return true when ok * @throws RestServerException * @throws ServiceException */ String removeNodesource(String sessionId, String name, boolean preempt) throws RestServerException, ServiceException; /** * @return version string of the REST api */ String getVersion() throws RestServerException, ServiceException; /** * Query a list of attributes from a specific RM MBean * @param sessionId current session * @param name of the JMX management bean * @param attrs attributes to fetch in the specified MBean * @return JSON object with attribute names as key * @throws RestServerException * @throws ServiceException */ String getMBeanInfo(String sessionId, String name, List<String> attrs) throws RestServerException, ServiceException; /** * Retrieves attributes of the specified mbean. * * @param sessionId current session * @param name of mbean * @param nodeJmxUrl mbean server url * @param attrs set of mbean attributes * * @return mbean attributes values */ String getNodeMBeanInfo(String sessionId, String nodeJmxUrl, String objectName, List<String> attrs) throws RestServerException, ServiceException; /** * Retrieves attributes of the specified mbeans. * * @param sessionId current session * @param objectNames mbean names (@see ObjectName format) * @param nodeJmxUrl mbean server url * @param attrs set of mbean attributes * * @return mbean attributes values */ String getNodeMBeansInfo(String sessionId, String nodeJmxUrl, String objectNames, List<String> attrs) throws RestServerException, ServiceException; /** * Statistic history for the following values:<pre> * { "BusyNodesCount", * "FreeNodesCount", * "DownNodesCount", * "AvailableNodesCount", * "AverageActivity" }</pre> * * @param sessionId current session * @param range a String of 5 chars, one for each stat history source, indicating the time range to fetch * for each source. Each char can be:<ul> * <li>'a' 1 minute * <li>'m' 10 minutes * <li>'h' 1 hour * <li>'H' 8 hours * <li>'d' 1 day * <li>'w' 1 week * <li>'M' 1 month * <li>'y' 1 year</ul> * @return will contain the server response, a JSON object containing a key for each source */ String getStatHistory(String sessionId, String range) throws RestServerException, ServiceException; }
agpl-3.0
lp0/cursus-core
src/main/java/uk/uuid/cursus/db/data/Class.java
2928
/* cursus - Race series management program Copyright 2011, 2013-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.cursus.db.data; import java.util.HashSet; import java.util.Set; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.JoinColumn; import javax.persistence.ManyToMany; import javax.persistence.ManyToOne; import javax.persistence.Table; import javax.persistence.UniqueConstraint; import uk.uuid.cursus.db.Constants; import com.google.common.collect.ComparisonChain; /** * Pilot class groupings within series (to segregate race scores) */ @Entity(name = "class") @Table(uniqueConstraints = { @UniqueConstraint(columnNames = { "series_id", "name" }) }) public final class Class extends AbstractEntity implements Comparable<Class>, NamedEntity { private String name; Class() { } public Class(Series series) { this(series, "", ""); //$NON-NLS-1$ //$NON-NLS-2$ } public Class(Series series, String name) { this(series, name, ""); //$NON-NLS-1$ } public Class(Series series, String name, String description) { setSeries(series); setName(name); setDescription(description); } @Column(nullable = false, length = Constants.MAX_STRING_LEN) public String getName() { return name; } public void setName(String name) { this.name = name; } private String description; @Column(nullable = false, length = Constants.MAX_STRING_LEN) public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } private Series series; @ManyToOne(optional = false) @JoinColumn(name = "series_id", nullable = false) public Series getSeries() { return series; } public void setSeries(Series series) { this.series = series; } private Set<Pilot> pilots = new HashSet<Pilot>(); @ManyToMany(mappedBy = "classes") public Set<Pilot> getPilots() { return pilots; } public void setPilots(Set<Pilot> pilots) { this.pilots = pilots; } @Override public String toString() { return getName().length() > 0 ? getName() : "[#" + getId() + "]"; //$NON-NLS-1$ //$NON-NLS-2$; } @Override public int compareTo(Class o) { return ComparisonChain.start().compare(getSeries(), o.getSeries()).compare(getName(), o.getName()).result(); } }
agpl-3.0
simplyianm/SuperPlots
src/main/java/com/simplyian/superplots/event/SPEventFactory.java
1881
package com.simplyian.superplots.event; import org.bukkit.entity.Player; import org.bukkit.event.Event; import org.bukkit.event.block.BlockBreakEvent; import org.bukkit.event.block.BlockPlaceEvent; import org.bukkit.event.player.PlayerInteractEvent; import com.simplyian.superplots.SuperPlotsPlugin; import com.simplyian.superplots.plot.Plot; public class SPEventFactory { private final SuperPlotsPlugin main; public SPEventFactory(SuperPlotsPlugin main) { this.main = main; } public PlotBuildEvent callPlotBuildEvent(BlockBreakEvent event, Plot plot) { PlotBuildEvent ret = new PlotBuildEvent(plot, false, event.getPlayer(), event.getBlock()); return callEvent(ret); } public PlotBuildEvent callPlotBuildEvent(BlockPlaceEvent event, Plot plot) { PlotBuildEvent ret = new PlotBuildEvent(plot, false, event.getPlayer(), event.getBlock()); return callEvent(ret); } public PlotCreateEvent callPlotCreateEvent(Plot plot) { return callEvent(new PlotCreateEvent(plot)); } public PlotDisbandEvent callPlotDisbandEvent(Plot plot) { return callEvent(new PlotDisbandEvent(plot)); } public PlotEnterEvent callPlotEnterEvent(Player player, Plot plot) { return callEvent(new PlotEnterEvent(player, plot)); } public PlotExitEvent callPlotExitEvent(Player player, Plot plot) { return callEvent(new PlotExitEvent(player, plot)); } public PlotInteractEvent callPlotInteractEvent(PlayerInteractEvent event, Plot plot) { return callEvent(new PlotInteractEvent(event.getPlayer(), event.getClickedBlock(), event.getAction(), plot)); } private <T extends Event> T callEvent(T event) { main.getServer().getPluginManager().callEvent(event); return event; } }
agpl-3.0
projectdanube/blockstore-cli-java
src/main/java/com/danubetech/blockstore/client/BlockstoreClient.java
3994
package com.danubetech.blockstore.client; import java.io.IOException; import org.json.simple.JSONArray; import org.json.simple.JSONObject; /** * Client interface to the Blockstore server. * * @author peacekeeper */ public interface BlockstoreClient { public JSONObject ping() throws IOException; public JSONObject getNameBlockchainRecord(String name) throws IOException; public JSONObject getinfo() throws IOException; public JSONObject preorder(String name, String privatekey, String register_addr) throws IOException; public JSONObject preorderTx(String name, String privatekey, String register_addr) throws IOException; public JSONObject preorderTxSubsidized(String name, String public_key, String register_addr, String subsidy_key) throws IOException; public JSONObject register(String name, String privatekey, String register_addr) throws IOException; public JSONObject registerTx(String name, String privatekey, String register_addr) throws IOException; public JSONObject registerTxSubsidized(String name, String public_key, String register_addr, String subsidy_key) throws IOException; public JSONObject update(String name, String data_hash, String privatekey) throws IOException; public JSONObject updateTx(String name, String data_hash, String privatekey) throws IOException; public JSONObject updateTxSubsidized(String name, String data_hash, String public_key, String subsidy_key) throws IOException; public JSONObject transfer(String name, String address, boolean keepdata, String privatekey) throws IOException; public JSONObject transferTx(String name, String address, boolean keepdata, String privatekey) throws IOException; public JSONObject transferTxSubsidized(String name, String address, boolean keepdata, String public_key, String subsidy_key) throws IOException; public JSONObject renew(String name, String privatekey) throws IOException; public JSONObject renewTx(String name, String privatekey) throws IOException; public JSONObject renewTxSubsidized(String name, String public_key, String subsidy_key) throws IOException; public JSONObject revoke(String name, String privatekey) throws IOException; public JSONObject revokeTx(String name, String privatekey) throws IOException; public JSONObject revokeTxSubsidized(String name, String public_key, String subsidy_key) throws IOException; public JSONObject nameImport(String name, String recipient_address, String update_hash, String privatekey) throws IOException; public JSONObject nameImportTx(String name, String recipient_address, String update_hash, String privatekey) throws IOException; public JSONObject namespacePreorder(String namespace_id, String reveal_addr, String privatekey) throws IOException; public JSONObject namespacePreorderTx(String namespace_id, String reveal_addr, String privatekey) throws IOException; public JSONObject namespaceReveal(String namespace_id, String reveal_addr, String lifetime, String coeff, String base, String bucket_exponents, String nonalpha_discount, String no_vowel_discount, String privatekey) throws IOException; public JSONObject namespaceRevealTx(String namespace_id, String reveal_addr, String lifetime, String coeff, String base, String bucket_exponents, String nonalpha_discount, String no_vowel_discount, String privatekey) throws IOException; public JSONObject namespaceReady(String namespace_id, String privatekey) throws IOException; public JSONObject namespaceReadyTx(String namespace_id, String privatekey) throws IOException; public JSONObject getNameCost(String name) throws IOException; public JSONObject getNamespaceCost(String namespace_id) throws IOException; public JSONObject getNamespaceBlockchainRecord(String namespace_id) throws IOException; public JSONArray getAllNames(Integer offset, Integer count) throws IOException; public JSONArray getNamesInNamespace(String namespace_id, Integer offset, Integer count) throws IOException; public JSONObject getConsensusAt(String block_id) throws IOException; }
agpl-3.0
elki-project/elki
elki-core-math/src/main/java/elki/math/linearalgebra/pca/weightfunctions/InverseProportionalWeight.java
1350
/* * This file is part of ELKI: * Environment for Developing KDD-Applications Supported by Index-Structures * * Copyright (C) 2019 * ELKI Development Team * * 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 elki.math.linearalgebra.pca.weightfunctions; /** * Inverse proportional weight function, scaled using the maximum using: * \( 1 / (1 + \frac{\text{distance}}{\max} ) \) * * @author Erich Schubert * @since 0.2 */ public final class InverseProportionalWeight implements WeightFunction { /** * Get inverse proportional weight. stddev is ignored. */ @Override public double getWeight(double distance, double max, double stddev) { return max <= 0 ? 1 : 1 / (1 + 9 * (distance / max)); } }
agpl-3.0
a-gogo/agogo
AMW_maia_federation/generated-sources/main/java/ch/mobi/xml/service/ch/mobi/maia/amw/maiaamwfederationservice/v1_0/MaiaAmwFederationPortType.java
3059
package ch.mobi.xml.service.ch.mobi.maia.amw.maiaamwfederationservice.v1_0; import ch.mobi.xml.datatype.ch.mobi.maia.amw.maiaamwfederationservicetypes.v1_0.UpdateRequest; import ch.mobi.xml.datatype.ch.mobi.maia.amw.maiaamwfederationservicetypes.v1_0.UpdateResponse; import ch.mobi.xml.datatype.common.commons.v3.CallContext; import javax.jws.WebMethod; import javax.jws.WebParam; import javax.jws.WebResult; import javax.jws.WebService; import javax.xml.bind.annotation.XmlSeeAlso; import javax.xml.ws.RequestWrapper; import javax.xml.ws.ResponseWrapper; /** * This class was generated by the JAX-WS RI. * JAX-WS RI 2.2.8 * Generated source version: 2.2 * */ @WebService(name = "MaiaAmwFederationPortType", targetNamespace = "http://xml.mobi.ch/service/ch/mobi/maia/amw/MaiaAmwFederationService/v1_0") @XmlSeeAlso({ ch.mobi.xml.datatype.ch.mobi.maia.amw.maiaamwfederation.v1_0.ObjectFactory.class, ch.mobi.xml.datatype.ch.mobi.maia.amw.maiaamwfederationservicetypes.v1_0.ObjectFactory.class, ch.mobi.xml.datatype.common.commons.v3.ObjectFactory.class, ch.mobi.xml.service.ch.mobi.maia.amw.v1_0.maiaamwfederationservice.datatype.ObjectFactory.class }) public interface MaiaAmwFederationPortType { /** * * @param update * @param callContext * @param fcOwner * @return * returns ch.mobi.xml.datatype.ch.mobi.maia.amw.maiaamwfederationservicetypes.v1_0.UpdateResponse * @throws ValidationException * @throws TechnicalException * @throws BusinessException */ @WebMethod @WebResult(name = "result", targetNamespace = "") @RequestWrapper(localName = "update", targetNamespace = "http://xml.mobi.ch/service/ch/mobi/maia/amw/v1_0/MaiaAmwFederationService/datatype", className = "ch.mobi.xml.service.ch.mobi.maia.amw.v1_0.maiaamwfederationservice.datatype.Update") @ResponseWrapper(localName = "updateResponse", targetNamespace = "http://xml.mobi.ch/service/ch/mobi/maia/amw/v1_0/MaiaAmwFederationService/datatype", className = "ch.mobi.xml.service.ch.mobi.maia.amw.v1_0.maiaamwfederationservice.datatype.UpdateResponse") public UpdateResponse update( @WebParam(name = "callContext", targetNamespace = "") CallContext callContext, @WebParam(name = "fcOwner", targetNamespace = "") String fcOwner, @WebParam(name = "update", targetNamespace = "") UpdateRequest update) throws BusinessException, TechnicalException, ValidationException ; /** * */ @WebMethod @RequestWrapper(localName = "ping", targetNamespace = "http://xml.mobi.ch/service/ch/mobi/maia/amw/v1_0/MaiaAmwFederationService/datatype", className = "ch.mobi.xml.service.ch.mobi.maia.amw.v1_0.maiaamwfederationservice.datatype.Ping") @ResponseWrapper(localName = "pingResponse", targetNamespace = "http://xml.mobi.ch/service/ch/mobi/maia/amw/v1_0/MaiaAmwFederationService/datatype", className = "ch.mobi.xml.service.ch.mobi.maia.amw.v1_0.maiaamwfederationservice.datatype.PingResponse") public void ping(); }
agpl-3.0
o2oa/o2oa
o2server/x_organization_assemble_authentication/src/main/java/com/x/organization/assemble/authentication/jaxrs/DingdingJaxrsFilter.java
333
package com.x.organization.assemble.authentication.jaxrs; import javax.servlet.annotation.WebFilter; import com.x.base.core.project.jaxrs.AnonymousCipherManagerUserJaxrsFilter; @WebFilter(urlPatterns = "/jaxrs/dingding/*", asyncSupported = true) public class DingdingJaxrsFilter extends AnonymousCipherManagerUserJaxrsFilter { }
agpl-3.0
automenta/java_dann
src/syncleus/dann/neural/spiking/neuron_update_rules/HodgkinHuxleyRule.java
7077
/** * */ package syncleus.dann.neural.spiking.neuron_update_rules; import syncleus.dann.neural.spiking.SpikingNeuralNetwork.TimeType; import syncleus.dann.neural.spiking.SpikingNeuron; import syncleus.dann.neural.spiking.SpikingNeuronUpdateRule; /** * Hodgkin-Huxley Neuron. * * Adapted from software written by Anthony Fodor, with help from Jonathan * Vickrey. TODO: No implementation. */ public class HodgkinHuxleyRule extends SpikingNeuronUpdateRule { /** Sodium Channels */ private float perNaChannels = 100f; /** Potassium */ private float perKChannels = 100f; /** Resting Membrane Potential */ private double resting_v = 65; /** */ private double elapsedTime = 0; /** */ private double dv; /** Membrane Capacitance */ private double cm; /** Constant leak permeabilities */ private double gk, gna, gl; /** voltage-dependent gating parameters */ private double n, m, h; /** corresponding deltas */ private double dn, dm, dh; /** // rate constants */ private double an, bn, am, bm, ah, bh; /** time step */ private double dt; /** Ek-Er, Ena - Er, Eleak - Er */ private double vk, vna, vl; /** */ private double n4; /** */ private double m3h; /** Sodium current */ private double na_current; /** Potassium current */ private double k_current; /** */ private double temp = 0; /** */ private boolean vClampOn = false; /** */ float vClampValue = convertV(0F); /** * @{inheritDoc */ public void update(SpikingNeuron neuron) { // Advances the model by dt and returns the new voltage double v = inputType.getInput(neuron); bh = 1 / (Math.exp((v + 30) / 10) + 1); ah = 0.07 * Math.exp(v / 20); dh = (ah * (1 - h) - bh * h) * dt; bm = 4 * Math.exp(v / 18); am = 0.1 * (v + 25) / (Math.exp((v + 25) / 10) - 1); bn = 0.125 * Math.exp(v / 80); an = 0.01 * (v + 10) / (Math.exp((v + 10) / 10) - 1); dm = (am * (1 - m) - bm * m) * dt; dn = (an * (1 - n) - bn * n) * dt; n4 = n * n * n * n; m3h = m * m * m * h; na_current = gna * m3h * (v - vna); k_current = gk * n4 * (v - vk); dv = -1 * dt * (k_current + na_current + gl * (v - vl)) / cm; neuron.setBuffer(-1 * (v + dv + resting_v)); h += dh; m += dm; n += dn; elapsedTime += dt; // if (vClampOn) // v = vClampValue; // getV() converts the model's v to present day convention } /** * {@inheritDoc} */ public void init(SpikingNeuron neuron) { cm = 1.0; double v = neuron.getActivation(); vna = -115; vk = 12; vl = -10.613; gna = perNaChannels * 120 / 100; gk = perKChannels * 36 / 100; gl = 0.3; dt = .005; bh = 1 / (Math.exp((v + 30) / 10) + 1); ah = 0.07 * Math.exp(v / 20); bm = 4 * Math.exp(v / 18); am = 0.1 * (v + 25) / (Math.exp((v + 25) / 10) - 1); bn = 0.125 * Math.exp(v / 80); an = 0.01 * (v + 10) / (Math.exp((v + 10) / 10) - 1); dh = (ah * (1 - h) - bh * h) * dt; dm = (am * (1 - m) - bm * m) * dt; dn = (an * (1 - n) - bn * n) * dt; // start these parameters in steady state n = an / (an + bn); m = am / (am + bm); h = ah / (ah + bh); update(neuron); } /** * {@inheritDoc} */ public TimeType getTimeType() { return TimeType.CONTINUOUS; } public double get_n4() { return n4; } public double get_m3h() { return m3h; } public synchronized float getEna() { return (float) (-1 * (vna + resting_v)); } public synchronized float getEk() { return (float) (-1 * (vk + resting_v)); } public synchronized void setEna(float Ena) { vna = -1 * Ena - resting_v; } public synchronized void setEk(float Ek) { vk = -1 * Ek - resting_v; } // The -1 is to correct for the fact that in the H & H paper, the currents // are reversed. public double get_na_current() { return -1 * na_current; } public double get_k_current() { return -1 * k_current; } // negative values set to zero public synchronized void setPerNaChannels(float perNaChannels) { if (perNaChannels < 0) { perNaChannels = 0; } this.perNaChannels = perNaChannels; gna = 120 * perNaChannels / 100; } public float getPerNaChannels() { return perNaChannels; } public synchronized void setPerKChannels(float perKChannels) { if (perKChannels < 0) { perKChannels = 0; } this.perKChannels = perKChannels; gk = 36 * perKChannels / 100; } public float getPerKChannels() { return perKChannels; } // remember that H&H voltages are -1 * present convention // TODO: should eventually calculate this instead of setting it // convert between internal use of V and the user's expectations // the V will be membrane voltage using present day conventions // see p. 505 of Hodgkin & Huxley, J Physiol. 1952, 117:500-544 public void setCm(double inCm) { cm = inCm; } public double getCm() { return cm; } public void setDt(double inDt) { dt = inDt; } public double getDt() { return dt; } public double getElapsedTime() { return elapsedTime; } public void resetElapsedTime() { elapsedTime = 0.0; } public double getN() { return n; } public double getM() { return m; } public double getH() { return h; } /** * Converts a voltage from the modern convention to the convention used by * the program. */ public float convertV(float voltage) { return (float) (-1 * voltage - resting_v); } public boolean getVClampOn() { return vClampOn; } public void setVClampOn(boolean vClampOn) { this.vClampOn = vClampOn; } float get_vClampValue() { return (float) (-1 * (vClampValue + resting_v)); } void set_vClampValue(float vClampValue) { this.vClampValue = convertV(vClampValue); } public double getTemp() { return temp; } public void setTemp(double temp) { this.temp = temp; } @Override public String getDescription() { return "Hodgkin-Huxley"; } public SpikingNeuronUpdateRule deepCopy() { // TODO return null; } }
agpl-3.0
automenta/narchy
ui/src/main/java/spacegraph/video/font/Font8x8.java
12455
package spacegraph.video.font; /** from: https://raw.githubusercontent.com/letoram/senseye/master/senses/font_8x8.h * TODO */ public class Font8x8 { // /** // * 8x8 monochrome bitmap fonts for rendering // * Author: Daniel Hepper <daniel@hepper.net> // * // * License: Public Domain // * // * Based on: // * // Summary: font8x8.h // * // 8x8 monochrome bitmap fonts for rendering // * // // * // Author: // * // Marcel Sondaar // * // International Business Machines (public domain VGA fonts) // * // // * // License: // * // Public Domain // * // * Fetched from: http://dimensionalrift.homelinux.net/combuster/mos3/? // * p=viewsource&file=/modules/gfx/font8_8.asm // **/ // // /* // * can be created by taking a TTF font, // * convert -resize 8x8\! -font Name-Family-Style -pointsize num // * label:CodePoint outp.xbm sweep through the desired codepoints and // * build the outer array, dump to header and replace // */ // //// Constant: builtin_font //// Contains an 8x8 font map for unicode points U+0000 - U+007F (basic latin) // // static int fontw = 8; // static int fonth = 8; // // static unsigned char builtin_font[128][8] = { // { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0000 (nul) // { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0001 // { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0002 // { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0003 // { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0004 // { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0005 // { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0006 // { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0007 // { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0008 // { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0009 // { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+000A // { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+000B // { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+000C // { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+000D // { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+000E // { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+000F // { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0010 // { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0011 // { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0012 // { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0013 // { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0014 // { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0015 // { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0016 // { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0017 // { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0018 // { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0019 // { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+001A // { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+001B // { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+001C // { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+001D // { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+001E // { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+001F // { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0020 (space) // { 0x18, 0x3C, 0x3C, 0x18, 0x18, 0x00, 0x18, 0x00}, // U+0021 (!) // { 0x36, 0x36, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0022 (") // { 0x36, 0x36, 0x7F, 0x36, 0x7F, 0x36, 0x36, 0x00}, // U+0023 (#) // { 0x0C, 0x3E, 0x03, 0x1E, 0x30, 0x1F, 0x0C, 0x00}, // U+0024 ($) // { 0x00, 0x63, 0x33, 0x18, 0x0C, 0x66, 0x63, 0x00}, // U+0025 (%) // { 0x1C, 0x36, 0x1C, 0x6E, 0x3B, 0x33, 0x6E, 0x00}, // U+0026 (&) // { 0x06, 0x06, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0027 (') // { 0x18, 0x0C, 0x06, 0x06, 0x06, 0x0C, 0x18, 0x00}, // U+0028 (() // { 0x06, 0x0C, 0x18, 0x18, 0x18, 0x0C, 0x06, 0x00}, // U+0029 ()) // { 0x00, 0x66, 0x3C, 0xFF, 0x3C, 0x66, 0x00, 0x00}, // U+002A (*) // { 0x00, 0x0C, 0x0C, 0x3F, 0x0C, 0x0C, 0x00, 0x00}, // U+002B (+) // { 0x00, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x0C, 0x06}, // U+002C (,) // { 0x00, 0x00, 0x00, 0x3F, 0x00, 0x00, 0x00, 0x00}, // U+002D (-) // { 0x00, 0x00, 0x00, 0x00, 0x00, 0x0C, 0x0C, 0x00}, // U+002E (.) // { 0x60, 0x30, 0x18, 0x0C, 0x06, 0x03, 0x01, 0x00}, // U+002F (/) // { 0x3E, 0x63, 0x73, 0x7B, 0x6F, 0x67, 0x3E, 0x00}, // U+0030 (0) // { 0x0C, 0x0E, 0x0C, 0x0C, 0x0C, 0x0C, 0x3F, 0x00}, // U+0031 (1) // { 0x1E, 0x33, 0x30, 0x1C, 0x06, 0x33, 0x3F, 0x00}, // U+0032 (2) // { 0x1E, 0x33, 0x30, 0x1C, 0x30, 0x33, 0x1E, 0x00}, // U+0033 (3) // { 0x38, 0x3C, 0x36, 0x33, 0x7F, 0x30, 0x78, 0x00}, // U+0034 (4) // { 0x3F, 0x03, 0x1F, 0x30, 0x30, 0x33, 0x1E, 0x00}, // U+0035 (5) // { 0x1C, 0x06, 0x03, 0x1F, 0x33, 0x33, 0x1E, 0x00}, // U+0036 (6) // { 0x3F, 0x33, 0x30, 0x18, 0x0C, 0x0C, 0x0C, 0x00}, // U+0037 (7) // { 0x1E, 0x33, 0x33, 0x1E, 0x33, 0x33, 0x1E, 0x00}, // U+0038 (8) // { 0x1E, 0x33, 0x33, 0x3E, 0x30, 0x18, 0x0E, 0x00}, // U+0039 (9) // { 0x00, 0x0C, 0x0C, 0x00, 0x00, 0x0C, 0x0C, 0x00}, // U+003A (:) // { 0x00, 0x0C, 0x0C, 0x00, 0x00, 0x0C, 0x0C, 0x06}, // U+003B (//) // { 0x18, 0x0C, 0x06, 0x03, 0x06, 0x0C, 0x18, 0x00}, // U+003C (<) // { 0x00, 0x00, 0x3F, 0x00, 0x00, 0x3F, 0x00, 0x00}, // U+003D (=) // { 0x06, 0x0C, 0x18, 0x30, 0x18, 0x0C, 0x06, 0x00}, // U+003E (>) // { 0x1E, 0x33, 0x30, 0x18, 0x0C, 0x00, 0x0C, 0x00}, // U+003F (?) // { 0x3E, 0x63, 0x7B, 0x7B, 0x7B, 0x03, 0x1E, 0x00}, // U+0040 (@) // { 0x0C, 0x1E, 0x33, 0x33, 0x3F, 0x33, 0x33, 0x00}, // U+0041 (A) // { 0x3F, 0x66, 0x66, 0x3E, 0x66, 0x66, 0x3F, 0x00}, // U+0042 (B) // { 0x3C, 0x66, 0x03, 0x03, 0x03, 0x66, 0x3C, 0x00}, // U+0043 (C) // { 0x1F, 0x36, 0x66, 0x66, 0x66, 0x36, 0x1F, 0x00}, // U+0044 (D) // { 0x7F, 0x46, 0x16, 0x1E, 0x16, 0x46, 0x7F, 0x00}, // U+0045 (E) // { 0x7F, 0x46, 0x16, 0x1E, 0x16, 0x06, 0x0F, 0x00}, // U+0046 (F) // { 0x3C, 0x66, 0x03, 0x03, 0x73, 0x66, 0x7C, 0x00}, // U+0047 (G) // { 0x33, 0x33, 0x33, 0x3F, 0x33, 0x33, 0x33, 0x00}, // U+0048 (H) // { 0x1E, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x1E, 0x00}, // U+0049 (I) // { 0x78, 0x30, 0x30, 0x30, 0x33, 0x33, 0x1E, 0x00}, // U+004A (J) // { 0x67, 0x66, 0x36, 0x1E, 0x36, 0x66, 0x67, 0x00}, // U+004B (K) // { 0x0F, 0x06, 0x06, 0x06, 0x46, 0x66, 0x7F, 0x00}, // U+004C (L) // { 0x63, 0x77, 0x7F, 0x7F, 0x6B, 0x63, 0x63, 0x00}, // U+004D (M) // { 0x63, 0x67, 0x6F, 0x7B, 0x73, 0x63, 0x63, 0x00}, // U+004E (N) // { 0x1C, 0x36, 0x63, 0x63, 0x63, 0x36, 0x1C, 0x00}, // U+004F (O) // { 0x3F, 0x66, 0x66, 0x3E, 0x06, 0x06, 0x0F, 0x00}, // U+0050 (P) // { 0x1E, 0x33, 0x33, 0x33, 0x3B, 0x1E, 0x38, 0x00}, // U+0051 (Q) // { 0x3F, 0x66, 0x66, 0x3E, 0x36, 0x66, 0x67, 0x00}, // U+0052 (R) // { 0x1E, 0x33, 0x07, 0x0E, 0x38, 0x33, 0x1E, 0x00}, // U+0053 (S) // { 0x3F, 0x2D, 0x0C, 0x0C, 0x0C, 0x0C, 0x1E, 0x00}, // U+0054 (T) // { 0x33, 0x33, 0x33, 0x33, 0x33, 0x33, 0x3F, 0x00}, // U+0055 (U) // { 0x33, 0x33, 0x33, 0x33, 0x33, 0x1E, 0x0C, 0x00}, // U+0056 (V) // { 0x63, 0x63, 0x63, 0x6B, 0x7F, 0x77, 0x63, 0x00}, // U+0057 (W) // { 0x63, 0x63, 0x36, 0x1C, 0x1C, 0x36, 0x63, 0x00}, // U+0058 (X) // { 0x33, 0x33, 0x33, 0x1E, 0x0C, 0x0C, 0x1E, 0x00}, // U+0059 (Y) // { 0x7F, 0x63, 0x31, 0x18, 0x4C, 0x66, 0x7F, 0x00}, // U+005A (Z) // { 0x1E, 0x06, 0x06, 0x06, 0x06, 0x06, 0x1E, 0x00}, // U+005B ([) // { 0x03, 0x06, 0x0C, 0x18, 0x30, 0x60, 0x40, 0x00}, // U+005C (\) // { 0x1E, 0x18, 0x18, 0x18, 0x18, 0x18, 0x1E, 0x00}, // U+005D (]) // { 0x08, 0x1C, 0x36, 0x63, 0x00, 0x00, 0x00, 0x00}, // U+005E (^) // { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0xFF}, // U+005F (_) // { 0x0C, 0x0C, 0x18, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+0060 (`) // { 0x00, 0x00, 0x1E, 0x30, 0x3E, 0x33, 0x6E, 0x00}, // U+0061 (a) // { 0x07, 0x06, 0x06, 0x3E, 0x66, 0x66, 0x3B, 0x00}, // U+0062 (b) // { 0x00, 0x00, 0x1E, 0x33, 0x03, 0x33, 0x1E, 0x00}, // U+0063 (c) // { 0x38, 0x30, 0x30, 0x3e, 0x33, 0x33, 0x6E, 0x00}, // U+0064 (d) // { 0x00, 0x00, 0x1E, 0x33, 0x3f, 0x03, 0x1E, 0x00}, // U+0065 (e) // { 0x1C, 0x36, 0x06, 0x0f, 0x06, 0x06, 0x0F, 0x00}, // U+0066 (f) // { 0x00, 0x00, 0x6E, 0x33, 0x33, 0x3E, 0x30, 0x1F}, // U+0067 (g) // { 0x07, 0x06, 0x36, 0x6E, 0x66, 0x66, 0x67, 0x00}, // U+0068 (h) // { 0x0C, 0x00, 0x0E, 0x0C, 0x0C, 0x0C, 0x1E, 0x00}, // U+0069 (i) // { 0x30, 0x00, 0x30, 0x30, 0x30, 0x33, 0x33, 0x1E}, // U+006A (j) // { 0x07, 0x06, 0x66, 0x36, 0x1E, 0x36, 0x67, 0x00}, // U+006B (k) // { 0x0E, 0x0C, 0x0C, 0x0C, 0x0C, 0x0C, 0x1E, 0x00}, // U+006C (l) // { 0x00, 0x00, 0x33, 0x7F, 0x7F, 0x6B, 0x63, 0x00}, // U+006D (m) // { 0x00, 0x00, 0x1F, 0x33, 0x33, 0x33, 0x33, 0x00}, // U+006E (n) // { 0x00, 0x00, 0x1E, 0x33, 0x33, 0x33, 0x1E, 0x00}, // U+006F (o) // { 0x00, 0x00, 0x3B, 0x66, 0x66, 0x3E, 0x06, 0x0F}, // U+0070 (p) // { 0x00, 0x00, 0x6E, 0x33, 0x33, 0x3E, 0x30, 0x78}, // U+0071 (q) // { 0x00, 0x00, 0x3B, 0x6E, 0x66, 0x06, 0x0F, 0x00}, // U+0072 (r) // { 0x00, 0x00, 0x3E, 0x03, 0x1E, 0x30, 0x1F, 0x00}, // U+0073 (s) // { 0x08, 0x0C, 0x3E, 0x0C, 0x0C, 0x2C, 0x18, 0x00}, // U+0074 (t) // { 0x00, 0x00, 0x33, 0x33, 0x33, 0x33, 0x6E, 0x00}, // U+0075 (u) // { 0x00, 0x00, 0x33, 0x33, 0x33, 0x1E, 0x0C, 0x00}, // U+0076 (v) // { 0x00, 0x00, 0x63, 0x6B, 0x7F, 0x7F, 0x36, 0x00}, // U+0077 (w) // { 0x00, 0x00, 0x63, 0x36, 0x1C, 0x36, 0x63, 0x00}, // U+0078 (x) // { 0x00, 0x00, 0x33, 0x33, 0x33, 0x3E, 0x30, 0x1F}, // U+0079 (y) // { 0x00, 0x00, 0x3F, 0x19, 0x0C, 0x26, 0x3F, 0x00}, // U+007A (z) // { 0x38, 0x0C, 0x0C, 0x07, 0x0C, 0x0C, 0x38, 0x00}, // U+007B ({) // { 0x18, 0x18, 0x18, 0x00, 0x18, 0x18, 0x18, 0x00}, // U+007C (|) // { 0x07, 0x0C, 0x0C, 0x38, 0x0C, 0x0C, 0x07, 0x00}, // U+007D (}) // { 0x6E, 0x3B, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00}, // U+007E (~) // { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00} // U+007F // }; // // static bool draw_box(struct arcan_shmif_cont* c, uint16_t x, uint16_t y, // uint16_t w, uint16_t h, shmif_pixel col) // { // if (x >= c->w || y >= c->h) // return false; // // int ux = x + w > c->w ? c->w : x + w; // int uy = y + h > c->h ? c->h : y + h; // // for (int cy = y; cy != uy; cy++) // for (int cx = x; cx != ux; cx++) // c->vidp[ cy * c->pitch + cx ] = col; // // return true; // } // // static inline void draw_char(struct arcan_shmif_cont* c, uint8_t ch, // uint16_t x, uint16_t y, shmif_pixel txcol) // { // for (int row = 0; row < fonth && row + y < c->h; row++) // for (int col = 0; col < fontw && col + x < c->w; col++) // if (builtin_font[ch][row] & 1 << col) // c->vidp[(row + y) * c->pitch + col + x] = txcol; // } // // static void draw_text(struct arcan_shmif_cont* c, const char* msg, // uint16_t x, uint16_t y, shmif_pixel txcol) // { // uint16_t cx = x; // uint16_t cy = y; // // while (*msg){ // uint8_t ch = *msg++; // // if (ch > 127) // continue; // // if ('\n' == ch){ // cx = x; // cy += fonth + 2; // } // // draw_char(c, ch, cx, cy, txcol), // cx += fontw; // } // } }
agpl-3.0
splicemachine/spliceengine
db-engine/src/main/java/com/splicemachine/db/mbeans/ManagementMBean.java
3767
/* * 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.db.mbeans; /** * JMX MBean inteface to control visibility of Derby's MBeans. * When Derby boots it attempts to register its MBeans. * It may fail due to lack of valid permissions. * If Derby does not register its MBeans then an * application may register the Management implementation * of ManagementMBean itself and use it to start Derby's * JMX management. * <P> * Key properties for registered MBean when registered by Derby: * <UL> * <LI> <code>type=Management</code> * <LI> <code>system=</code><em>runtime system identifier</em> (see overview) * </UL> * * @see Management * @see ManagementMBean#getSystemIdentifier() */ public interface ManagementMBean { /** * Is Derby's JMX management active. If active then Derby * has registered MBeans relevant to its current state. * @return true Derby has registered beans, false Derby has not * registered any beans. */ boolean isManagementActive(); /** * Get the system identifier that this MBean is managing. * The system identifier is a runtime value to disambiguate * multiple Derby systems in the same virtual machine but * different class loaders. * * @return Runtime identifier for the system, null if Derby is not running. */ String getSystemIdentifier(); /** * Inform Derby to start its JMX management by registering * MBeans relevant to its current state. If Derby is not * booted then no action is taken. * <P> * Require <code>SystemPermission("jmx", "control")</code> if a security * manager is installed. * * @see com.splicemachine.db.security.SystemPermission */ void startManagement(); /** * Inform Derby to stop its JMX management by unregistering * its MBeans. If Derby is not booted then no action is taken. * <P> * Require <code>SystemPermission("jmx", "control")</code> if a security * manager is installed. * * @see com.splicemachine.db.security.SystemPermission */ void stopManagement(); }
agpl-3.0
CeON/CERMINE
cermine-impl/src/main/java/pl/edu/icm/cermine/metadata/extraction/enhancers/JournalVolumeIssueWithAuthorEnhancer.java
3371
/** * This file is part of CERMINE project. * Copyright (c) 2011-2018 ICM-UW * * CERMINE 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. * * CERMINE 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 CERMINE. If not, see <http://www.gnu.org/licenses/>. */ package pl.edu.icm.cermine.metadata.extraction.enhancers; import java.util.ArrayList; import java.util.EnumSet; import java.util.List; import java.util.Locale; import java.util.Set; import java.util.regex.MatchResult; import java.util.regex.Pattern; import pl.edu.icm.cermine.metadata.model.DocumentAuthor; import pl.edu.icm.cermine.metadata.model.DocumentMetadata; import pl.edu.icm.cermine.structure.model.BxZoneLabel; /** * @author Dominika Tkaczyk (d.tkaczyk@icm.edu.pl) */ public class JournalVolumeIssueWithAuthorEnhancer extends AbstractPatternEnhancer { private static final Pattern PATTERN = Pattern.compile("(.*)\\d{4}, (\\d+):(\\d+)"); private static final Set<BxZoneLabel> SEARCHED_ZONE_LABELS = EnumSet.of(BxZoneLabel.MET_BIB_INFO); public JournalVolumeIssueWithAuthorEnhancer() { super(PATTERN, SEARCHED_ZONE_LABELS); } @Override protected Set<EnhancedField> getEnhancedFields() { return EnumSet.of(EnhancedField.JOURNAL, EnhancedField.VOLUME, EnhancedField.ISSUE); } @Override protected boolean enhanceMetadata(MatchResult result, DocumentMetadata metadata) { String journal = result.group(1); List<String> authors = getAuthorNames(metadata); if (authors.size() == 1) { journal = removeFirst(journal, authors.get(0)); } if (authors.size() == 2) { journal = removeFirst(journal, authors.get(0)); journal = removeFirst(journal, "and"); journal = removeFirst(journal, authors.get(1)); } if (authors.size() > 2) { journal = journal.replaceFirst("^.*et al\\.", "").trim(); } metadata.setJournal(journal); metadata.setVolume(result.group(2)); metadata.setIssue(result.group(3)); return true; } private String removeFirst(String journal, String prefix) { if (journal.toLowerCase(Locale.ENGLISH).startsWith(prefix.toLowerCase(Locale.ENGLISH))) { return journal.substring(prefix.length()).trim(); } String[] strs = prefix.split(" "); for (String str : strs) { if (journal.toLowerCase(Locale.ENGLISH).startsWith(str.toLowerCase(Locale.ENGLISH))) { return journal.substring(str.length()).trim(); } } return journal; } private List<String> getAuthorNames(DocumentMetadata metadata) { List<String> authors = new ArrayList<String>(); for (DocumentAuthor a : metadata.getAuthors()) { authors.add(a.getName()); } return authors; } }
agpl-3.0
TMS-v113/server
src/server/shops/HiredMerchant.java
7341
/* This file is part of the OdinMS Maple Story Server Copyright (C) 2008 ~ 2010 Patrick Huy <patrick.huy@frz.cc> Matthias Butz <matze@odinms.de> Jan Christian Meyer <vimes@odinms.de> 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. You may not use, modify or distribute this program under any other version of the GNU Affero General Public License. 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 server.shops; import java.util.concurrent.ScheduledFuture; import client.inventory.IItem; import java.util.concurrent.locks.Lock; import client.inventory.ItemFlag; import constants.GameConstants; import client.MapleCharacter; import client.MapleClient; import server.MapleItemInformationProvider; import handling.channel.ChannelServer; import java.util.LinkedList; import java.util.List; import java.util.LinkedHashMap; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.locks.ReentrantReadWriteLock; import server.MapleInventoryManipulator; import server.Timer.EtcTimer; import server.maps.MapleMapObjectType; import tools.MaplePacketCreator; import tools.packet.PlayerShopPacket; public class HiredMerchant extends AbstractPlayerStore { public ScheduledFuture<?> schedule; private List<String> blacklist; private Map<String, Byte> MsgList; private int storeid; private long start; private ReentrantReadWriteLock merchantLock = new ReentrantReadWriteLock(); public HiredMerchant(MapleCharacter owner, int itemId, String desc) { super(owner, itemId, desc, "", 3); start = System.currentTimeMillis(); blacklist = new LinkedList<String>(); MsgList = new HashMap<String, Byte>(); this.schedule = EtcTimer.getInstance().schedule(new Runnable() { @Override public void run() { closeShop(true, true); } }, 1000 * 60 * 60 * 24); } public byte getShopType() { return IMaplePlayerShop.HIRED_MERCHANT; } public final void setStoreid(final int storeid) { this.storeid = storeid; } public List<MaplePlayerShopItem> searchItem(final int itemSearch) { final List<MaplePlayerShopItem> itemz = new LinkedList<MaplePlayerShopItem>(); for (MaplePlayerShopItem item : items) { if (item.item.getItemId() == itemSearch && item.bundles > 0) { itemz.add(item); } } return itemz; } @Override public void buy(MapleClient c, int item, short quantity) { final MaplePlayerShopItem pItem = items.get(item); synchronized(pItem){ final IItem shopItem = pItem.item; final IItem newItem = shopItem.copy(); final short perbundle = newItem.getQuantity(); final int theQuantity = (pItem.price * quantity); newItem.setQuantity((short) (quantity * perbundle)); byte flag = newItem.getFlag(); if (ItemFlag.KARMA_EQ.check(flag)) { newItem.setFlag((byte) (flag - ItemFlag.KARMA_EQ.getValue())); } else if (ItemFlag.KARMA_USE.check(flag)) { newItem.setFlag((byte) (flag - ItemFlag.KARMA_USE.getValue())); } if (MapleInventoryManipulator.checkSpace(c, newItem.getItemId(), newItem.getQuantity(), newItem.getOwner())) { final int gainmeso = getMeso() + theQuantity - GameConstants.EntrustedStoreTax(theQuantity); if (gainmeso > 0) { if(MapleInventoryManipulator.addFromDrop(c, newItem, false)){ setMeso(gainmeso); pItem.bundles -= quantity; // Number remaining in the store bought.add(new BoughtItem(newItem.getItemId(), quantity, theQuantity, c.getPlayer().getName())); c.getPlayer().gainMeso(-theQuantity, false); MapleCharacter chr = getMCOwnerWorld(); if (chr != null) { chr.dropMessage(5, "物品 " + MapleItemInformationProvider.getInstance().getName(newItem.getItemId()) + " (" + perbundle + ") x " + quantity + " 已從精靈商店賣出. 還剩下 " + pItem.bundles + "個"); } }else{ c.getPlayer().dropMessage(1, "您的背包滿了."); c.getSession().write(MaplePacketCreator.enableActions()); } } else { c.getPlayer().dropMessage(1, "拍賣家有太多錢了."); c.getSession().write(MaplePacketCreator.enableActions()); } } else { c.getPlayer().dropMessage(1, "您的背包滿了."); c.getSession().write(MaplePacketCreator.enableActions()); } } } @Override public void closeShop(boolean saveItems, boolean remove) { merchantLock.writeLock().lock(); try{ if (schedule != null) { schedule.cancel(false); } if (saveItems) { saveItems(); items.clear(); } if (remove) { ChannelServer.getInstance(channel).removeMerchant(this); getMap().broadcastMessage(PlayerShopPacket.destroyHiredMerchant(getOwnerId())); } getMap().removeMapObject(this); schedule = null; }finally{ merchantLock.writeLock().unlock(); } } public int getTimeLeft() { return (int) ((System.currentTimeMillis() - start) / 1000); } public final int getStoreId() { return storeid; } @Override public MapleMapObjectType getType() { return MapleMapObjectType.HIRED_MERCHANT; } @Override public void sendDestroyData(MapleClient client) { if (isAvailable()) { client.getSession().write(PlayerShopPacket.destroyHiredMerchant(getOwnerId())); } } @Override public void sendSpawnData(MapleClient client) { if (isAvailable()) { client.getSession().write(PlayerShopPacket.spawnHiredMerchant(this)); } } public final boolean isInBlackList(final String bl) { return blacklist.contains(bl); } public final void addBlackList(final String bl) { blacklist.add(bl); } public final void removeBlackList(final String bl) { blacklist.remove(bl); } public final void sendBlackList(final MapleClient c) { c.getSession().write(PlayerShopPacket.MerchantBlackListView(blacklist)); } public final void sendVisitor(final MapleClient c) { c.getSession().write(PlayerShopPacket.MerchantVisitorView(visitors)); } public final void addMsg(final String msg , final byte slot) { MsgList.put( msg , slot); } public final void SendMsg(final MapleClient c) { for (final Entry<String, Byte> s : MsgList.entrySet()) { c.getSession().write(PlayerShopPacket.shopChat( s.getKey() , s.getValue() ) ); } } }
agpl-3.0
MCPhoton/Photon-MC1.8
src/org/mcphoton/world/ChunkCoordinates.java
2413
/* * Copyright (C) 2015 ElectronWill * * 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.mcphoton.world; import org.mcphoton.util.Location; /** * Represents the coordinates of a map chunk. They are NOT the same as the coordinates of the first block in the chunk ! */ public final class ChunkCoordinates implements Comparable<ChunkCoordinates> { /** * Returns the chunk coordinates of the given block XZ. * * @param blockX * @param blockZ * @return */ public static ChunkCoordinates ofBlock(int blockX, int blockZ) { return new ChunkCoordinates(blockX >> 4, blockZ >> 4);// >> 4 means divide by 16 } /** * Returns the chunk coordinates of the given location XZ. * * @param locX * @param locZ * @return */ public static ChunkCoordinates ofLocation(double locX, double locZ) { return new ChunkCoordinates((int) locX / 16, (int) locZ / 16); } /** * Returns the chunk coordinates of the given location. * * @param l * @return */ public static ChunkCoordinates ofLocation(Location l) { return new ChunkCoordinates(l.getBlockX() >> 4, l.getBlockZ() >> 4); } private final int x; private final int z; public ChunkCoordinates(int x, int z) { this.x = x; this.z = z; } @Override public int compareTo(ChunkCoordinates o) { return x == o.x ? z - o.z : x - o.x;// Compares x first, then z if x are the same. } @Override public boolean equals(Object obj) { if (!(obj instanceof ChunkCoordinates)) { return false; } ChunkCoordinates cc = (ChunkCoordinates) obj; return x == cc.x && z == cc.z; } public int getX() { return x; } public int getZ() { return z; } @Override public int hashCode() { int hash = 3; hash = 47 * hash + this.x; hash = 47 * hash + this.z; return hash; } }
agpl-3.0
printedheart/opennars
nars_gui/src/main/java/ca/nengo/ui/lib/object/activity/TrackedAction.java
1496
package ca.nengo.ui.lib.object.activity; import ca.nengo.ui.AbstractNengo; import ca.nengo.ui.lib.action.StandardAction; import ca.nengo.ui.lib.world.piccolo.WorldObjectImpl; import javax.swing.*; /** * An action which is tracked by the UI. Since tracked actions are slow and have * UI messages associated with them, they do never execute inside the Swing * dispatcher thread. * * @author Shu Wu */ public abstract class TrackedAction extends StandardAction { private static final long serialVersionUID = 1L; private final String taskName; private TrackedStatusMsg trackedMsg; private final WorldObjectImpl wo; public TrackedAction(String taskName) { this(taskName, null); } public TrackedAction(String taskName, WorldObjectImpl wo) { super(taskName, null, false); this.taskName = taskName; this.wo = wo; } @Override public void doAction() { SwingUtilities.invokeLater(new Runnable() { public void run() { trackedMsg = new TrackedStatusMsg(taskName, wo); } }); AbstractNengo.getInstance().getProgressIndicator().start(taskName); super.doAction(); } protected void doActionInternal() { AbstractNengo.getInstance().getProgressIndicator().setThread(); super.doActionInternal(); } @Override protected void postAction() { super.postAction(); AbstractNengo.getInstance().getProgressIndicator().stop(); SwingUtilities.invokeLater(new Runnable() { public void run() { trackedMsg.finished(); } }); } }
agpl-3.0
apnadmin/appynotebook
src/java/com/feezixlabs/util/FileSystem.java
4113
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package com.feezixlabs.util; import java.io.*; /** * * @author bitlooter */ public class FileSystem extends File { static final java.text.DateFormat dateFormat = new java.text.SimpleDateFormat("MM-dd-yyyy"); // Constructor public FileSystem( String name) { super( name ); } // Output file name with indentation public void printName( int depth) { // for( int i = 0; i < depth; i++ ) // System.out.print( "\t" ); // System.out.println( getName( ) ); } // Public driver to list all files in directory public String listAll( ) { StringBuffer buf = new StringBuffer(); listAll( 0,"NULL",buf,"" ); return buf.toString(); } // Recursive method to list all files in directory private void listAll( int depth,String parentId,StringBuffer buf,String qualifiedParentId ) { printName( depth ); String id = (depth==0)?this.getName():org.apache.commons.codec.digest.DigestUtils.md5Hex(this.getAbsolutePath()); String qualifiedId = qualifiedParentId.length()>0?qualifiedParentId+","+id:id; String checkBox = " <input type=\"checkbox\" onclick=\"appletBuilder.selectLibraryEntry(["+(qualifiedParentId.length()>0?"'"+qualifiedParentId.replaceAll(",", "','")+"'":"")+"],'"+id+"')\" class=\"selectlibraryentry\" id=\"selectlibraryentry-"+qualifiedId.replaceAll(",","-")+"\" name=\"selectlibraryentry-"+id+"\" disabled/> "; buf.append("<row>"); buf.append(" <cell><![CDATA["+id+"]]></cell>"); buf.append(" <cell><![CDATA["+checkBox+this.getName()+"]]></cell>"); buf.append(" <cell><![CDATA["+(this.size())+"]]></cell>"); int library_path_length = (com.feezixlabs.util.ConfigUtil.resource_directory+"/library").length()+1; buf.append(" <cell><![CDATA["+(this.getAbsolutePath().substring(library_path_length))+"]]></cell>"); if(depth == 0 ){ buf.append(" <cell><![CDATA["+dateFormat.format(new java.util.Date(this.lastModified()))+"]]></cell>"); buf.append(" <cell><![CDATA[]]></cell>"); } else{ buf.append(" <cell><![CDATA[]]></cell>"); buf.append(" <cell><![CDATA[]]></cell>"); } buf.append(" <cell>"+depth+"</cell>"); buf.append(" <cell>"+parentId+"</cell>"); if( isDirectory( ) ) { buf.append(" <cell>false</cell>"); buf.append(" <cell>false</cell>"); buf.append("</row>"); String [ ] entries = list( ); for( int i = 0; i < entries.length; i++ ) { FileSystem child = new FileSystem( getPath( )+ separatorChar + entries[ i ] ); child.listAll( depth + 1,id, buf,qualifiedId); } } else { buf.append(" <cell>true</cell>"); buf.append(" <cell>false</cell>"); buf.append("</row>"); } } public long size( ) { long totalSize = length( ); if( isDirectory( ) ) { String [ ] entries = list( ); for( int i = 0; i < entries.length; i++ ) { FileSystem child = new FileSystem( getPath( )+ separatorChar + entries[ i ] ); totalSize += child.size( ); } } return totalSize; } // Simple main to list all files in current directory static public String buildGrid( String rootDir) { FileSystem f = new FileSystem( rootDir ); String [ ] entries = f.list( ); StringBuffer buf = new StringBuffer(); for( int i = 0; i < entries.length; i++ ) { FileSystem child = new FileSystem( f.getPath( )+ separatorChar + entries[ i ] ); child.listAll( 0,"NULL", buf,"" ); } return buf.toString(); //System.out.println( "Total bytes: " + f.size( ) ); } }
agpl-3.0
shenan4321/BIMplatform
generated/cn/dlb/bim/models/ifc2x3tc1/IfcDistributionChamberElementType.java
2662
/** * Copyright (C) 2009-2014 BIMserver.org * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package cn.dlb.bim.models.ifc2x3tc1; /** * <!-- begin-user-doc --> * A representation of the model object '<em><b>Ifc Distribution Chamber Element Type</b></em>'. * <!-- end-user-doc --> * * <p> * The following features are supported: * </p> * <ul> * <li>{@link cn.dlb.bim.models.ifc2x3tc1.IfcDistributionChamberElementType#getPredefinedType <em>Predefined Type</em>}</li> * </ul> * * @see cn.dlb.bim.models.ifc2x3tc1.Ifc2x3tc1Package#getIfcDistributionChamberElementType() * @model * @generated */ public interface IfcDistributionChamberElementType extends IfcDistributionFlowElementType { /** * Returns the value of the '<em><b>Predefined Type</b></em>' attribute. * The literals are from the enumeration {@link cn.dlb.bim.models.ifc2x3tc1.IfcDistributionChamberElementTypeEnum}. * <!-- begin-user-doc --> * <p> * If the meaning of the '<em>Predefined Type</em>' attribute isn't clear, * there really should be more of a description here... * </p> * <!-- end-user-doc --> * @return the value of the '<em>Predefined Type</em>' attribute. * @see cn.dlb.bim.models.ifc2x3tc1.IfcDistributionChamberElementTypeEnum * @see #setPredefinedType(IfcDistributionChamberElementTypeEnum) * @see cn.dlb.bim.models.ifc2x3tc1.Ifc2x3tc1Package#getIfcDistributionChamberElementType_PredefinedType() * @model * @generated */ IfcDistributionChamberElementTypeEnum getPredefinedType(); /** * Sets the value of the '{@link cn.dlb.bim.models.ifc2x3tc1.IfcDistributionChamberElementType#getPredefinedType <em>Predefined Type</em>}' attribute. * <!-- begin-user-doc --> * <!-- end-user-doc --> * @param value the new value of the '<em>Predefined Type</em>' attribute. * @see cn.dlb.bim.models.ifc2x3tc1.IfcDistributionChamberElementTypeEnum * @see #getPredefinedType() * @generated */ void setPredefinedType(IfcDistributionChamberElementTypeEnum value); } // IfcDistributionChamberElementType
agpl-3.0
printedheart/opennars
nars_lab/src/main/java/automenta/spacegraph/ui/PointerLayer.java
2542
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package automenta.spacegraph.ui; import automenta.spacegraph.Surface; import automenta.spacegraph.control.Pointer; import automenta.spacegraph.math.linalg.Vec3f; import automenta.spacegraph.shape.Drawable; import com.jogamp.opengl.GL2; /** * * @author seh */ public class PointerLayer implements Drawable { private final Surface canvas; final Vec3f color = new Vec3f(); final Vec3f red = new Vec3f(1f, 0, 0); final Vec3f green = new Vec3f(0, 1f, 0); float minPointerSize = 0.2f; float alpha = 0.75f; final Vec3f lastPos = new Vec3f(); final Vec3f speed = new Vec3f(); float radius = 0.5f; float radiusMomentum = 0.9f; float phase = 0; float accelerationMagnification = 1.5f; float deltaPhase = 0.01f; int numSteps = 16; public PointerLayer(Surface canvas) { super(); this.canvas = canvas; } public void draw(GL2 gl) { //gl.glMatrixMode(GL2ES1.GL_MODELVIEW); //gl.glLoadIdentity(); //gl.glMatrixMode(GL2ES1.GL_PROJECTION); //gl.glLoadIdentity(); drawPointer(gl, canvas.getPointer()); //TODO handle multiple pointers } protected void drawPointer(GL2 gl, Pointer pointer) { speed.set(pointer.world); speed.sub(lastPos); lastPos.set(pointer.world); gl.glOrtho(-1, 1, -1, 1, -1, 1); double increment = Math.PI / numSteps; float nextRadius = accelerationMagnification * speed.length() + minPointerSize; //TODO adjust for 'z' height radius = nextRadius * (1.0f - radiusMomentum) + radius * (radiusMomentum); phase += deltaPhase; float x = pointer.world.x(); float y = pointer.world.y(); if (pointer.buttons[0]) { color.lerp(green, 0.9f); } else { color.lerp(red, 0.9f); } gl.glBegin(GL2.GL_LINES); for (int i = numSteps - 1; i >= 0; i--) { gl.glColor4f(color.x(), color.y(), color.z(), alpha); gl.glVertex3d(x + radius * Math.cos(phase + i * increment), y + radius * Math.sin(phase + i * increment), 0); gl.glVertex3d(x + -1.0 * radius * Math.cos(phase + i * increment), y + -1.0 * radius * Math.sin(phase + i * increment), 0); } gl.glEnd(); } }
agpl-3.0
crosslink/xowa
dev/400_xowa/src/gplx/xowa/xtns/gallery/Gallery_itm_parser_tst.java
7217
/* XOWA: the XOWA Offline Wiki Application Copyright (C) 2012 gnosygnu@gmail.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 gplx.xowa.xtns.gallery; import gplx.*; import gplx.xowa.*; import gplx.xowa.xtns.*; import org.junit.*; public class Gallery_itm_parser_tst { @Before public void init() {fxt.Init();} private Gallery_itm_parser_fxt fxt = new Gallery_itm_parser_fxt(); @Test public void All() {fxt.Test_parse("File:A.png|a|alt=b|link=c" , fxt.Expd("File:A.png", "a" , "b" , "c"));} @Test public void Ttl_only() {fxt.Test_parse("File:A.png" , fxt.Expd("File:A.png", null, null, null));} @Test public void Ttl_url_encoded() {fxt.Test_parse("File:A%28b%29.png" , fxt.Expd("File:A(b).png"));} // PURPOSE: handle url-encoded sequences; DATE:2014-01-01 @Test public void Caption_only() {fxt.Test_parse("File:A.png|a" , fxt.Expd("File:A.png", "a" , null, null));} @Test public void Caption_many() {fxt.Test_parse("File:A.png|a|b" , fxt.Expd("File:A.png", "a|b"));} // NOTE: pipe becomes part of caption (i.e.: doesn't separate into caption / alt) @Test public void Alt_only() {fxt.Test_parse("File:A.png|alt=a" , fxt.Expd("File:A.png", null, "a" , null));} @Test public void Link_only() {fxt.Test_parse("File:A.png|link=a" , fxt.Expd("File:A.png", null, null, "a"));} @Test public void Caption_alt() {fxt.Test_parse("File:A.png|a|alt=b" , fxt.Expd("File:A.png", "a" , "b"));} @Test public void Alt_caption() {fxt.Test_parse("File:A.png|alt=a|b" , fxt.Expd("File:A.png", "b" , "a"));} @Test public void Alt_blank() {fxt.Test_parse("File:A.png|alt=|b" , fxt.Expd("File:A.png", "b" , ""));} @Test public void Alt_invalid() {fxt.Test_parse("File:A.png|alta=b" , fxt.Expd("File:A.png", "alta=b"));} // NOTE: invalid alt becomes caption @Test public void Ws() {fxt.Test_parse("File:A.png| alt = b | c" , fxt.Expd("File:A.png", "c" , "b"));} @Test public void Ws_caption_many() {fxt.Test_parse("File:A.png| a | b | c " , fxt.Expd("File:A.png", "a | b | c"));} @Test public void Page_pdf() {fxt.Test_parse("File:A.pdf|page=1 " , fxt.Expd("File:A.pdf", null, null, null, 1));} // pdf parses page=1 @Test public void Page_png() {fxt.Test_parse("File:A.png|page=1 " , fxt.Expd("File:A.png", "page=1", null, null));} // non-pdf treats page=1 as caption @Test public void Page_invalid() {fxt.Test_parse("|page=1");} // check that null title doesn't fail; DATE:2014-03-21 @Test public void Skip_blank() {fxt.Test_parse("");} @Test public void Skip_empty() {fxt.Test_parse("|File:A.png");} @Test public void Skip_ws() {fxt.Test_parse(" |File:A.png");} @Test public void Skip_anchor() {fxt.Test_parse("#a");} // PURPOSE: anchor-like ttl should not render; ar.d:جَبَّارَة; DATE:2014-03-18 @Test public void Many() { fxt.Test_parse("File:A.png\nFile:B.png" , fxt.Expd("File:A.png"), fxt.Expd("File:B.png")); } @Test public void Many_nl() { fxt.Test_parse("File:A.png\n\n\nFile:B.png" , fxt.Expd("File:A.png"), fxt.Expd("File:B.png")); } @Test public void Many_nl_w_tab() { fxt.Test_parse("File:A.png\n \t \nFile:B.png" , fxt.Expd("File:A.png"), fxt.Expd("File:B.png")); } @Test public void Many_invalid() { fxt.Test_parse("File:A.png\n<invalid>\nFile:B.png" , fxt.Expd("File:A.png"), fxt.Expd("File:B.png")); } @Test public void Caption_complicated() { fxt.Test_parse("File:A.png|alt=a|b[[c|d]]e ", fxt.Expd("File:A.png", "b[[c|d]]e", "a")); } @Test public void Alt_magic_word_has_arg() { // PURPOSE: img_alt magic_word is of form "alt=$1"; make sure =$1 is stripped for purpose of parser; DATE:2013-09-12 fxt.Init_kwd_set(Xol_kwd_grp_.Id_img_alt, "alt=$1"); fxt.Test_parse("File:A.png|alt=a|b", fxt.Expd("File:A.png", "b", "a")); } @Test public void Link_null() { // PURPOSE: null link causes page to fail; EX: ru.w:Гянджа; <gallery>Datei:A.png|link= |</gallery>; DATE:2014-04-11 fxt.Test_parse("File:A.png|link = |b", fxt.Expd("File:A.png", "b", null, null)); } @Test public void Caption_empty() { // PURPOSE: check that empty ws doesn't break caption (based on Link_null); DATE:2014-04-11 fxt.Test_parse("File:A.png| | | ", fxt.Expd("File:A.png", null, null, null)); } } class Gallery_itm_parser_fxt { private Xoa_app app; private Xow_wiki wiki; private Gallery_itm_parser parser; public Gallery_itm_parser_fxt Init() { this.app = Xoa_app_fxt.app_(); this.wiki = Xoa_app_fxt.wiki_tst_(app); parser = new Gallery_itm_parser(); parser.Init_by_wiki(wiki); return this; } public String[] Expd(String ttl) {return new String[] {ttl, null, null, null, null};} public String[] Expd(String ttl, String caption) {return new String[] {ttl, caption, null, null, null};} public String[] Expd(String ttl, String caption, String alt) {return new String[] {ttl, caption, alt, null, null};} public String[] Expd(String ttl, String caption, String alt, String link) {return new String[] {ttl, caption, alt, link, null};} public String[] Expd(String ttl, String caption, String alt, String link, int page) {return new String[] {ttl, caption, alt, link, Int_.XtoStr(page)};} public void Init_kwd_set(int kwd_id, String kwd_val) { wiki.Lang().Kwd_mgr().Get_or_new(kwd_id).Itms()[0].Val_(Bry_.new_ascii_(kwd_val)); parser.Init_by_wiki(wiki); } public void Test_parse(String raw, String[]... expd) { ListAdp actl = ListAdp_.new_(); byte[] src = Bry_.new_ascii_(raw); parser.Parse_all(actl, Gallery_mgr_base_.New_by_mode(Gallery_mgr_base_.Traditional_tid), new Gallery_xnde(), src, 0, src.length); Tfds.Eq_ary(String_.Ary_flatten(expd), String_.Ary_flatten(X_to_str_ary(src, actl))); } private String[][] X_to_str_ary(byte[] src, ListAdp list) { int len = list.Count(); String[][] rv = new String[len][]; for (int i = 0; i < len; i++) { Gallery_itm itm = (Gallery_itm)list.FetchAt(i); String[] ary = new String[5]; rv[i] = ary; ary[0] = String_.new_utf8_(itm.Ttl().Full_txt()); ary[2] = X_to_str_ary_itm(src, itm.Alt_bgn(), itm.Alt_end()); ary[3] = X_to_str_ary_itm(src, itm.Link_bgn(), itm.Link_end()); ary[4] = X_to_str_ary_itm(src, itm.Page_bgn(), itm.Page_end()); byte[] caption = itm.Caption_bry(); ary[1] = caption == null ? null : String_.new_utf8_(caption); } return rv; } private String X_to_str_ary_itm(byte[] src, int bgn, int end) { return bgn == Bry_.NotFound && end == Bry_.NotFound ? null : String_.new_utf8_(src, bgn, end); } }
agpl-3.0
boob-sbcm/3838438
src/main/java/com/rapidminer/operator/learner/functions/kernel/jmysvm/svm/SVM.java
36219
/** * 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.learner.functions.kernel.jmysvm.svm; import com.rapidminer.example.Attribute; import com.rapidminer.operator.Operator; import com.rapidminer.operator.learner.functions.kernel.AbstractMySVMLearner; import com.rapidminer.operator.learner.functions.kernel.JMySVMLearner; import com.rapidminer.operator.learner.functions.kernel.jmysvm.examples.SVMExample; import com.rapidminer.operator.learner.functions.kernel.jmysvm.examples.SVMExamples; import com.rapidminer.operator.learner.functions.kernel.jmysvm.kernel.Kernel; import com.rapidminer.operator.learner.functions.kernel.jmysvm.optimizer.QuadraticProblem; import com.rapidminer.operator.learner.functions.kernel.jmysvm.optimizer.QuadraticProblemSMO; import com.rapidminer.operator.learner.functions.kernel.jmysvm.util.MaxHeap; import com.rapidminer.operator.learner.functions.kernel.jmysvm.util.MinHeap; import com.rapidminer.parameter.UndefinedParameterError; import com.rapidminer.tools.LogService; import com.rapidminer.tools.RandomGenerator; import com.rapidminer.tools.WrapperLoggingHandler; import java.util.Iterator; import java.util.logging.Level; /** * Abstract base class for all SVMs * * @author Stefan Rueping, Ingo Mierswa */ public abstract class SVM implements SVMInterface { private static final int[] RAPID_MINER_VERBOSITY = { LogService.STATUS, LogService.STATUS, LogService.STATUS, LogService.MINIMUM, LogService.MINIMUM }; protected Kernel the_kernel; protected SVMExamples the_examples; double[] alphas; double[] ys; protected int examples_total; // protected int verbosity; protected int target_count; protected double convergence_epsilon = 1e-3; protected double lambda_factor; protected int[] at_bound; protected double[] sum; protected boolean[] which_alpha; protected int[] working_set; protected double[] primal; protected double sum_alpha; protected double lambda_eq; protected int to_shrink; protected double feasible_epsilon; protected double lambda_WS; protected boolean quadraticLossPos = false; protected boolean quadraticLossNeg = false; boolean shrinked; protected double epsilon_pos = 0.0d; protected double epsilon_neg = 0.0d; private int max_iterations = 100000; protected int working_set_size = 10; protected int parameters_working_set_size = 10; // was set in parameters protected double is_zero = 1e-10; protected int shrink_const = 50; protected double C = 1.0d; protected double[] cPos; protected double[] cNeg; protected double descend = 1e-15; MinHeap heap_min; MaxHeap heap_max; protected QuadraticProblem qp; private Operator paramOperator; private RandomGenerator randomGenerator; public SVM() {} /** * class constructor. Throws an operator exception if a non-optional parameter was not set and * has no default value. */ public SVM(Operator paramOperator, Kernel new_kernel, SVMExamples new_examples, com.rapidminer.example.ExampleSet rapidMinerExamples, RandomGenerator randomGenerator) throws UndefinedParameterError { this.paramOperator = paramOperator; the_examples = new_examples; this.randomGenerator = randomGenerator; max_iterations = paramOperator.getParameterAsInt(AbstractMySVMLearner.PARAMETER_MAX_ITERATIONS); convergence_epsilon = paramOperator.getParameterAsDouble(AbstractMySVMLearner.PARAMETER_CONVERGENCE_EPSILON); quadraticLossPos = paramOperator.getParameterAsBoolean(JMySVMLearner.PARAMETER_QUADRATIC_LOSS_POS); quadraticLossNeg = paramOperator.getParameterAsBoolean(JMySVMLearner.PARAMETER_QUADRATIC_LOSS_NEG); cPos = new double[rapidMinerExamples.size()]; cNeg = new double[rapidMinerExamples.size()]; Attribute weightAttribute = rapidMinerExamples.getAttributes().getWeight(); if (weightAttribute != null) { Iterator<com.rapidminer.example.Example> reader = rapidMinerExamples.iterator(); int index = 0; while (reader.hasNext()) { com.rapidminer.example.Example example = reader.next(); cPos[index] = cNeg[index] = example.getValue(weightAttribute); index++; } if (paramOperator.getParameterAsBoolean(JMySVMLearner.PARAMETER_BALANCE_COST)) { logWarning("Since the example set contains a weight attribute, the parameter balance_cost will be ignored."); } logln(1, "Use defined weight attribute for example weights."); } else { Attribute weightPosAttribute = rapidMinerExamples.getAttributes().getSpecial("weight_pos"); Attribute weightNegAttribute = rapidMinerExamples.getAttributes().getSpecial("weight_neg"); if ((weightPosAttribute != null) && (weightNegAttribute != null)) { Iterator<com.rapidminer.example.Example> reader = rapidMinerExamples.iterator(); int index = 0; while (reader.hasNext()) { com.rapidminer.example.Example example = reader.next(); cPos[index] = example.getValue(weightPosAttribute); cNeg[index] = example.getValue(weightNegAttribute); index++; } if (paramOperator.getParameterAsBoolean(JMySVMLearner.PARAMETER_BALANCE_COST)) { logWarning("Since the example set contains a weight attribute, the parameter balance_cost will be ignored."); } logln(1, "Use defined weight_pos and weight_neg attributes for example weights."); } else { double generalCpos = paramOperator.getParameterAsDouble(JMySVMLearner.PARAMETER_L_POS); double generalCneg = paramOperator.getParameterAsDouble(JMySVMLearner.PARAMETER_L_NEG); if (paramOperator.getParameterAsBoolean(JMySVMLearner.PARAMETER_BALANCE_COST)) { generalCpos *= the_examples.count_examples() / (2.0d * (the_examples.count_examples() - the_examples.count_pos_examples())); generalCneg *= ((the_examples.count_examples()) / (2.0d * the_examples.count_pos_examples())); } for (int i = 0; i < cPos.length; i++) { cPos[i] = generalCpos; cNeg[i] = generalCneg; } } } this.C = paramOperator.getParameterAsDouble(AbstractMySVMLearner.PARAMETER_C); double epsilonValue = paramOperator.getParameterAsDouble(JMySVMLearner.PARAMETER_EPSILON); if (epsilonValue != -1) { epsilon_pos = epsilon_neg = epsilonValue; } else { epsilon_pos = paramOperator.getParameterAsDouble(JMySVMLearner.PARAMETER_EPSILON_PLUS); epsilon_neg = paramOperator.getParameterAsDouble(JMySVMLearner.PARAMETER_EPSILON_MINUS); } }; /** * Init the SVM * * @param new_kernel * new kernel function. * @param new_examples * the data container */ @Override public void init(Kernel new_kernel, SVMExamples new_examples) { the_kernel = new_kernel; the_examples = new_examples; examples_total = the_examples.count_examples(); parameters_working_set_size = working_set_size; if (this.C <= 0.0d) { this.C = 0.0d; for (int i = 0; i < examples_total; i++) { this.C += the_kernel.calculate_K(i, i); } ; this.C = examples_total / this.C; logln(3, "C set to " + this.C); } if (cPos != null) { for (int i = 0; i < cPos.length; i++) { cPos[i] *= this.C; cNeg[i] *= this.C; } } lambda_factor = 1.0; lambda_eq = 0; target_count = 0; sum_alpha = 0; feasible_epsilon = convergence_epsilon; alphas = the_examples.get_alphas(); ys = the_examples.get_ys(); }; /** * Train the SVM */ @Override public void train() { if (examples_total <= 0) { // exception? the_examples.set_b(Double.NaN); return; } if (examples_total == 1) { the_examples.set_b(ys[0]); return; } target_count = 0; shrinked = false; init_optimizer(); init_working_set(); int iteration = 0; boolean converged = false; M: while (iteration < max_iterations) { iteration++; logln(4, "optimizer iteration " + iteration); // log(3,"."); optimize(); put_optimizer_values(); converged = convergence(); if (converged) { logln(3, ""); // dots project_to_constraint(); if (shrinked) { // check convergence for all alphas logln(2, "***** Checking convergence for all variables"); reset_shrinked(); converged = convergence(); } ; if (converged) { logln(1, "*** Convergence"); break M; } ; // set variables free again shrink_const += 10; target_count = 0; for (int i = 0; i < examples_total; i++) { at_bound[i] = 0; } ; } ; shrink(); calculate_working_set(); update_working_set(); } ; int i; if ((iteration >= max_iterations) && (!converged)) { logln(1, "*** No convergence: Time up."); if (shrinked) { // set sums for all variables for statistics reset_shrinked(); } ; } ; // calculate b double new_b = 0; int new_b_count = 0; for (i = 0; i < examples_total; i++) { if ((alphas[i] - cNeg[i] < -is_zero) && (alphas[i] > is_zero)) { new_b += ys[i] - sum[i] - epsilon_neg; new_b_count++; } else if ((alphas[i] + cPos[i] > is_zero) && (alphas[i] < -is_zero)) { new_b += ys[i] - sum[i] + epsilon_pos; new_b_count++; } ; } ; if (new_b_count > 0) { the_examples.set_b(new_b / new_b_count); } else { // unlikely for (i = 0; i < examples_total; i++) { if ((alphas[i] < is_zero) && (alphas[i] > -is_zero)) { new_b += ys[i] - sum[i]; new_b_count++; } ; } ; if (new_b_count > 0) { the_examples.set_b(new_b / new_b_count); } else { // even unlikelier for (i = 0; i < examples_total; i++) { new_b += ys[i] - sum[i]; new_b_count++; } ; the_examples.set_b(new_b / new_b_count); } ; } ; // if(verbosity>= 2){ logln(2, "Done training: " + iteration + " iterations."); // if(verbosity >= 2){ double now_target = 0; double now_target_dummy = 0; for (i = 0; i < examples_total; i++) { now_target_dummy = sum[i] / 2 - ys[i]; if (is_alpha_neg(i)) { now_target_dummy += epsilon_pos; } else { now_target_dummy -= epsilon_neg; } ; now_target += alphas[i] * now_target_dummy; } ; logln(2, "Target function: " + now_target); // }; // }; print_statistics(); exit_optimizer(); }; /** * print statistics about result */ protected void print_statistics() { int dim = the_examples.get_dim(); int i, j; double alpha; double[] x; int svs = 0; int bsv = 0; double mae = 0; double mse = 0; int countpos = 0; int countneg = 0; double y; double prediction; double min_lambda = Double.MAX_VALUE; double b = the_examples.get_b(); for (i = 0; i < examples_total; i++) { if (lambda(i) < min_lambda) { min_lambda = lambda(i); } ; y = ys[i]; prediction = sum[i] + b; mae += Math.abs(y - prediction); mse += (y - prediction) * (y - prediction); alpha = alphas[i]; if (y < prediction - epsilon_pos) { countpos++; } else if (y > prediction + epsilon_neg) { countneg++; } ; if (alpha != 0) { svs++; if ((alpha == cPos[i]) || (alpha == -cNeg[i])) { bsv++; } ; } ; } ; mae /= examples_total; mse /= examples_total; min_lambda = -min_lambda; logln(1, "Error on KKT is " + min_lambda); logln(1, svs + " SVs"); logln(1, bsv + " BSVs"); logln(1, "MAE " + mae); logln(1, "MSE " + mse); logln(1, countpos + " pos loss"); logln(1, countneg + " neg loss"); // if(verbosity >= 2){ // print hyperplane double[] w = new double[dim]; for (j = 0; j < dim; j++) { w[j] = 0; } for (i = 0; i < examples_total; i++) { x = the_examples.get_example(i).toDense(dim); alpha = alphas[i]; for (j = 0; j < dim; j++) { w[j] += alpha * x[j]; } ; } ; // double[] Exp = the_examples.Exp; // double[] Dev = the_examples.Dev; // if(Exp != null){ // for(j=0;j<dim;j++){ // if(Dev[j] != 0){ // w[j] /= Dev[j]; // }; // if(0 != Dev[dim]){ // w[j] *= Dev[dim]; // }; // b -= w[j]*Exp[j]; // }; // b += Exp[dim]; // }; // logln(2," "); for (j = 0; j < dim; j++) { logln(2, "w[" + j + "] = " + w[j]); } ; logln(2, "b = " + b); if (dim == 1) { logln(2, "y = " + w[0] + "*x+" + b); } ; // }; }; /** Return the weights of the features. */ @Override public double[] getWeights() { int dim = the_examples.get_dim(); double[] w = new double[dim]; for (int j = 0; j < dim; j++) { w[j] = 0; } for (int i = 0; i < examples_total; i++) { double[] x = the_examples.get_example(i).toDense(dim); double alpha = alphas[i]; for (int j = 0; j < dim; j++) { w[j] += alpha * x[j]; } } return w; } /** Returns the value of b. */ @Override public double getB() { return the_examples.get_b(); } /** * Gets the complexity constant of the svm. */ public double getC() { return C; } /** * init the optimizer */ protected void init_optimizer() { which_alpha = new boolean[working_set_size]; primal = new double[working_set_size]; sum = new double[examples_total]; at_bound = new int[examples_total]; // init variables if (working_set_size > examples_total) { working_set_size = examples_total; } qp = new QuadraticProblemSMO(is_zero / 100, convergence_epsilon / 100, working_set_size * working_set_size); qp.set_n(working_set_size); // reserve workspace for calculate_working_set working_set = new int[working_set_size]; heap_max = new MaxHeap(0); heap_min = new MinHeap(0); // if(the_examples.Dev != null){ // double dev = the_examples.Dev[the_examples.get_dim()]; // if(dev != 0){ // epsilon_pos /= dev; // epsilon_neg /= dev; // }; // }; int i; for (i = 0; i < working_set_size; i++) { qp.l[i] = 0; // -is_zero; } ; if (quadraticLossPos) { for (i = 0; i < cPos.length; i++) { cPos[i] = Double.MAX_VALUE; } } ; if (quadraticLossNeg) { for (i = 0; i < cNeg.length; i++) { cNeg[i] = Double.MAX_VALUE; } } ; for (i = 0; i < examples_total; i++) { alphas[i] = 0.0; } ; lambda_WS = 0; to_shrink = 0; qp.set_n(working_set_size); }; /** * exit the optimizer */ protected void exit_optimizer() { qp = null; }; /** * shrink the variables */ protected void shrink() { // move shrinked examples to back if (to_shrink > examples_total / 10) { int i; int last_pos = examples_total; if (last_pos > working_set_size) { for (i = 0; i < last_pos; i++) { if (at_bound[i] >= shrink_const) { // shrink i sum_alpha += alphas[i]; last_pos--; the_examples.swap(i, last_pos); the_kernel.swap(i, last_pos); sum[i] = sum[last_pos]; at_bound[i] = at_bound[last_pos]; if (last_pos <= working_set_size) { break; } ; } ; } ; to_shrink = 0; shrinked = true; if (last_pos < examples_total) { examples_total = last_pos; the_kernel.set_examples_size(examples_total); } ; } ; logln(4, "shrinked to " + examples_total + " variables"); } ; }; /** * reset the shrinked variables */ protected void reset_shrinked() { int old_ex_tot = examples_total; target_count = 0; examples_total = the_examples.count_examples(); the_kernel.set_examples_size(examples_total); // unshrink, recalculate sum for all variables int i, j; // reset all sums for (i = old_ex_tot; i < examples_total; i++) { sum[i] = 0; at_bound[i] = 0; } ; double alpha; double[] kernel_row; for (i = 0; i < examples_total; i++) { alpha = alphas[i]; if (alpha != 0) { kernel_row = the_kernel.get_row(i); for (j = old_ex_tot; j < examples_total; j++) { sum[j] += alpha * kernel_row[j]; } ; } ; } ; sum_alpha = 0; shrinked = false; logln(5, "Resetting shrinked from " + old_ex_tot + " to " + examples_total); }; /** * Project variables to constraints */ protected void project_to_constraint() { // project alphas to match the constraint double alpha_sum = sum_alpha; int SVcount = 0; double alpha; int i; for (i = 0; i < examples_total; i++) { alpha = alphas[i]; alpha_sum += alpha; if (((alpha > is_zero) && (alpha - cNeg[i] < -is_zero)) || ((alpha < -is_zero) && (alpha + cPos[i] > is_zero))) { SVcount++; } ; } ; if (SVcount > 0) { // project alpha_sum /= SVcount; for (i = 0; i < examples_total; i++) { alpha = alphas[i]; if (((alpha > is_zero) && (alpha - cNeg[i] < -is_zero)) || ((alpha < -is_zero) && (alpha + cPos[i] > is_zero))) { alphas[i] -= alpha_sum; } ; } ; } ; }; /** * Calculates the working set * * @exception Exception * on any error */ protected void calculate_working_set() { // reset WSS if (working_set_size < parameters_working_set_size) { working_set_size = parameters_working_set_size; if (working_set_size > examples_total) { working_set_size = examples_total; } } ; heap_min.init(working_set_size / 2); heap_max.init(working_set_size / 2 + working_set_size % 2); int i = 0; double sort_value; double the_nabla; boolean is_feasible; int j; while (i < examples_total) { is_feasible = feasible(i); if (is_feasible) { the_nabla = nabla(i); if (is_alpha_neg(i)) { sort_value = -the_nabla; // - : maximum inconsistency // approach } else { sort_value = the_nabla; } ; // add to heaps heap_min.add(sort_value, i); heap_max.add(sort_value, i); } ; i++; } ; int[] new_ws = heap_min.get_values(); working_set_size = 0; int pos; j = heap_min.size(); for (i = 0; i < j; i++) { working_set[working_set_size] = new_ws[i]; working_set_size++; } ; pos = working_set_size; new_ws = heap_max.get_values(); j = heap_max.size(); for (i = 0; i < j; i++) { working_set[working_set_size] = new_ws[i]; working_set_size++; } ; if ((!heap_min.empty()) && (!heap_max.empty())) { if (heap_min.top_value() >= heap_max.top_value()) { // there could be the same values in the min- and maxheap, // sort them out (this is very unlikely) j = 0; i = 0; while (i < pos) { // working_set[i] also in max-heap? j = pos; while ((j < working_set_size) && (working_set[j] != working_set[i])) { j++; } ; if (j < working_set_size) { // working_set[i] equals working_set[j] // remove j from WS working_set[j] = working_set[working_set_size - 1]; working_set_size--; } else { i++; } ; } ; } ; } ; if (target_count > 0) { // convergence error on last iteration? // some more tests on WS // unlikely to happen, so speed isn't so important // are all variables at the bound? int pos_abs; boolean bounded_pos = true; boolean bounded_neg = true; pos = 0; double alpha; while ((pos < working_set_size) && (bounded_pos || bounded_neg)) { pos_abs = working_set[pos]; alpha = alphas[pos_abs]; if (is_alpha_neg(pos_abs)) { if (alpha - cNeg[pos_abs] < -is_zero) { bounded_pos = false; } ; if (alpha > is_zero) { bounded_neg = false; } ; } else { if (alpha + cNeg[pos_abs] > is_zero) { bounded_neg = false; } ; if (alpha < -is_zero) { bounded_pos = false; } ; } ; pos++; } ; if (bounded_pos) { // all alphas are at upper bound // need alpha that can be moved upward // use alpha with smallest lambda double max_lambda = Double.MAX_VALUE; int max_pos = examples_total; for (pos_abs = 0; pos_abs < examples_total; pos_abs++) { alpha = alphas[pos_abs]; if (is_alpha_neg(pos_abs)) { if (alpha - cNeg[pos_abs] < -is_zero) { if (lambda(pos_abs) < max_lambda) { max_lambda = lambda(pos_abs); max_pos = pos_abs; } ; } ; } else { if (alpha < -is_zero) { if (lambda(pos_abs) < max_lambda) { max_lambda = lambda(pos_abs); max_pos = pos_abs; } ; } ; } ; } ; if (max_pos < examples_total) { if (working_set_size < parameters_working_set_size) { working_set_size++; } ; working_set[working_set_size - 1] = max_pos; } ; } else if (bounded_neg) { // all alphas are at lower bound // need alpha that can be moved downward // use alpha with smallest lambda double max_lambda = Double.MAX_VALUE; int max_pos = examples_total; for (pos_abs = 0; pos_abs < examples_total; pos_abs++) { alpha = alphas[pos_abs]; if (is_alpha_neg(pos_abs)) { if (alpha > is_zero) { if (lambda(pos_abs) < max_lambda) { max_lambda = lambda(pos_abs); max_pos = pos_abs; } ; } ; } else { if (alpha + cNeg[pos_abs] > is_zero) { if (lambda(pos_abs) < max_lambda) { max_lambda = lambda(pos_abs); max_pos = pos_abs; } ; } ; } ; } ; if (max_pos < examples_total) { if (working_set_size < parameters_working_set_size) { working_set_size++; } ; working_set[working_set_size - 1] = max_pos; } ; } ; } ; if ((working_set_size < parameters_working_set_size) && (working_set_size < examples_total)) { // use full working set pos = (int) (randomGenerator.nextDouble() * examples_total); int ok; while ((working_set_size < parameters_working_set_size) && (working_set_size < examples_total)) { // add pos into WS if it isn't already ok = 1; for (i = 0; i < working_set_size; i++) { if (working_set[i] == pos) { ok = 0; i = working_set_size; } ; } ; if (1 == ok) { working_set[working_set_size] = pos; working_set_size++; } ; pos = (pos + 1) % examples_total; } ; } ; int ipos; for (ipos = 0; ipos < working_set_size; ipos++) { which_alpha[ipos] = is_alpha_neg(working_set[ipos]); } ; }; /** * Updates the working set */ protected void update_working_set() { // setup subproblem int i, j; int pos_i, pos_j; double[] kernel_row; double sum_WS; boolean[] my_which_alpha = which_alpha; for (pos_i = 0; pos_i < working_set_size; pos_i++) { i = working_set[pos_i]; // put row sort_i in hessian kernel_row = the_kernel.get_row(i); sum_WS = 0; // for(pos_j=0;pos_j<working_set_size;pos_j++){ for (pos_j = 0; pos_j < pos_i; pos_j++) { j = working_set[pos_j]; // put all elements K(i,j) in hessian, where j in WS if (((!my_which_alpha[pos_j]) && (!my_which_alpha[pos_i])) || ((my_which_alpha[pos_j]) && (my_which_alpha[pos_i]))) { // both i and j positive or negative (qp.H)[pos_i * working_set_size + pos_j] = kernel_row[j]; (qp.H)[pos_j * working_set_size + pos_i] = kernel_row[j]; } else { // one of i and j positive, one negative (qp.H)[pos_i * working_set_size + pos_j] = -kernel_row[j]; (qp.H)[pos_j * working_set_size + pos_i] = -kernel_row[j]; } ; } ; for (pos_j = 0; pos_j < working_set_size; pos_j++) { j = working_set[pos_j]; sum_WS += alphas[j] * kernel_row[j]; } ; // set main diagonal (qp.H)[pos_i * working_set_size + pos_i] = kernel_row[i]; // linear and box constraints if (!my_which_alpha[pos_i]) { // alpha (qp.A)[pos_i] = -1; // lin(alpha) = y_i+eps-sum_{i not in WS} alpha_i K_{ij} // = y_i+eps-sum_i+sum_{i in WS} (qp.c)[pos_i] = ys[i] + epsilon_pos - sum[i] + sum_WS; primal[pos_i] = -alphas[i]; (qp.u)[pos_i] = cPos[i]; } else { // alpha^* (qp.A)[pos_i] = 1; (qp.c)[pos_i] = -ys[i] + epsilon_neg + sum[i] - sum_WS; primal[pos_i] = alphas[i]; (qp.u)[pos_i] = cNeg[i]; } ; } ; if (quadraticLossNeg) { for (pos_i = 0; pos_i < working_set_size; pos_i++) { i = working_set[pos_i]; if (my_which_alpha[pos_i]) { (qp.H)[pos_i * (working_set_size + 1)] += 1 / cNeg[i]; (qp.u)[pos_i] = Double.MAX_VALUE; } ; } ; } ; if (quadraticLossPos) { for (pos_i = 0; pos_i < working_set_size; pos_i++) { i = working_set[pos_i]; if (!my_which_alpha[pos_i]) { (qp.H)[pos_i * (working_set_size + 1)] += 1 / cPos[i]; (qp.u)[pos_i] = Double.MAX_VALUE; } ; } ; } ; }; /** * Initialises the working set * * @exception Exception * on any error */ protected void init_working_set() { // calculate sum int i, j; project_to_constraint(); // skip kernel calculation as all alphas = 0 for (i = 0; i < examples_total; i++) { sum[i] = 0; at_bound[i] = 0; } ; // first working set is random j = 0; i = 0; while ((i < working_set_size) && (j < examples_total)) { working_set[i] = j; if (is_alpha_neg(j)) { which_alpha[i] = true; } else { which_alpha[i] = false; } ; i++; j++; } ; update_working_set(); }; /** * Calls the optimizer */ protected abstract void optimize(); /** * Stores the optimizer results */ protected void put_optimizer_values() { // update nabla, sum, examples. // sum[i] += (primal_j^*-primal_j-alpha_j^*+alpha_j)K(i,j) // check for |nabla| < is_zero (nabla <-> nabla*) int i = 0; int j = 0; int pos_i; double the_new_alpha; double[] kernel_row; double alpha_diff; double my_sum[] = sum; pos_i = working_set_size; while (pos_i > 0) { pos_i--; if (which_alpha[pos_i]) { the_new_alpha = primal[pos_i]; } else { the_new_alpha = -primal[pos_i]; } ; // next three statements: keep this order! i = working_set[pos_i]; alpha_diff = the_new_alpha - alphas[i]; alphas[i] = the_new_alpha; if (alpha_diff != 0) { // update sum ( => nabla) kernel_row = the_kernel.get_row(i); for (j = examples_total - 1; j >= 0; j--) { my_sum[j] += alpha_diff * kernel_row[j]; } ; } ; } ; }; /** * Checks if the optimization converged * * @return boolean true optimzation if converged */ protected boolean convergence() { double the_lambda_eq = 0; int total = 0; double alpha_sum = 0; double alpha = 0; int i; boolean result = true; // actual convergence-test total = 0; alpha_sum = 0; for (i = 0; i < examples_total; i++) { alpha = alphas[i]; alpha_sum += alpha; if ((alpha > is_zero) && (alpha - cNeg[i] < -is_zero)) { // alpha^* = - nabla the_lambda_eq += -nabla(i); // all_ys[i]-epsilon_neg-sum[i]; total++; } else if ((alpha < -is_zero) && (alpha + cPos[i] > is_zero)) { // alpha = nabla the_lambda_eq += nabla(i); // all_ys[i]+epsilon_pos-sum[i]; total++; } ; } ; logln(4, "lambda_eq = " + (the_lambda_eq / total)); if (total > 0) { lambda_eq = the_lambda_eq / total; } else { // keep WS lambda_eq lambda_eq = lambda_WS; // (lambda_eq+4*lambda_WS)/5; logln(4, "*** no SVs in convergence(), lambda_eq = " + lambda_eq + "."); } ; if (target_count > 2) { // estimate lambda from WS if (target_count > 20) { // desperate attempt to get good lambda! lambda_eq = ((40 - target_count) * lambda_eq + (target_count - 20) * lambda_WS) / 20; logln(5, "Re-Re-calculated lambda from WS: " + lambda_eq); if (target_count > 40) { // really desperate, kick one example out! i = working_set[target_count % working_set_size]; if (is_alpha_neg(i)) { lambda_eq = -nabla(i); } else { lambda_eq = nabla(i); } ; logln(5, "set lambda_eq to nabla(" + i + "): " + lambda_eq); } ; } else { lambda_eq = lambda_WS; logln(5, "Re-calculated lambda_eq from WS: " + lambda_eq); } ; } ; // check linear constraint if (java.lang.Math.abs(alpha_sum + sum_alpha) > convergence_epsilon) { // equality constraint violated logln(4, "No convergence: equality constraint violated: |" + (alpha_sum + sum_alpha) + "| >> 0"); project_to_constraint(); result = false; } ; i = 0; while ((i < examples_total) && (result != false)) { if (lambda(i) >= -convergence_epsilon) { i++; } else { result = false; } ; } ; return result; }; protected abstract double nabla(int i); /** * lagrangion multiplier of variable i * * @param i * variable index * @return lambda */ protected double lambda(int i) { double alpha; double result; if (is_alpha_neg(i)) { result = -java.lang.Math.abs(nabla(i) + lambda_eq); } else { result = -java.lang.Math.abs(nabla(i) - lambda_eq); } ; // default = not at bound alpha = alphas[i]; if (alpha > is_zero) { // alpha* if (alpha - cNeg[i] >= -is_zero) { // upper bound active result = -lambda_eq - nabla(i); } ; } else if (alpha >= -is_zero) { // lower bound active if (is_alpha_neg(i)) { result = nabla(i) + lambda_eq; } else { result = nabla(i) - lambda_eq; } ; } else if (alpha + cPos[i] <= is_zero) { // upper bound active result = lambda_eq - nabla(i); } ; return result; }; protected boolean feasible(int i) { boolean is_feasible = true; double alpha = alphas[i]; double the_lambda = lambda(i); if (alpha - cNeg[i] >= -is_zero) { // alpha* at upper bound if (the_lambda >= 0) { at_bound[i]++; if (at_bound[i] == shrink_const) { to_shrink++; } } else { at_bound[i] = 0; } ; } else if ((alpha <= is_zero) && (alpha >= -is_zero)) { // lower bound active if (the_lambda >= 0) { at_bound[i]++; if (at_bound[i] == shrink_const) { to_shrink++; } } else { at_bound[i] = 0; } ; } else if (alpha + cPos[i] <= is_zero) { // alpha at upper bound if (the_lambda >= 0) { at_bound[i]++; if (at_bound[i] == shrink_const) { to_shrink++; } } else { at_bound[i] = 0; } ; } else { // not at bound at_bound[i] = 0; } ; if ((the_lambda >= feasible_epsilon) || (at_bound[i] >= shrink_const)) { is_feasible = false; } ; return is_feasible; } protected abstract boolean is_alpha_neg(int i); /** * log the output plus newline * * @param level * warning level * @param message * Message test */ protected void logln(int level, String message) { Level mappedLevel = WrapperLoggingHandler.LEVELS[RAPID_MINER_VERBOSITY[level - 1]]; if (paramOperator != null) { paramOperator.getLogger().log(mappedLevel, message); } else { LogService.getRoot().log(mappedLevel, message); } } protected void logWarning(String message) { paramOperator.getLogger().warning(message); } /** * predict values on the testset with model */ @Override public void predict(SVMExamples to_predict) { int i; double prediction; SVMExample sVMExample; // int size = the_examples.count_examples(); // IM 04/02/12 int size = to_predict.count_examples(); for (i = 0; i < size; i++) { sVMExample = to_predict.get_example(i); prediction = predict(sVMExample); to_predict.set_y(i, prediction); } ; logln(4, "Prediction generated"); }; public double predict(int i) { return predict(the_examples.get_example(i)); } /** * predict a single example */ @Override public double predict(SVMExample sVMExample) { int i; int[] sv_index; double[] sv_att; double the_sum = the_examples.get_b(); double alpha; for (i = 0; i < examples_total; i++) { alpha = alphas[i]; if (alpha != 0) { sv_index = the_examples.index[i]; sv_att = the_examples.atts[i]; the_sum += alpha * the_kernel.calculate_K(sv_index, sv_att, sVMExample.index, sVMExample.att); } ; } ; return the_sum; }; /** * check internal variables, for debugging only */ protected void check() { double tsum; int i, j; double s = 0; for (i = 0; i < examples_total; i++) { s += alphas[i]; tsum = 0; for (j = 0; j < the_examples.count_examples(); j++) { tsum += alphas[j] * the_kernel.calculate_K(i, j); } ; if (Math.abs(tsum - sum[i]) > is_zero) { logln(1, "ERROR: sum[" + i + "] off by " + (tsum - sum[i])); // throw(new Exception("ERROR: sum["+i+"] off by // "+(tsum-sum[i]))); // System.exit(1); } ; } ; if (Math.abs(s + sum_alpha) > is_zero) { logln(1, "ERROR: sum_alpha is off by " + (s + sum_alpha)); // throw(new Exception("ERROR: sum_alpha is off by // "+(s+sum_alpha))); // System.exit(1); } ; }; /** * Returns a double array of estimated performance values. These are accuracy, precision and * recall. Works only for classification SVMs. */ public double[] getXiAlphaEstimation(Kernel kernel) { double r_delta = 0.0d; for (int j = 0; j < examples_total; j++) { double norm_x = kernel.calculate_K(j, j); for (int i = 0; i < examples_total; i++) { double r_current = norm_x - kernel.calculate_K(i, j); if (r_current > r_delta) { r_delta = r_current; } } } int total_pos = 0; int total_neg = 0; int estim_pos = 0; int estim_neg = 0; double xi = 0.0d; for (int i = 0; i < examples_total; i++) { double alpha = the_examples.get_alpha(i); double prediction = predict(i); double y = the_examples.get_y(i); if (y > 0) { if (prediction > 1) { xi = 0; } else { xi = 1 - prediction; } ; if (2 * alpha * r_delta + xi >= 1) { estim_pos++; } ; total_pos++; } else { if (prediction < -1) { xi = 0; } else { xi = 1 + prediction; } ; if (2 * (-alpha) * r_delta + xi >= 1) { estim_neg++; } ; total_neg++; } ; } ; double[] result = new double[3]; result[0] = 1.0d - (double) (estim_pos + estim_neg) / (double) (total_pos + total_neg); result[1] = (double) (total_pos - estim_pos) / (double) (total_pos - estim_pos + estim_neg); result[2] = 1.0d - (double) estim_pos / (double) total_pos; return result; } };
agpl-3.0
cojen/Tupl
src/main/java/org/cojen/tupl/repl/SnapshotScore.java
1488
/* * Copyright (C) 2017 Cojen.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.cojen.tupl.repl; import java.util.concurrent.CountDownLatch; /** * * * @author Brian S O'Neill */ final class SnapshotScore extends CountDownLatch implements Comparable<SnapshotScore> { final Peer mPeer; int mActiveSessions; float mWeight; SnapshotScore(Peer peer) { super(1); mPeer = peer; } void snapshotScoreReply(int activeSessions, float weight) { mActiveSessions = activeSessions; mWeight = weight; countDown(); } @Override public int compareTo(SnapshotScore other) { int cmp = Integer.compare(mActiveSessions, other.mActiveSessions); if (cmp == 0) { cmp = Float.compare(mWeight, other.mWeight); } return cmp; } }
agpl-3.0
MiguelSMendoza/Kunagi
WEB-INF/classes/scrum/server/collaboration/CommentDao.java
2317
/* * Copyright 2011 Witoslaw Koczewsi <wi@koczewski.de>, Artjom Kochtchi * * 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 General Public License along with this program. If not, see * <http://www.gnu.org/licenses/>. */ package scrum.server.collaboration; import ilarkesto.base.AFactoryCache; import ilarkesto.base.Cache; import ilarkesto.core.base.Str; import ilarkesto.core.time.DateAndTime; import ilarkesto.fp.Predicate; import ilarkesto.persistence.AEntity; import java.util.Set; public class CommentDao extends GCommentDao { @Override public void clearCaches() { super.clearCaches(); commentsByParentIdCache.clear(); } public Set<Comment> getPublishedCommentsByParent(final AEntity parent) { return getEntities(new Predicate<Comment>() { @Override public boolean test(Comment c) { return c.isPublished() && c.isParent(parent); } }); } private Cache<String, Set<Comment>> commentsByParentIdCache = new AFactoryCache<String, Set<Comment>>() { @Override public Set<Comment> create(final String parentId) { return getEntities(new Predicate<Comment>() { @Override public boolean test(Comment e) { return e.getParent().getId().equals(parentId); } }); } }; public Set<Comment> getCommentsByParentId(final String parentId) { return commentsByParentIdCache.get(parentId); } public Comment postComment(AEntity entity, String text, String name, String email, boolean publish) { assert entity != null; if (Str.isBlank(name)) name = "anonymous"; Comment comment = newEntityInstance(); comment.setParent(entity); comment.setText(text); comment.setAuthorName(name); comment.setAuthorEmail(email); comment.setDateAndTime(DateAndTime.now()); comment.setPublished(publish); saveEntity(comment); return comment; } }
agpl-3.0
opensourceBIM/BIMserver
PluginBase/generated/org/bimserver/models/ifc4/impl/IfcFillAreaStyleImpl.java
4133
/** * 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.IfcFillAreaStyle; import org.bimserver.models.ifc4.IfcFillStyleSelect; import org.bimserver.models.ifc4.Tristate; 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 Fill Area Style</b></em>'. * <!-- end-user-doc --> * <p> * The following features are implemented: * </p> * <ul> * <li>{@link org.bimserver.models.ifc4.impl.IfcFillAreaStyleImpl#getFillStyles <em>Fill Styles</em>}</li> * <li>{@link org.bimserver.models.ifc4.impl.IfcFillAreaStyleImpl#getModelorDraughting <em>Modelor Draughting</em>}</li> * </ul> * * @generated */ public class IfcFillAreaStyleImpl extends IfcPresentationStyleImpl implements IfcFillAreaStyle { /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ protected IfcFillAreaStyleImpl() { super(); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override protected EClass eStaticClass() { return Ifc4Package.Literals.IFC_FILL_AREA_STYLE; } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @SuppressWarnings("unchecked") @Override public EList<IfcFillStyleSelect> getFillStyles() { return (EList<IfcFillStyleSelect>) eGet(Ifc4Package.Literals.IFC_FILL_AREA_STYLE__FILL_STYLES, true); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public Tristate getModelorDraughting() { return (Tristate) eGet(Ifc4Package.Literals.IFC_FILL_AREA_STYLE__MODELOR_DRAUGHTING, true); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void setModelorDraughting(Tristate newModelorDraughting) { eSet(Ifc4Package.Literals.IFC_FILL_AREA_STYLE__MODELOR_DRAUGHTING, newModelorDraughting); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public void unsetModelorDraughting() { eUnset(Ifc4Package.Literals.IFC_FILL_AREA_STYLE__MODELOR_DRAUGHTING); } /** * <!-- begin-user-doc --> * <!-- end-user-doc --> * @generated */ @Override public boolean isSetModelorDraughting() { return eIsSet(Ifc4Package.Literals.IFC_FILL_AREA_STYLE__MODELOR_DRAUGHTING); } } //IfcFillAreaStyleImpl
agpl-3.0
SilverDav/Silverpeas-Core
core-web/src/main/java/org/silverpeas/core/web/util/viewgenerator/html/tabs/TabbedPaneTag.java
2236
/* * Copyright (C) 2000 - 2021 Silverpeas * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Affero General Public License as * published by the Free Software Foundation, either version 3 of the * License, or (at your option) any later version. * * As a special exception to the terms and conditions of version 3.0 of * the GPL, you may redistribute this Program in connection with Free/Libre * Open Source Software ("FLOSS") applications as described in Silverpeas's * FLOSS exception. You should have received a copy of the text describing * the FLOSS exception, and it is also available here: * "https://www.silverpeas.org/legal/floss_exception.html" * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Affero General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.silverpeas.core.web.util.viewgenerator.html.tabs; import java.io.IOException; import javax.servlet.jsp.JspException; import javax.servlet.jsp.tagext.TagSupport; import org.silverpeas.core.web.util.viewgenerator.html.GraphicElementFactory; public class TabbedPaneTag extends TagSupport { private static final long serialVersionUID = 2716176010690113590L; static final String TABBEDPANE_PAGE_ATT = "pageContextTabbedPane"; public int doEndTag() throws JspException { try { TabbedPane tabs = (TabbedPane) pageContext .getAttribute(TABBEDPANE_PAGE_ATT); pageContext.getOut().println(tabs.print()); } catch (IOException e) { throw new JspException("TabbedPane Tag", e); } return EVAL_PAGE; } public int doStartTag() throws JspException { GraphicElementFactory gef = (GraphicElementFactory) pageContext .getSession() .getAttribute(GraphicElementFactory.GE_FACTORY_SESSION_ATT); TabbedPane tabs = gef.getTabbedPane(); pageContext.setAttribute(TABBEDPANE_PAGE_ATT, tabs); return EVAL_BODY_INCLUDE; } }
agpl-3.0
nmpgaspar/PainlessProActive
src/Extensions/org/objectweb/proactive/extensions/calcium/statistics/Timer.java
3690
/* * ################################################################ * * 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 ProActive Team * http://proactive.inria.fr/team_members.htm * Contributor(s): * * ################################################################ * $$PROACTIVE_INITIAL_DEV$$ */ package org.objectweb.proactive.extensions.calcium.statistics; import java.io.Serializable; import java.lang.management.ManagementFactory; import java.lang.management.ThreadMXBean; public class Timer implements Serializable { private static final long serialVersionUID = 54L; long t; long accumulated; int numberActivatedTimes; boolean cpuTime; public Timer(boolean useCPUTime) { cpuTime = useCPUTime; reset(); } public Timer() { this(false); } /** * Starts the current timer. This method * resets the timer state. */ public void start() { reset(); } /** * Stops the current timer. * @return Accumulated elapsed time. */ public long stop() { if (t > 0) { accumulated += (getCurrentTime() - t); } t = -1; return accumulated; } /** * After the timer has been stoped, this method can * resume the counter. The new time will be agregated to * the previous time. */ public void resume() { t = getCurrentTime(); numberActivatedTimes++; } /** * Resets the timer state. */ private void reset() { t = getCurrentTime(); accumulated = 0; numberActivatedTimes = 1; } /** * @return The currently accumulated time of this timer. */ public long getTime() { if (t > 0) { return (accumulated + getCurrentTime()) - t; } return accumulated; } /** * @return Number of times this timer wast activated: the number * of times resume was called plus 1 (the inital start). */ public int getNumberOfActivatedTimes() { return numberActivatedTimes; } private long getCurrentTime() { if (!cpuTime) { return System.currentTimeMillis(); } ThreadMXBean tmb = ManagementFactory.getThreadMXBean(); if (tmb.isThreadCpuTimeSupported()) { if (!tmb.isThreadCpuTimeEnabled()) { tmb.setThreadCpuTimeEnabled(true); } return tmb.getCurrentThreadCpuTime() / 1000000; } return System.currentTimeMillis(); } }
agpl-3.0
torakiki/pdfsam
pdfsam-gui/src/test/java/org/pdfsam/ui/info/KeywordsTabTest.java
3776
/* * This file is part of the PDF Split And Merge source code * Created on 21/ago/2014 * Copyright 2017 by Sober Lemur S.a.s. di Vacondio Andrea (info@pdfsam.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 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.pdfsam.ui.info; import static org.junit.Assert.assertNotNull; import static org.mockito.ArgumentMatchers.any; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.timeout; import static org.mockito.Mockito.verify; import java.io.File; import org.junit.Rule; import org.junit.Test; import org.pdfsam.pdf.PdfDescriptorLoadingStatus; import org.pdfsam.pdf.PdfDocumentDescriptor; import org.pdfsam.test.ClearEventStudioRule; import org.pdfsam.test.InitializeJavaFxThreadRule; import org.pdfsam.ui.commons.ShowPdfDescriptorRequest; import org.sejda.model.pdf.PdfMetadataFields; import org.testfx.util.WaitForAsyncUtils; import javafx.beans.value.ChangeListener; import javafx.beans.value.ObservableValue; import javafx.scene.control.Labeled; import javafx.scene.control.ScrollPane; /** * @author Andrea Vacondio * */ public class KeywordsTabTest { @Rule public ClearEventStudioRule studio = new ClearEventStudioRule(); @Rule public InitializeJavaFxThreadRule javaFxThread = new InitializeJavaFxThreadRule(); @Test public void showRequest() { KeywordsTab victim = new KeywordsTab(); Labeled keywords = (Labeled) ((ScrollPane) victim.getContent()).getContent().lookup(".info-property-value"); assertNotNull(keywords); ChangeListener<? super String> listener = mock(ChangeListener.class); keywords.textProperty().addListener(listener); PdfDocumentDescriptor descriptor = PdfDocumentDescriptor.newDescriptorNoPassword(mock(File.class)); descriptor.putInformation(PdfMetadataFields.KEYWORDS, "test"); WaitForAsyncUtils.waitForAsyncFx(2000, () -> victim.requestShow(new ShowPdfDescriptorRequest(descriptor))); verify(listener, timeout(2000).times(1)).changed(any(ObservableValue.class), anyString(), eq("test")); } @Test public void onLoad() { KeywordsTab victim = new KeywordsTab(); Labeled keywords = (Labeled) ((ScrollPane) victim.getContent()).getContent().lookup(".info-property-value"); assertNotNull(keywords); ChangeListener<? super String> listener = mock(ChangeListener.class); keywords.textProperty().addListener(listener); PdfDocumentDescriptor descriptor = PdfDocumentDescriptor.newDescriptorNoPassword(mock(File.class)); WaitForAsyncUtils.waitForAsyncFx(2000, () -> victim.requestShow(new ShowPdfDescriptorRequest(descriptor))); descriptor.putInformation(PdfMetadataFields.KEYWORDS, "test"); descriptor.moveStatusTo(PdfDescriptorLoadingStatus.REQUESTED); descriptor.moveStatusTo(PdfDescriptorLoadingStatus.LOADING); descriptor.moveStatusTo(PdfDescriptorLoadingStatus.LOADED); verify(listener, timeout(2000).times(1)).changed(any(ObservableValue.class), anyString(), eq("test")); } }
agpl-3.0
uniteddiversity/mycollab
mycollab-dao/src/main/java/com/esofthead/mycollab/core/db/query/SearchFieldInfo.java
2028
/** * This file is part of mycollab-dao. * * mycollab-dao 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-dao 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-dao. If not, see <http://www.gnu.org/licenses/>. */ package com.esofthead.mycollab.core.db.query; import java.io.Serializable; /** * * @author MyCollab Ltd. * @since 4.0 * */ public class SearchFieldInfo implements Serializable { private static final long serialVersionUID = 1L; private String prefixOper; private Param param; private String compareOper; private Object value; private String paramClsName; public SearchFieldInfo() { } public SearchFieldInfo(String prefixOper, Param param, String compareOper, Object value) { this.prefixOper = prefixOper; this.param = param; this.compareOper = compareOper; this.value = value; this.paramClsName = param.getClass().getName(); } public String getPrefixOper() { return prefixOper; } public void setPrefixOper(String prefixOper) { this.prefixOper = prefixOper; } public Param getParam() { return param; } public void setParam(Param param) { this.param = param; } public Object getValue() { return value; } public void setValue(Object value) { this.value = value; } public String getCompareOper() { return compareOper; } public void setCompareOper(String compareOper) { this.compareOper = compareOper; } public String getParamClsName() { return paramClsName; } public void setParamClsName(String paramClsName) { this.paramClsName = paramClsName; } }
agpl-3.0
JLospinoso/dailyc
mogreet/src/test/java/net/lospi/mogreet/core/SendRequestTest.java
1993
package net.lospi.mogreet.core; import org.testng.annotations.BeforeMethod; import org.testng.annotations.Test; import static org.hamcrest.CoreMatchers.is; import static org.hamcrest.CoreMatchers.notNullValue; import static org.junit.Assert.assertThat; public class SendRequestTest { private String from; private String message; private String contentId; private String campaignId; private String to; @BeforeMethod public void setUp() { campaignId = "campaignId"; to = "to"; message = "message"; from = "from"; contentId = "contentId"; } @Test public void getCampaignId() { SendRequest underStudy = new SendRequest(campaignId, to, from, message, contentId); String result = underStudy.getCampaignId(); assertThat(result, is(campaignId)); } @Test public void getContentId() { SendRequest underStudy = new SendRequest(campaignId, to, from, message, contentId); String result = underStudy.getContentId(); assertThat(result, is(contentId)); } @Test public void getFrom() { SendRequest underStudy = new SendRequest(campaignId, to, from, message, contentId); String result = underStudy.getFrom(); assertThat(result, is(from)); } @Test public void getTo() { SendRequest underStudy = new SendRequest(campaignId, to, from, message, contentId); String result = underStudy.getTo(); assertThat(result, is(to)); } @Test public void canToString() { SendRequest underStudy = new SendRequest(campaignId, to, from, message, contentId); String result = underStudy.toString(); assertThat(result, is(notNullValue())); } @Test public void getMessage() { SendRequest underStudy = new SendRequest(campaignId, to, from, message, contentId); String result = underStudy.getMessage(); assertThat(result, is(message)); } }
agpl-3.0
nmc-probe/emulab-nome
www/wireless-stats/src/DatasetModel.java
4759
/* * Copyright (c) 2006-2007 University of Utah and the Flux Group. * * {{{EMULAB-LICENSE * * This file is part of the Emulab network testbed software. * * This file 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 file 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 file. If not, see <http://www.gnu.org/licenses/>. * * }}} */ import java.util.*; public class DatasetModel { final static int TYPE_NEW = 1; final static int TYPE_UNLOAD = 2; final static int TYPE_CUR_CHANGE = 3; private Hashtable datasetModels; private Dataset currentDataset; private String currentDatasetName; private MapDataModel currentModel; private Vector listeners; public DatasetModel() { this.datasetModels = new Hashtable(); this.currentModel = null; this.currentDataset = null; this.listeners = new Vector(); } public void setCurrentModel(String dsn) { Dataset d = (Dataset)datasetModels.get(dsn); MapDataModel mdm = d.model; if (mdm != null && mdm != currentModel) { this.currentModel = mdm; this.currentDataset = d; this.currentDatasetName = dsn; notifyModelListeners(TYPE_CUR_CHANGE,dsn); } } public MapDataModel getCurrentModel() { if (this.currentDataset == null) { // scan through our list and take the first one we find. for (Enumeration e1 = datasetModels.elements(); e1.hasMoreElements(); ) { this.currentDataset = (Dataset)e1.nextElement(); this.currentModel = this.currentDataset.model; this.currentDatasetName = this.currentDataset.name; } } return this.currentModel; } public String getCurrentDatasetName() { return this.currentDatasetName; } public Dataset getCurrentDataset() { if (this.currentDataset == null) { // scan through our list and take the first one we find. for (Enumeration e1 = datasetModels.elements(); e1.hasMoreElements(); ) { this.currentDataset = (Dataset)e1.nextElement(); this.currentModel = this.currentDataset.model; this.currentDatasetName = this.currentDataset.name; } } return this.currentDataset; } public void addDataset(String dsn,Dataset d) { datasetModels.put(dsn,d); notifyModelListeners(TYPE_NEW,dsn); } public void removeDataset(String dsn) { datasetModels.remove(dsn); notifyModelListeners(TYPE_UNLOAD,dsn); } public Dataset getDataset(String name) { return (Dataset)this.datasetModels.get(name); } public Vector getDatasetNames() { Vector retval = new Vector(); for (Enumeration e1 = this.datasetModels.keys(); e1.hasMoreElements(); ) { retval.add(e1.nextElement()); } return retval; } public Vector getDatasets() { Vector retval = new Vector(); for (Enumeration e1 = this.datasetModels.elements(); e1.hasMoreElements(); ) { retval.add(e1.nextElement()); } return retval; } public void addDatasetModelListener(DatasetModelListener dl) { if (!this.listeners.contains(dl)) { this.listeners.add(dl); } } public void removeDatasetModelListener(DatasetModelListener dl) { if (this.listeners.contains(dl)) { this.listeners.remove(dl); } } void notifyModelListeners(int type,String ds) { for (Enumeration e1 = listeners.elements(); e1.hasMoreElements(); ) { DatasetModelListener dl = (DatasetModelListener)e1.nextElement(); switch (type) { case TYPE_NEW: dl.newDataset(ds,this); break; case TYPE_UNLOAD: dl.datasetUnloaded(ds,this); break; case TYPE_CUR_CHANGE: dl.currentDatasetChanged(ds,this); break; default: break; } } } }
agpl-3.0
pku1001210910/JDeSurvey
jdsurvey-core/src/main/java/com/jd/survey/dao/settings/InvitationDAOImpl.java
5161
/*Copyright (C) 2014 JD Software, 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 com.jd.survey.dao.settings; import java.util.Arrays; import java.util.HashSet; import java.util.LinkedHashSet; import java.util.Set; import java.util.SortedSet; import java.util.TreeSet; import javax.persistence.EntityManager; import javax.persistence.NoResultException; import javax.persistence.PersistenceContext; import javax.persistence.Query; import org.skyway.spring.util.dao.AbstractJpaDao; import org.springframework.dao.DataAccessException; import org.springframework.stereotype.Repository; import org.springframework.transaction.annotation.Transactional; import com.jd.survey.dao.interfaces.settings.InvitationDAO; import com.jd.survey.domain.settings.Invitation; /** DAO implementation to handle persistence for object :Invitation */ @Repository("InvitationDAO") @Transactional public class InvitationDAOImpl extends AbstractJpaDao<Invitation> implements InvitationDAO { private final static Set<Class<?>> dataTypes = new HashSet<Class<?>>(Arrays.asList(new Class<?>[] { Invitation.class })); @PersistenceContext(unitName = "persistenceUnit") private EntityManager entityManager; public InvitationDAOImpl() { super(); } public EntityManager getEntityManager() { return entityManager; } public Set<Class<?>> getTypes() { return dataTypes; } @Override @Transactional public SortedSet<Invitation> findSurveyAll(Long surveyDefinitionId) throws DataAccessException { return findSurveyAll(surveyDefinitionId , -1, -1); } @Override @SuppressWarnings("unchecked") @Transactional public SortedSet<Invitation> findSurveyAll(Long surveyDefinitionId,int startResult, int maxRows) throws DataAccessException { Query query = createNamedQuery("Invitation.findSurveyAll", startResult,maxRows , surveyDefinitionId); return new TreeSet<Invitation>(query.getResultList()); } @Override @Transactional public Invitation findById(Long id) throws DataAccessException { try { Query query = createNamedQuery("Invitation.findById", -1, -1, id); return (Invitation) query.getSingleResult(); } catch (NoResultException nre) { return null; } } @Override @Transactional public Invitation findByUuid(String uuid) throws DataAccessException { try { Query query = createNamedQuery("Invitation.findByUuid", -1, -1, uuid); return (Invitation) query.getSingleResult(); } catch (NoResultException nre) { return null; } } @Override @Transactional public Long getSurveyCount(Long surveyDefinitionId) throws DataAccessException { try { Query query = createNamedQuery("Invitation.getSurveyCount",-1,-1,surveyDefinitionId); return (Long) query.getSingleResult(); } catch (NoResultException nre) { return null; } } @Override @Transactional public Long getSurveyOpenedCount(Long surveyDefinitionId) throws DataAccessException { try { Query query = createNamedQuery("Invitation.getSurveyOpenedCount",-1,-1, surveyDefinitionId); return (Long) query.getSingleResult(); } catch (NoResultException nre) { return null; } } @SuppressWarnings("unchecked") @Override @Transactional public SortedSet<Invitation> searchByFirstName(String firstName) throws DataAccessException { Query query = createNamedQuery("Invitation.searchByFirstName", -1, -1 , "%" + firstName +"%" ); return new TreeSet<Invitation>(query.getResultList()); } @SuppressWarnings("unchecked") @Override @Transactional public SortedSet<Invitation> searchByLastName(String lastName) throws DataAccessException { Query query = createNamedQuery("Invitation.searchByLastName", -1, -1 , "%" + lastName +"%" ); return new TreeSet<Invitation>(query.getResultList()); } @SuppressWarnings("unchecked") @Override @Transactional public SortedSet<Invitation> searchByFirstNameAndLastName(String firstName , String lastName) throws DataAccessException { Query query = createNamedQuery("Invitation.searchByFirstNameAndLastName", -1, -1 , "%" + firstName +"%" , "%" + lastName +"%"); return new TreeSet<Invitation>(query.getResultList()); } @SuppressWarnings("unchecked") @Override @Transactional public SortedSet<Invitation> searchByEmail(String email) throws DataAccessException { Query query = createNamedQuery("Invitation.searchByEmail", -1, -1 , "%" + email +"%" ); return new TreeSet<Invitation>(query.getResultList()); } public boolean canBeMerged(Invitation entity) { return true; } }
agpl-3.0
o2oa/o2oa
o2server/x_attendance_assemble_control/src/main/java/com/x/attendance/assemble/control/jaxrs/AttendanceSimpleJaxrsFilter.java
483
package com.x.attendance.assemble.control.jaxrs; import javax.servlet.annotation.WebFilter; import com.x.base.core.project.jaxrs.AnonymousCipherManagerUserJaxrsFilter; /** * web服务过滤器,将指定的URL定义为需要用户认证的服务,如果用户未登录,则无法访问该服务 */ @WebFilter(urlPatterns = { "/jaxrs/selfholidaysimple/*" }, asyncSupported = true) public class AttendanceSimpleJaxrsFilter extends AnonymousCipherManagerUserJaxrsFilter { }
agpl-3.0
alejandro-du/quizpro
src/ingswii/quizpro/biz/vo/ram/Convocatoria.java
3290
package ingswii.quizpro.biz.vo.ram; import java.io.Serializable; import java.util.List; import javax.persistence.Column; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.GenerationType; import javax.persistence.Id; import javax.persistence.JoinColumn; import javax.persistence.JoinTable; import javax.persistence.ManyToOne; import javax.persistence.OneToMany; import javax.persistence.Table; /** * * @author Alejandro */ @Entity @Table(name="convocatoria") public class Convocatoria implements Serializable { private static final long serialVersionUID = 1L; @Id @GeneratedValue(strategy = GenerationType.AUTO) @Column(name="con_id") private Long id; @Column(name="con_nombre") private String nombre; @Column(name="con_fecha_inicio") private String fechaInicio; @Column(name="con_fecha_fin") private String fechaFin; @Column(name="con_descripcion") private String descripcion; @Column(name="con_vacantes") private Integer vacantes; @ManyToOne @JoinColumn(name="exa_id") private Examen examen; @OneToMany @JoinTable(joinColumns=@JoinColumn(name="con_id"), inverseJoinColumns=@JoinColumn(name="pos_id")) private List<Postulante> postulantes; public void setId(Long id) { this.id = id; } public Long getId() { return id; } @Override public int hashCode() { int hash = 0; hash += (id != null ? id.hashCode() : 0); return hash; } @Override public boolean equals(Object object) { // TODO: Warning - this method won't work in the case the id fields are not set if (!(object instanceof Convocatoria)) { return false; } Convocatoria other = (Convocatoria) object; if ((this.id == null && other.id != null) || (this.id != null && !this.id.equals(other.id))) { return false; } return true; } @Override public String toString() { return "ingswii.quizpro.biz.vo.convocatoria.Convocatoria[id=" + id + "]"; } public String getNombre() { return nombre; } public void setNombre(String nombre) { this.nombre = nombre; } public String getFechaInicio() { return fechaInicio; } public void setFechaInicio(String fechaInicio) { this.fechaInicio = fechaInicio; } public String getFechaFin() { return fechaFin; } public void setFechaFin(String fechaFin) { this.fechaFin = fechaFin; } public List<Postulante> getPostulantes() { return postulantes; } public void setPostulantes(List<Postulante> postulantes) { this.postulantes = postulantes; } public String getDescripcion() { return descripcion; } public void setDescripcion(String descripcion) { this.descripcion = descripcion; } public Examen getExamen() { return examen; } public void setExamen(Examen examen) { this.examen = examen; } public Integer getVacantes() { return vacantes; } public void setVacantes(Integer vacantes) { this.vacantes = vacantes; } }
agpl-3.0
cfpio/callForPapers
src/test/java/io/cfp/multitenant/TenantFilterTest.java
2165
/* * Copyright (c) 2016 BreizhCamp * [http://breizhcamp.org] * * This file is part of CFP.io. * * CFP.io 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 io.cfp.multitenant; import io.cfp.multitenant.TenantFilter; import org.junit.Test; import org.springframework.http.HttpHeaders; import org.springframework.mock.web.MockHttpServletRequest; import static org.junit.Assert.*; /** * @author <a href="mailto:nicolas.deloof@gmail.com">Nicolas De Loof</a> */ public class TenantFilterTest { private MockHttpServletRequest request = new MockHttpServletRequest(); private TenantFilter filter = new TenantFilter(); @Test public void should_retrieve_tenant_from_Origin() { request.setPathInfo("/some/api"); request.addHeader(HttpHeaders.ORIGIN, "https://test.cfp.io" ); assertEquals("test", filter.extractTenant(request)); } @Test public void should_retrieve_tenant_from_Referer() { request.setPathInfo("/some/api"); request.addHeader(HttpHeaders.REFERER, "https://test.cfp.io/" ); assertEquals("test", filter.extractTenant(request)); } @Test public void should_retrieve_tenant_from_XTenant_header() { request.setPathInfo("/some/api"); request.addHeader(TenantFilter.TENANT_HEADER, "test" ); assertEquals("test", filter.extractTenant(request)); } @Test public void should_retrieve_tenant_from_Host() { request.setServerName("test.cfp.io"); assertEquals("test", filter.extractTenant(request)); } }
agpl-3.0
tdefilip/opennms
opennms-dao-api/src/main/java/org/opennms/netmgt/dao/util/Correlation.java
2983
/******************************************************************************* * This file is part of OpenNMS(R). * * Copyright (C) 2002-2014 The OpenNMS Group, Inc. * OpenNMS(R) is Copyright (C) 1999-2014 The OpenNMS Group, Inc. * * OpenNMS(R) is a registered trademark of The OpenNMS Group, Inc. * * OpenNMS(R) 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. * * OpenNMS(R) 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 OpenNMS(R). If not, see: * http://www.gnu.org/licenses/ * * For more information contact: * OpenNMS(R) Licensing <license@opennms.org> * http://www.opennms.org/ * http://www.opennms.com/ *******************************************************************************/ package org.opennms.netmgt.dao.util; import java.io.StringWriter; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.opennms.core.xml.JaxbUtils; import org.opennms.netmgt.model.events.Constants; import org.springframework.dao.DataAccessException; /** * This is an utility class used to format the event correlation info - to be * inserted into the 'events' table - it simply returns the correlation as an * 'XML' block * * @author <A HREF="mailto:sowmya@opennms.org">Sowmya Kumaraswamy </A> * @author <A HREF="http://www.opennms.org/">OpenNMS </A> * @see org.opennms.netmgt.model.events.Constants#VALUE_TRUNCATE_INDICATOR */ public abstract class Correlation { private static final Logger LOG = LoggerFactory.getLogger(Correlation.class); /** * Format the correlation block to have the xml * * @param ec * the correlation * @param sz * the size to which the formatted string is to be limited * to(usually the size of the column in the database) * @return the formatted event correlation */ public static String format(final org.opennms.netmgt.xml.event.Correlation ec, final int sz) { StringWriter out = new StringWriter(); try { JaxbUtils.marshal(ec, out); } catch (DataAccessException e) { LOG.error("Failed to convert new event to XML", e); return null; } String outstr = out.toString(); if (outstr.length() >= sz) { StringBuffer buf = new StringBuffer(outstr); buf.setLength(sz - 4); buf.append(Constants.VALUE_TRUNCATE_INDICATOR); return buf.toString(); } else { return outstr; } } }
agpl-3.0
jph-axelor/axelor-business-suite
axelor-account/src/main/java/com/axelor/apps/account/service/bankorder/BankOrderCreateService.java
5329
/** * Axelor Business Solutions * * Copyright (C) 2016 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.account.service.bankorder; import java.math.BigDecimal; import java.util.ArrayList; import java.time.LocalDate; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.axelor.apps.account.db.BankOrder; import com.axelor.apps.account.db.BankOrderFileFormat; import com.axelor.apps.account.db.BankOrderLine; import com.axelor.apps.account.db.Invoice; import com.axelor.apps.account.db.InvoicePayment; import com.axelor.apps.account.db.PaymentMode; import com.axelor.apps.account.db.repo.BankOrderRepository; import com.axelor.apps.account.db.repo.InvoiceRepository; import com.axelor.apps.account.service.config.AccountConfigService; import com.axelor.apps.base.db.BankDetails; import com.axelor.apps.base.db.Company; import com.axelor.apps.base.db.Currency; import com.axelor.apps.base.db.Partner; import com.axelor.exception.AxelorException; import com.google.inject.Inject; public class BankOrderCreateService { private final Logger log = LoggerFactory.getLogger( getClass() ); protected BankOrderRepository bankOrderRepo; protected AccountConfigService accountConfigService; protected BankOrderLineService bankOrderLineService; @Inject public BankOrderCreateService(BankOrderRepository bankOrderRepo, AccountConfigService accountConfigService, BankOrderLineService bankOrderLineService) { this.bankOrderRepo = bankOrderRepo; this.accountConfigService = accountConfigService; this.bankOrderLineService = bankOrderLineService; } /** * Créer un ordre bancaire avec tous les paramètres * * @param * @return * @throws AxelorException */ public BankOrder createBankOrder(PaymentMode paymentMode, Integer partnerType, LocalDate bankOrderDate, Company senderCompany, BankDetails senderBankDetails, Currency currency, String senderReference, String senderLabel) throws AxelorException { BankOrderFileFormat bankOrderFileFormat = paymentMode.getBankOrderFileFormat(); BankOrder bankOrder = new BankOrder(); bankOrder.setOrderTypeSelect(paymentMode.getOrderTypeSelect()); bankOrder.setPaymentMode(paymentMode); bankOrder.setPartnerTypeSelect(partnerType); if(!bankOrderFileFormat.getIsMultiDate()) { bankOrder.setBankOrderDate(bankOrderDate); } bankOrder.setStatusSelect(BankOrderRepository.STATUS_DRAFT); bankOrder.setRejectStatusSelect(BankOrderRepository.REJECT_STATUS_NOT_REJECTED); bankOrder.setSenderCompany(senderCompany); bankOrder.setSenderBankDetails(senderBankDetails); bankOrder.setSignatoryUser(accountConfigService.getAccountConfig(senderCompany).getDefaultSignatoryUser()); if(!bankOrderFileFormat.getIsMultiCurrency()) { bankOrder.setBankOrderCurrency(currency); } bankOrder.setCompanyCurrency(senderCompany.getCurrency()); bankOrder.setSenderLabel(senderLabel); bankOrder.setBankOrderLineList(new ArrayList<BankOrderLine>()); bankOrderRepo.save(bankOrder); return bankOrder; } /** * Method to create a bank order for an invoice Payment * * * @param invoicePayment * An invoice payment * * @throws AxelorException * */ public BankOrder createBankOrder(InvoicePayment invoicePayment) throws AxelorException { Invoice invoice = invoicePayment.getInvoice(); Company company = invoice.getCompany(); PaymentMode paymentMode = invoicePayment.getPaymentMode(); Partner partner = invoice.getPartner(); BigDecimal amount = invoicePayment.getAmount(); Currency currency = invoicePayment.getCurrency(); LocalDate paymentDate = invoicePayment.getPaymentDate(); BankOrder bankOrder = this.createBankOrder( paymentMode, this.getBankOrderPartnerType(invoice), paymentDate, company, this.getSenderBankDetails(invoice), currency, invoice.getInvoiceId(), invoice.getInvoiceId()); bankOrder.addBankOrderLineListItem(bankOrderLineService.createBankOrderLine(paymentMode.getBankOrderFileFormat(), partner, amount, currency, paymentDate, invoice.getInvoiceId(), null)); return bankOrder; } public int getBankOrderPartnerType(Invoice invoice) { if(invoice.getOperationTypeSelect() == InvoiceRepository.OPERATION_TYPE_CLIENT_REFUND || invoice.getOperationTypeSelect() == InvoiceRepository.OPERATION_TYPE_CLIENT_SALE) { return BankOrderRepository.CUSTOMER; }else{ return BankOrderRepository.SUPPLIER; } } public BankDetails getSenderBankDetails(Invoice invoice) { if(invoice.getBankDetails() != null) { return invoice.getCompanyBankDetails() ; } return invoice.getCompany().getDefaultBankDetails(); } }
agpl-3.0
dzc34/Asqatasun
rules/rules-rgaa3.2016/src/test/java/org/asqatasun/rules/rgaa32016/Rgaa32016Rule030203Test.java
4461
/* * 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.entity.audit.TestSolution; import org.asqatasun.entity.audit.ProcessResult; import org.asqatasun.rules.rgaa32016.test.Rgaa32016RuleImplementationTestCase; /** * Unit test class for the implementation of the rule 3.2.3 of the referential RGAA 3.2016 * * @author */ public class Rgaa32016Rule030203Test extends Rgaa32016RuleImplementationTestCase { /** * Default constructor * @param testName */ public Rgaa32016Rule030203Test (String testName){ super(testName); } @Override protected void setUpRuleImplementationClassName() { setRuleImplementationClassName( "org.asqatasun.rules.rgaa32016.Rgaa32016Rule030203"); } @Override protected void setUpWebResourceMap() { // addWebResource("Rgaa32016.Test.3.2.3-1Passed-01"); // addWebResource("Rgaa32016.Test.3.2.3-2Failed-01"); addWebResource("Rgaa32016.Test.3.2.3-3NMI-01"); // addWebResource("Rgaa32016.Test.3.2.3-4NA-01"); } @Override protected void setProcess() { //---------------------------------------------------------------------- //------------------------------1Passed-01------------------------------ //---------------------------------------------------------------------- // checkResultIsPassed(processPageTest("Rgaa32016.Test.3.2.3-1Passed-01"), 1); //---------------------------------------------------------------------- //------------------------------2Failed-01------------------------------ //---------------------------------------------------------------------- // ProcessResult processResult = processPageTest("Rgaa32016.Test.3.2.3-2Failed-01"); // checkResultIsFailed(processResult, 1, 1); // checkRemarkIsPresent( // processResult, // TestSolution.FAILED, // "#MessageHere", // "#CurrentElementHere", // 1, // new ImmutablePair("#ExtractedAttributeAsEvidence", "#ExtractedAttributeValue")); //---------------------------------------------------------------------- //------------------------------3NMI-01--------------------------------- //---------------------------------------------------------------------- ProcessResult processResult = processPageTest("Rgaa32016.Test.3.2.3-3NMI-01"); checkResultIsNotTested(processResult); // temporary result to make the result buildable before implementation // checkResultIsPreQualified(processResult, 2, 1); // checkRemarkIsPresent( // processResult, // TestSolution.NEED_MORE_INFO, // "#MessageHere", // "#CurrentElementHere", // 1, // new ImmutablePair("#ExtractedAttributeAsEvidence", "#ExtractedAttributeValue")); //---------------------------------------------------------------------- //------------------------------4NA-01------------------------------ //---------------------------------------------------------------------- // checkResultIsNotApplicable(processPageTest("Rgaa32016.Test.3.2.3-4NA-01")); } @Override protected void setConsolidate() { // The consolidate method can be removed when real implementation is done. // The assertions are automatically tested regarding the file names by // the abstract parent class assertEquals(TestSolution.NOT_TESTED, consolidate("Rgaa32016.Test.3.2.3-3NMI-01").getValue()); } }
agpl-3.0
DaveRead/SequenceHunt
src/com/monead/games/android/sequence/ui/package-info.java
113
/** * The ui package for the android-based Sequence Hunt game. */ package com.monead.games.android.sequence.ui;
agpl-3.0
o2oa/o2oa
o2server/x_processplatform_assemble_surface/src/main/java/com/x/processplatform/assemble/surface/jaxrs/attachment/ActionDeleteWithWorkCompleted.java
2525
package com.x.processplatform.assemble.surface.jaxrs.attachment; import com.x.base.core.container.EntityManagerContainer; import com.x.base.core.container.factory.EntityManagerContainerFactory; import com.x.base.core.project.Applications; import com.x.base.core.project.x_processplatform_service_processing; import com.x.base.core.project.exception.ExceptionAccessDenied; import com.x.base.core.project.exception.ExceptionEntityNotExist; import com.x.base.core.project.http.ActionResult; import com.x.base.core.project.http.EffectivePerson; import com.x.base.core.project.jaxrs.WoId; import com.x.base.core.project.logger.Logger; import com.x.base.core.project.logger.LoggerFactory; import com.x.processplatform.assemble.surface.Business; import com.x.processplatform.assemble.surface.ThisApplication; import com.x.processplatform.assemble.surface.WorkCompletedControl; import com.x.processplatform.core.entity.content.Attachment; import com.x.processplatform.core.entity.content.WorkCompleted; class ActionDeleteWithWorkCompleted extends BaseAction { private static Logger logger = LoggerFactory.getLogger(ActionDeleteWithWorkCompleted.class); ActionResult<Wo> execute(EffectivePerson effectivePerson, String id, String workCompletedId) throws Exception { ActionResult<Wo> result = new ActionResult<>(); Attachment attachment = null; WorkCompleted workCompleted = null; try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) { Business business = new Business(emc); workCompleted = emc.find(workCompletedId, WorkCompleted.class); if (null == workCompleted) { throw new ExceptionEntityNotExist(workCompletedId, WorkCompleted.class); } attachment = emc.find(id, Attachment.class); if (null == attachment) { throw new ExceptionEntityNotExist(id, Attachment.class); } if (!business.canManageApplicationOrProcess(effectivePerson, attachment.getApplication(), attachment.getProcess())) { throw new ExceptionAccessDenied(effectivePerson); } } Wo wo = ThisApplication .context().applications().deleteQuery(effectivePerson.getDebugger(), x_processplatform_service_processing.class, Applications.joinQueryUri("attachment", attachment.getId(), "workcompleted", workCompleted.getId()), workCompleted.getJob()) .getData(Wo.class); wo.setId(attachment.getId()); result.setData(wo); return result; } public static class Wo extends WoId { } public static class WoControl extends WorkCompletedControl { } }
agpl-3.0
FYP17-4G/Aardvark
CryptoAW/Source/Aardvark_Project/app/src/main/java/com/example/FYP/aardvark_project/Analytics/InvalidKeyException.java
225
package com.example.FYP.aardvark_project.Analytics; public class InvalidKeyException extends Exception { public InvalidKeyException() {} public InvalidKeyException(String message) { super (message); } }
agpl-3.0
opensourceBIM/BIMserver
BimServer/src/org/bimserver/database/actions/GetSerializerByContentTypeDatabaseAction.java
4342
package org.bimserver.database.actions; /****************************************************************************** * 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 java.util.List; import org.bimserver.BimServer; /****************************************************************************** * Copyright (C) 2009-2018 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.BimserverDatabaseException; import org.bimserver.database.BimserverLockConflictException; import org.bimserver.database.DatabaseSession; import org.bimserver.database.OldQuery; import org.bimserver.models.log.AccessMethod; import org.bimserver.models.store.SerializerPluginConfiguration; import org.bimserver.models.store.StorePackage; import org.bimserver.plugins.PluginConfiguration; import org.bimserver.plugins.serializers.SerializerPlugin; import org.bimserver.plugins.serializers.StreamingSerializerPlugin; import org.bimserver.shared.exceptions.UserException; public class GetSerializerByContentTypeDatabaseAction extends BimDatabaseAction<SerializerPluginConfiguration> { private final String contentType; private BimServer bimServer; public GetSerializerByContentTypeDatabaseAction(BimServer bimServer, DatabaseSession databaseSession, AccessMethod accessMethod, String contentType) { super(databaseSession, accessMethod); this.bimServer = bimServer; this.contentType = contentType; } @Override public SerializerPluginConfiguration execute() throws UserException, BimserverLockConflictException, BimserverDatabaseException { List<SerializerPluginConfiguration> allOfType = getDatabaseSession().getAllOfType(StorePackage.eINSTANCE.getSerializerPluginConfiguration(), SerializerPluginConfiguration.class, OldQuery.getDefault()); // One loop to try and find the streaming version for (SerializerPluginConfiguration serializerPluginConfiguration : allOfType) { PluginConfiguration pluginConfiguration = bimServer.getPluginSettingsCache().getPluginSettings(serializerPluginConfiguration.getOid()); String string = pluginConfiguration.getString(SerializerPlugin.CONTENT_TYPE); if (string != null && string.equals(contentType) && serializerPluginConfiguration.getPluginDescriptor().getPluginInterfaceClassName().equals(StreamingSerializerPlugin.class.getName())) { return serializerPluginConfiguration; } } // None found, there try again and also allow non-streaming for (SerializerPluginConfiguration serializerPluginConfiguration : allOfType) { PluginConfiguration pluginConfiguration = bimServer.getPluginSettingsCache().getPluginSettings(serializerPluginConfiguration.getOid()); String string = pluginConfiguration.getString(SerializerPlugin.CONTENT_TYPE); if (string != null && string.equals(contentType)) { return serializerPluginConfiguration; } } return null; } }
agpl-3.0
ManfredKarrer/exchange
gui/src/main/java/io/bisq/gui/util/BsqFormatter.java
4088
/* * This file is part of Bisq. * * Bisq 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. * * Bisq 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 Bisq. If not, see <http://www.gnu.org/licenses/>. */ package io.bisq.gui.util; import io.bisq.common.app.DevEnv; import io.bisq.common.util.MathUtils; import io.bisq.core.app.BisqEnvironment; import io.bisq.core.provider.price.MarketPrice; import lombok.extern.slf4j.Slf4j; import org.bitcoinj.core.Address; import org.bitcoinj.core.AddressFormatException; import org.bitcoinj.core.Coin; import org.bitcoinj.utils.MonetaryFormat; import javax.inject.Inject; import java.text.DecimalFormat; @Slf4j public class BsqFormatter extends BSFormatter { @SuppressWarnings("PointlessBooleanExpression") private static final boolean useBsqAddressFormat = true || !DevEnv.DEV_MODE; private final String prefix = "B"; private final DecimalFormat amountFormat = new DecimalFormat("###,###,###.###"); private final DecimalFormat marketCapFormat = new DecimalFormat("###,###,###"); @Inject private BsqFormatter() { super(); final String baseCurrencyCode = BisqEnvironment.getBaseCurrencyNetwork().getCurrencyCode(); switch (baseCurrencyCode) { case "BTC": coinFormat = new MonetaryFormat().shift(5).code(5, "BSQ").minDecimals(3); break; case "LTC": coinFormat = new MonetaryFormat().shift(3).code(3, "BSQ").minDecimals(5); break; case "DOGE": // BSQ for DOGE not used/supported coinFormat = new MonetaryFormat().shift(3).code(3, "???").minDecimals(5); break; case "DASH": // BSQ for DASH not used/supported coinFormat = new MonetaryFormat().shift(3).code(3, "???").minDecimals(5); break; default: throw new RuntimeException("baseCurrencyCode not defined. baseCurrencyCode=" + baseCurrencyCode); } amountFormat.setMinimumFractionDigits(3); } /** * Returns the base-58 encoded String representation of this * object, including version and checksum bytes. */ public String getBsqAddressStringFromAddress(Address address) { final String addressString = address.toString(); if (useBsqAddressFormat) return prefix + addressString; else return addressString; } public Address getAddressFromBsqAddress(String encoded) { if (useBsqAddressFormat) encoded = encoded.substring(prefix.length(), encoded.length()); try { return Address.fromBase58(BisqEnvironment.getParameters(), encoded); } catch (AddressFormatException e) { log.error(e.toString()); e.printStackTrace(); throw new RuntimeException(e); } } public String formatAmountWithGroupSeparatorAndCode(Coin amount) { return amountFormat.format(MathUtils.scaleDownByPowerOf10(amount.value, 3)) + " BSQ"; } public String formatMarketCap(MarketPrice bsqPriceMarketPrice, MarketPrice fiatMarketPrice, Coin issuedAmount) { if (bsqPriceMarketPrice != null && fiatMarketPrice != null) { double marketCap = bsqPriceMarketPrice.getPrice() * fiatMarketPrice.getPrice() * (MathUtils.scaleDownByPowerOf10(issuedAmount.value, 3)); return marketCapFormat.format(MathUtils.doubleToLong(marketCap)) + " " + fiatMarketPrice.getCurrencyCode(); } else { return ""; } } }
agpl-3.0
ua-eas/ua-kfs-5.3
work/src/org/kuali/kfs/gl/dataaccess/CorrectionChangeDao.java
1755
/* * 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.gl.dataaccess; import java.util.List; import org.kuali.kfs.gl.businessobject.CorrectionChange; /** * A DAO interface for CorrectionChange business objects to interact with the databse */ public interface CorrectionChangeDao { /** * Surprisingly, this method deletes a GLCP correction * * @param spec the GLCP correction to delete */ void delete(CorrectionChange spec); /** * Finds CorrectionChanges associated with the given document and group * * @param documentHeaderId the document number of a GLCP document * @param correctionGroupLineNumber the line number of the group within the GLCP document to find correction chagnes for * @return a List of correction changes */ List findByDocumentHeaderIdAndCorrectionGroupNumber(String documentHeaderId, Integer correctionGroupLineNumber); }
agpl-3.0
automenta/narchy
ui/src/main/java/spacegraph/space2d/phys/collision/broadphase/DefaultBroadPhaseBuffer.java
7991
/******************************************************************************* * Copyright (c) 2013, Daniel Murphy * All rights reserved. * * Redistribution and use in source and binary forms, with or without modification, * are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. * IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, * INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR * PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. ******************************************************************************/ package spacegraph.space2d.phys.collision.broadphase; import jcog.math.v2; import spacegraph.space2d.phys.callbacks.DebugDraw; import spacegraph.space2d.phys.callbacks.PairCallback; import spacegraph.space2d.phys.callbacks.TreeCallback; import spacegraph.space2d.phys.callbacks.TreeRayCastCallback; import spacegraph.space2d.phys.collision.AABB; import spacegraph.space2d.phys.collision.RayCastInput; import java.util.Arrays; /** * The broad-phase is used for computing pairs and performing volume queries and ray casts. This * broad-phase does not persist pairs. Instead, this reports potentially new pairs. It is up to the * client to consume the new pairs and to track subsequent overlap. * * @author Daniel Murphy */ public class DefaultBroadPhaseBuffer implements TreeCallback, BroadPhase { private final BroadPhaseStrategy m_tree; private int m_proxyCount; private int[] m_moveBuffer; private int m_moveCapacity; private int m_moveCount; private Pair[] m_pairBuffer; private int m_pairCapacity; private int m_pairCount; private int m_queryProxyId; public DefaultBroadPhaseBuffer(BroadPhaseStrategy strategy) { m_proxyCount = 0; m_pairCapacity = 16; m_pairCount = 0; m_pairBuffer = new Pair[m_pairCapacity]; for (int i = 0; i < m_pairCapacity; i++) { m_pairBuffer[i] = new Pair(); } m_moveCapacity = 16; m_moveCount = 0; m_moveBuffer = new int[m_moveCapacity]; m_tree = strategy; m_queryProxyId = NULL_PROXY; } @Override public final int createProxy(final AABB aabb, Object userData) { int proxyId = m_tree.createProxy(aabb, userData); ++m_proxyCount; bufferMove(proxyId); return proxyId; } @Override public final void destroyProxy(int proxyId) { unbufferMove(proxyId); --m_proxyCount; m_tree.destroyProxy(proxyId); } @Override public final void moveProxy(int proxyId, final AABB aabb, final v2 displacement) { boolean buffer = m_tree.moveProxy(proxyId, aabb, displacement); if (buffer) { bufferMove(proxyId); } } @Override public void touchProxy(int proxyId) { bufferMove(proxyId); } @Override public Object get(int proxyId) { return m_tree.getUserData(proxyId); } @Override public AABB getFatAABB(int proxyId) { return m_tree.getFatAABB(proxyId); } @Override public boolean testOverlap(int proxyIdA, int proxyIdB) { final AABB a = m_tree.getFatAABB(proxyIdA); final AABB b = m_tree.getFatAABB(proxyIdB); if (b.lowerBound.x - a.upperBound.x > 0.0f || b.lowerBound.y - a.upperBound.y > 0.0f) { return false; } return !(a.lowerBound.x - b.upperBound.x > 0.0f) && !(a.lowerBound.y - b.upperBound.y > 0.0f); } @Override public final int getProxyCount() { return m_proxyCount; } @Override public void drawTree(DebugDraw argDraw) { m_tree.drawTree(argDraw); } @Override public final void updatePairs(PairCallback callback) { m_pairCount = 0; for (int i = 0; i < m_moveCount; ++i) { m_queryProxyId = m_moveBuffer[i]; if (m_queryProxyId == NULL_PROXY) { continue; } final AABB fatAABB = m_tree.getFatAABB(m_queryProxyId); m_tree.query(this, fatAABB); } m_moveCount = 0; Arrays.sort(m_pairBuffer, 0, m_pairCount); int i = 0; while (i < m_pairCount) { Pair primaryPair = m_pairBuffer[i]; Object userDataA = m_tree.getUserData(primaryPair.proxyIdA); Object userDataB = m_tree.getUserData(primaryPair.proxyIdB); callback.addPair(userDataA, userDataB); ++i; while (i < m_pairCount) { Pair pair = m_pairBuffer[i]; if (pair.proxyIdA != primaryPair.proxyIdA || pair.proxyIdB != primaryPair.proxyIdB) { break; } ++i; } } } @Override public final void query(final TreeCallback callback, final AABB aabb) { m_tree.query(callback, aabb); } @Override public final void raycast(final TreeRayCastCallback callback, final RayCastInput input) { m_tree.raycast(callback, input); } @Override public final int getTreeHeight() { return m_tree.getHeight(); } @Override public int getTreeBalance() { return m_tree.getMaxBalance(); } @Override public float getTreeQuality() { return m_tree.getAreaRatio(); } private void bufferMove(int proxyId) { if (m_moveCount == m_moveCapacity) { int[] old = m_moveBuffer; m_moveCapacity *= 2; m_moveBuffer = new int[m_moveCapacity]; System.arraycopy(old, 0, m_moveBuffer, 0, old.length); } m_moveBuffer[m_moveCount] = proxyId; ++m_moveCount; } private void unbufferMove(int proxyId) { for (int i = 0; i < m_moveCount; i++) { if (m_moveBuffer[i] == proxyId) { m_moveBuffer[i] = NULL_PROXY; } } } /** * This is called from DynamicTree::query when we are gathering pairs. */ public final boolean treeCallback(int proxyId) { if (proxyId == m_queryProxyId) { return true; } if (m_pairCount == m_pairCapacity) { Pair[] oldBuffer = m_pairBuffer; m_pairCapacity *= 2; m_pairBuffer = new Pair[m_pairCapacity]; System.arraycopy(oldBuffer, 0, m_pairBuffer, 0, oldBuffer.length); for (int i = oldBuffer.length; i < m_pairCapacity; i++) { m_pairBuffer[i] = new Pair(); } } Pair thePair = m_pairBuffer[m_pairCount++]; if (proxyId < m_queryProxyId) { thePair.proxyIdA = proxyId; thePair.proxyIdB = m_queryProxyId; } else { thePair.proxyIdA = m_queryProxyId; thePair.proxyIdB = proxyId; } return true; } }
agpl-3.0
aborg0/rapidminer-vega
src/com/rapidminer/gui/properties/celleditors/value/DateFormatValueCellEditor.java
6693
/* * 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.gui.properties.celleditors.value; import java.awt.Component; import java.awt.GridBagConstraints; import java.awt.GridBagLayout; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import javax.swing.AbstractAction; import javax.swing.AbstractButton; import javax.swing.AbstractCellEditor; import javax.swing.JButton; import javax.swing.JComboBox; import javax.swing.JMenu; import javax.swing.JMenuItem; import javax.swing.JPanel; import javax.swing.JPopupMenu; import javax.swing.JTable; import com.rapidminer.gui.tools.ResourceAction; import com.rapidminer.operator.Operator; import com.rapidminer.operator.ports.metadata.AttributeMetaData; import com.rapidminer.operator.ports.metadata.ExampleSetMetaData; import com.rapidminer.operator.ports.metadata.MetaData; import com.rapidminer.parameter.ParameterTypeAttribute; import com.rapidminer.parameter.ParameterTypeDateFormat; /** * Value cell editor for date formats. The user can select among a predefined set of values and copy nominal values * retrieved from an example set at an input port to the combo box as an editing help. * * @author Simon Fischer */ public class DateFormatValueCellEditor extends AbstractCellEditor implements PropertyValueCellEditor { private static final long serialVersionUID = -1889899793777695100L; private JPanel panel; private JComboBox formatCombo; private AbstractButton selectButton; public DateFormatValueCellEditor(final ParameterTypeDateFormat type) { panel = new JPanel(new GridBagLayout()); GridBagConstraints c = new GridBagConstraints(); c.fill = GridBagConstraints.BOTH; c.anchor = GridBagConstraints.FIRST_LINE_START; c.weightx = 1; c.gridwidth = GridBagConstraints.RELATIVE; formatCombo = new JComboBox(type.getValues()); formatCombo.setEditable(true); panel.add(formatCombo, c); selectButton = new JButton(new ResourceAction(true, "dateformat.select_sample") { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { JPopupMenu menu = new JPopupMenu(); if (type.getInputPort() != null) { MetaData md = type.getInputPort().getMetaData(); if (md instanceof ExampleSetMetaData) { ExampleSetMetaData emd = (ExampleSetMetaData) md; final ParameterTypeAttribute attributeParameterType = type.getAttributeParameterType(); if (attributeParameterType != null) { String selectedAttributeName = type.getInputPort().getPorts().getOwner().getOperator().getParameters().getParameterOrNull(attributeParameterType.getKey()); AttributeMetaData selectedAttribute = emd.getAttributeByName(selectedAttributeName); if (selectedAttribute != null && (selectedAttribute.isNominal()) && (selectedAttribute.getValueSet() != null)) { boolean isNotMenuEmpty = false; for (final String value : selectedAttribute.getValueSet()) { menu.add(new JMenuItem(new AbstractAction(value) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { formatCombo.setSelectedItem(value); } })); isNotMenuEmpty = true; } if (isNotMenuEmpty) menu.show(selectButton, 0, selectButton.getHeight()); selectButton.setEnabled(isNotMenuEmpty); } else if (emd.getAllAttributes() != null) { int j = 0; boolean isNotMenuEmpty = false; for (final AttributeMetaData amd : emd.getAllAttributes()) { if (amd.isNominal() && (amd.getValueSet() != null)) { JMenu subMenu = new JMenu(amd.getName()); menu.add(subMenu); int i = 0; for (final String value : amd.getValueSet()) { subMenu.add(new JMenuItem(new AbstractAction(value) { private static final long serialVersionUID = 1L; @Override public void actionPerformed(ActionEvent e) { formatCombo.setSelectedItem(value); if (attributeParameterType != null && type.getInputPort() != null) type.getInputPort().getPorts().getOwner().getOperator().getParameters().setParameter(attributeParameterType.getKey(), amd.getName()); } })); i++; if (i > 21) //don't show too many values: list could become really long. break; } isNotMenuEmpty = true; j++; if (j>13) // don't show to many attributes break; } } if (isNotMenuEmpty) menu.show(selectButton, 0, selectButton.getHeight()); selectButton.setEnabled(isNotMenuEmpty); } } } } } }); c.gridwidth = GridBagConstraints.REMAINDER; c.weightx = 0; selectButton.setText(null); panel.add(selectButton, c); formatCombo.addActionListener(new ActionListener() { @Override public void actionPerformed(ActionEvent e) { fireEditingStopped(); } }); } @Override public boolean rendersLabel() { return false; } @Override public void setOperator(Operator operator) { } @Override public boolean useEditorAsRenderer() { return true; } @Override public Component getTableCellRendererComponent(JTable table, Object value, boolean isSelected, boolean hasFocus, int row, int column) { return panel; } @Override public Component getTableCellEditorComponent(JTable table, Object value, boolean isSelected, int row, int column) { formatCombo.setSelectedItem(value); return panel; } @Override public Object getCellEditorValue() { return formatCombo.getSelectedItem(); } }
agpl-3.0
PureSolTechnologies/Purifinity
analysis/api/ust/src/main/java/com/puresoltechnologies/parsers/ust/eval/ValueType.java
141
package com.puresoltechnologies.parsers.ust.eval; public enum ValueType { UNSPECIFIED, CHARACTER, STRING, BOOLEAN, INTEGER, NUMERICAL; }
agpl-3.0
martinlau/unidle-old
src/test/java/org/unidle/controller/CreateQuestionControllerTest.java
7742
/* * #%L * unidle * %% * Copyright (C) 2013 Martin Lau * %% * 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 General Public License for more details. * * You should have received a copy of the GNU Affero General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. * #L% */ package org.unidle.controller; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.mock.web.MockMultipartFile; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.core.context.SecurityContextHolder; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.ContextHierarchy; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import org.springframework.test.context.web.WebAppConfiguration; import org.springframework.test.web.servlet.MockMvc; import org.springframework.transaction.annotation.Transactional; import org.springframework.web.context.WebApplicationContext; import org.unidle.analytics.config.AnalyticsTestConfiguration; import org.unidle.config.CacheConfiguration; import org.unidle.config.DataConfiguration; import org.unidle.config.I18NConfiguration; import org.unidle.config.MvcConfiguration; import org.unidle.config.ServiceConfiguration; import org.unidle.domain.User; import org.unidle.repository.AttachmentRepository; import org.unidle.repository.QuestionRepository; import org.unidle.repository.UserRepository; import static org.fest.assertions.Assertions.assertThat; import static org.hamcrest.Matchers.startsWith; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.fileUpload; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.get; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.model; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.view; import static org.springframework.test.web.servlet.setup.MockMvcBuilders.webAppContextSetup; @ContextHierarchy({@ContextConfiguration(classes = CacheConfiguration.class), @ContextConfiguration(classes = DataConfiguration.class), @ContextConfiguration(classes = I18NConfiguration.class), @ContextConfiguration(classes = ServiceConfiguration.class), @ContextConfiguration(classes = AnalyticsTestConfiguration.class), @ContextConfiguration(classes = MvcConfiguration.class)}) @RunWith(SpringJUnit4ClassRunner.class) @Transactional @WebAppConfiguration public class CreateQuestionControllerTest { @Autowired private AttachmentRepository attachmentRepository; @Autowired private QuestionRepository questionRepository; private MockMvc subject; private User user; @Autowired private UserRepository userRepository; @Autowired private WebApplicationContext webApplicationContext; @Before public void setUp() throws Exception { subject = webAppContextSetup(webApplicationContext).build(); user = new User(); user.setEmail("email@example.com"); user.setFirstName("first name"); user.setLastName("last name"); user = userRepository.save(user); } @After public void tearDown() throws Exception { SecurityContextHolder.clearContext(); } @Test public void testQuestion() throws Exception { SecurityContextHolder.getContext() .setAuthentication(new UsernamePasswordAuthenticationToken(user.getUuid(), null)); subject.perform(get("/question/create")) .andExpect(status().isOk()) .andExpect(model().attributeExists("questionForm")); } @Test public void testQuestionPost() throws Exception { SecurityContextHolder.getContext() .setAuthentication(new UsernamePasswordAuthenticationToken(user.getUuid(), null)); subject.perform(fileUpload("/question/create") .param("question", "this is a test question")) .andExpect(view().name(startsWith("redirect:/question/"))); assertThat(questionRepository.count()).isEqualTo(1L); assertThat(questionRepository.findAll().get(0).getTags()).isEmpty(); } @Test public void testQuestionPostWithErrors() throws Exception { SecurityContextHolder.getContext() .setAuthentication(new UsernamePasswordAuthenticationToken(user.getUuid(), null)); subject.perform(post("/question/create")) .andExpect(view().name(".create-question")) .andExpect(model().attributeExists("questionForm")); } @Test public void testQuestionPostWithTags() throws Exception { SecurityContextHolder.getContext() .setAuthentication(new UsernamePasswordAuthenticationToken(user.getUuid(), null)); subject.perform(fileUpload("/question/create") .param("question", "this is a test question") .param("tags", "tag1, tag2, tag3")) .andExpect(view().name(startsWith("redirect:/question/"))); assertThat(questionRepository.count()).isEqualTo(1L); assertThat(questionRepository.findAll().get(0).getTags()).containsOnly("tag1", "tag2", "tag3"); } @Test public void testQuestionPostWithTagsAndAttachments() throws Exception { SecurityContextHolder.getContext() .setAuthentication(new UsernamePasswordAuthenticationToken(user.getUuid(), null)); subject.perform(fileUpload("/question/create") .file(new MockMultipartFile("attachments", "test.txt", "text/plain", "this is a text file".getBytes())) .param("question", "this is a test question") .param("tags", "tag1, tag2, tag3")) .andExpect(view().name(startsWith("redirect:/question/"))); assertThat(questionRepository.count()).isEqualTo(1L); assertThat(questionRepository.findAll().get(0).getTags()).containsOnly("tag1", "tag2", "tag3"); assertThat(attachmentRepository.count()).isEqualTo(1L); } @Test public void testQuestionPostWithoutAuthentication() throws Exception { subject.perform(post("/question/create") .param("question", "this is a test question")) .andExpect(view().name("redirect:/signin")); } @Test public void testQuestionWithoutAuthentication() throws Exception { subject.perform(get("/question/create")) .andExpect(view().name("redirect:/signin")); } }
agpl-3.0
Xapagy/Xapagy
src/main/java/org/xapagy/activity/Activity.java
4186
/* This file is part of the Xapagy Cognitive Architecture Copyright (C) 2008-2017 Ladislau Boloni 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.xapagy.activity; import java.io.Serializable; import java.util.HashMap; import java.util.Map; import org.xapagy.agents.Agent; import org.xapagy.ui.formatters.IxwFormattable; /** * * The ancestor of all the activity classes (Spike and Diffusion) These * activities must be self describing and self-monitoring for debugging * purposes. * * @author Ladislau Boloni * Created on: Apr 22, 2011 */ public abstract class Activity implements Serializable, IxwFormattable { private static final long serialVersionUID = 7200661641720685777L; /** * Link to the agent to which they are tied */ protected Agent agent; /** * The description of the activity */ private String description; /** * The name of the activity - it is necessary, because the same activity, differently * parameterized might be serving in several places */ private String name; protected Map<String, String> parameters = new HashMap<>(); /** * @return the name */ public String getName() { return name; } /** * Default constructor, forces name in the rest of the activities * * @param agent * @param name */ public Activity(Agent agent, String name) { super(); this.agent = agent; this.name = name; } /** * @return the description */ public String getDescription() { return description; } /** * @param description * the description to set */ public void setDescription(String description) { this.description = description; } /** * Overwrites the existing parameters and calls extractParameters * @param parameters the parameters to set */ public void setAndExtractParameters(Map<String, String> param) { parameters = new HashMap<>(); for(String key: param.keySet()) { parameters.put(key, param.get(key)); } extractParameters(); } /** * Gets a parameter, throws appropriate error if not found * @param name * @return */ public String getParameterString(String name) { String value = parameters.get(name); if (value == null) { throw new Error("Expected parameter " + name + " not found"); } return value; } /** * Gets a parameter, throws appropriate exception if not found * @param name * @return * @throws Exception */ public double getParameterDouble(String name) { String value = null; double b = 0.0; try { value = parameters.get(name); b = Double.parseDouble(value); } catch(NullPointerException npe) { throw new Error("Expected parameter " + name + " not found"); } catch(NumberFormatException nfe) { throw new Error("The value " + value + " for parameter " + name + " cannot be parsed to double."); } return b; } /** * Extracts the parameters from parameters into local variables. MUST be overwritten * in every Activity */ public abstract void extractParameters(); }
agpl-3.0