code
stringlengths
10
749k
repo_name
stringlengths
5
108
path
stringlengths
7
333
language
stringclasses
1 value
license
stringclasses
15 values
size
int64
10
749k
/* * SonarQube * Copyright (C) 2009-2017 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.api.ce.posttask; /** * @since 5.5 */ public interface CeTask { /** * Id of the Compute Engine task. * <p> * This is the id under which the processing of the project analysis report has been added to the Compute Engine * queue. * */ String getId(); /** * Indicates whether the Compute Engine task ended successfully or not. */ Status getStatus(); enum Status { SUCCESS, FAILED } }
lbndev/sonarqube
sonar-plugin-api/src/main/java/org/sonar/api/ce/posttask/CeTask.java
Java
lgpl-3.0
1,287
package calc.lib; /** Class (POJO) used to store Uninhabited Solar System JSON objects * * @author Carlin Robertson * @version 1.0 * */ public class SolarSystemUninhabited { private String[] information; private String requirePermit; private Coords coords; private String name; public String[] getInformation () { return information; } public void setInformation (String[] information) { this.information = information; } public String getRequirePermit () { return requirePermit; } public void setRequirePermit (String requirePermit) { this.requirePermit = requirePermit; } public Coords getCoords () { return coords; } public void setCoords (Coords coords) { this.coords = coords; } public String getName () { return name; } public void setName (String name) { this.name = name; } }
TheJavaMagician/CalculusBot
src/main/java/calc/lib/SolarSystemUninhabited.java
Java
lgpl-3.0
977
// Catalano Fuzzy Library // The Catalano Framework // // Copyright © Diego Catalano, 2013 // diego.catalano at live.com // // Copyright © Andrew Kirillov, 2007-2008 // andrew.kirillov at gmail.com // // This library is free software; you can redistribute it and/or // modify it under the terms of the GNU Lesser General Public // License as published by the Free Software Foundation; either // version 2.1 of the License, or (at your option) any later version. // // This library is distributed in the hope that it will be useful, // but WITHOUT ANY WARRANTY; without even the implied warranty of // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU // Lesser General Public License for more details. // // You should have received a copy of the GNU Lesser General Public // License along with this library; if not, write to the Free Software // Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA // package Catalano.Fuzzy; /** * Interface with the common methods of Fuzzy Unary Operator. * @author Diego Catalano */ public interface IUnaryOperator { /** * Calculates the numerical result of a Unary operation applied to one fuzzy membership value. * @param membership A fuzzy membership value, [0..1]. * @return The numerical result of the operation applied to <paramref name="membership"/>. */ float Evaluate( float membership ); }
accord-net/java
Catalano.Fuzzy/src/Catalano/Fuzzy/IUnaryOperator.java
Java
lgpl-3.0
1,453
package flabs.mods.magitech.aura; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.world.WorldSavedData; public class AuraSavedData extends WorldSavedData{ public static final String nbtName="MagiAura"; public AuraSavedData(String name) { super(name); } @Override public void readFromNBT(NBTTagCompound nbttagcompound) { System.out.println("Reading Aura Data"); } @Override public void writeToNBT(NBTTagCompound nbttagcompound) { System.out.println("Writing Aura Data"); } }
froschi3b/Magitech
magitech_common/flabs/mods/magitech/aura/AuraSavedData.java
Java
lgpl-3.0
532
package edu.ut.mobile.network; public class NetInfo{ //public static byte[] IPAddress = {Integer.valueOf("54").byteValue(),Integer.valueOf("73").byteValue(),Integer.valueOf("28").byteValue(),Integer.valueOf("236").byteValue()}; static byte[] IPAddress = {Integer.valueOf("192").byteValue(),Integer.valueOf("168").byteValue(),Integer.valueOf("1").byteValue(),Integer.valueOf("67").byteValue()}; static int port = 6000; static int waitTime = 100000; }
huberflores/BenchmarkingAndroidx86
Simulator/MobileOffloadSimulator/src/main/java/edu/ut/mobile/network/NetInfo.java
Java
lgpl-3.0
473
/* Copyright 2009 Semantic Discovery, Inc. (www.semanticdiscovery.com) This file is part of the Semantic Discovery Toolkit. The Semantic Discovery Toolkit is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. The Semantic Discovery Toolkit is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with The Semantic Discovery Toolkit. If not, see <http://www.gnu.org/licenses/>. */ package org.sd.text; import org.sd.io.FileUtil; import org.sd.nlp.AbstractLexicon; import org.sd.nlp.AbstractNormalizer; import org.sd.nlp.Break; import org.sd.nlp.BreakStrategy; import org.sd.nlp.Categories; import org.sd.nlp.Category; import org.sd.nlp.CategoryFactory; import org.sd.nlp.GeneralNormalizer; import org.sd.nlp.GenericLexicon; import org.sd.nlp.Lexicon; import org.sd.nlp.LexiconPipeline; import org.sd.nlp.TokenizationStrategy; import org.sd.nlp.TokenizerWrapper; import org.sd.nlp.StringWrapper; import org.sd.util.PropertiesParser; import org.sd.util.tree.Tree; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.net.MalformedURLException; import java.util.ArrayList; import java.util.Collections; import java.util.Comparator; import java.util.HashMap; import java.util.Iterator; import java.util.LinkedList; import java.util.List; import java.util.Map; import java.util.Properties; /** * Utility to find meaningful words in strings. * <p> * @author Spence Koehler */ public class MungedWordFinder { private static final String UNDETERMINED_LETTER = "X"; private static final String UNDETERMINED_WORD = "U"; private static final String WORD = "W"; private static final String NUMBER = "N"; private static final String SEQUENCE = "S"; private static final String CONSTITUENT = "C"; private static final String[] CATEGORIES = new String[] { UNDETERMINED_LETTER, UNDETERMINED_WORD, WORD, NUMBER, SEQUENCE, CONSTITUENT, }; private static final AbstractNormalizer NORMALIZER = GeneralNormalizer.getCaseInsensitiveInstance(); private static final BreakStrategy BREAK_STRATEGY = new MyBreakStrategy(); private static final Comparator<WordSequence> SEQUENCE_COMPARATOR = new Comparator<WordSequence>() { public int compare(WordSequence ws1, WordSequence ws2) { return ws1.size() - ws2.size(); } public boolean equals(Object o) { return this == o; } }; private CategoryFactory categoryFactory; private Map<String, File> wordFiles; private Map<String, String[]> wordSets; private List<Lexicon> lexicons; private TokenizerWrapper _tokenizerWrapper; /** * Construct without any dictionaries. * <p> * Add dictionaries to use for finding munged words using the * addWordFile, addWordSet, and addLexicon methods. */ public MungedWordFinder() { this.categoryFactory = new CategoryFactory(CATEGORIES); this.wordFiles = new HashMap<String, File>(); this.wordSets = new HashMap<String, String[]>(); this.lexicons = new ArrayList<Lexicon>(); this._tokenizerWrapper = null; } /** * Add a word file defining words to recognize. */ public final void addWordFile(String name, File wordFile) { this.wordFiles.put(name, wordFile); this._tokenizerWrapper = null; // force rebuild. } /** * Add a word set defining words to recognize. */ public final void addWordSet(String name, String[] words) { this.wordSets.put(name, words); this._tokenizerWrapper = null; // force rebuild. } /** * Add a lexicon defining words to recognize. */ public final void addLexicon(Lexicon lexicon) { this.lexicons.add(lexicon); this._tokenizerWrapper = null; // force rebuild. } protected final TokenizerWrapper getTokenizerWrapper() { if (_tokenizerWrapper == null) { try { final Lexicon lexicon = new LexiconPipeline(buildLexicons()); _tokenizerWrapper = new TokenizerWrapper( lexicon, categoryFactory, TokenizationStrategy.Type.LONGEST_TO_SHORTEST, NORMALIZER, BREAK_STRATEGY, false, 0, false); //NOTE: lexicon should classify every token } catch (IOException e) { throw new IllegalStateException(e); } } return _tokenizerWrapper; } private final Lexicon[] buildLexicons() throws IOException { final List<Lexicon> result = new ArrayList<Lexicon>(); final Category wordCategory = categoryFactory.getCategory(WORD); // add a lexicon that identifies/recognizes number sequences. result.add(new NumberLexicon(categoryFactory.getCategory(NUMBER))); // add a lexicon for each wordSet for (Map.Entry<String, String[]> wordSetEntry : wordSets.entrySet()) { final String name = wordSetEntry.getKey(); final String[] terms = wordSetEntry.getValue(); final GenericLexicon genericLexicon = new GenericLexicon(terms, NORMALIZER, wordCategory, false, true, false, "name=" + name); genericLexicon.setMaxNumWords(0); // disable "word" limit. each char counts as a word with our break strategy. result.add(genericLexicon); } // add a lexicon for each wordFile for (Map.Entry<String, File> wordFileEntry : wordFiles.entrySet()) { final String name = wordFileEntry.getKey(); final File wordFile = wordFileEntry.getValue(); final GenericLexicon genericLexicon = new GenericLexicon(FileUtil.getInputStream(wordFile), NORMALIZER, wordCategory, false, true, false, "name=" + name); genericLexicon.setMaxNumWords(0); // disable "word" limit. each char counts as a word with our break strategy. result.add(genericLexicon); } // add each lexicon for (Lexicon lexicon : lexicons) { result.add(lexicon); } // add a lexicon that identifies a single letter as unknown. result.add(new UnknownLexicon(categoryFactory.getCategory(UNDETERMINED_LETTER))); return result.toArray(new Lexicon[result.size()]); //todo: what about conjugations? } public List<WordSequence> getBestSplits(String string) { List<WordSequence> result = new ArrayList<WordSequence>(); final TokenizerWrapper tokenizerWrapper = getTokenizerWrapper(); final Tree<StringWrapper.SubString> tokenTree = tokenizerWrapper.tokenize(string); final List<Tree<StringWrapper.SubString>> leaves = tokenTree.gatherLeaves(); int maxScore = -1; for (Tree<StringWrapper.SubString> leaf : leaves) { final WordSequence wordSequence = new WordSequence(leaf); final int curScore = wordSequence.getScore(); if (curScore >= maxScore) { if (curScore > maxScore) { result.clear(); maxScore = curScore; } result.add(wordSequence); } } if (result.size() > 0) { Collections.sort(result, SEQUENCE_COMPARATOR); } return result; } public List<WordSequence> getBestDomainSplits(String domain) { final int dotPos = domain.indexOf('.'); if (dotPos > 0 && dotPos < domain.length() - 1) { final DetailedUrl dUrl = new DetailedUrl(domain); domain = dUrl.getHost(false, false, false); } return getBestSplits(domain); } public String getSplitsAsString(List<WordSequence> splits) { final StringBuilder result = new StringBuilder(); if (splits != null) { for (Iterator<WordSequence> splitIter = splits.iterator(); splitIter.hasNext(); ) { final WordSequence split = splitIter.next(); result.append(split.toString()); if (splitIter.hasNext()) result.append('|'); } } return result.toString(); } // symbols are hard breaks... letters are soft breaks... consecutive digits aren't (don't break numbers) private static final class MyBreakStrategy implements BreakStrategy { public Break[] computeBreaks(int[] codePoints) { final Break[] result = new Break[codePoints.length]; boolean inNumber = false; for (int i = 0; i < codePoints.length; ++i) { Break curBreak = Break.NONE; final int cp = codePoints[i]; if (Character.isDigit(cp)) { if (i > 0 && !inNumber && result[i - 1] != Break.HARD) { curBreak = Break.SOFT_SPLIT; } else { curBreak = Break.NONE; } inNumber = true; } else if (Character.isLetter(cp)) { // first letter after a hard break (or at start) isn't a break if (i == 0 || result[i - 1] == Break.HARD) { curBreak = Break.NONE; } else { curBreak = Break.SOFT_SPLIT; } inNumber = false; } else { // if following a digit or with-digit-symbol, then consider the number parts as a whole if (inNumber) { curBreak = Break.NONE; } // else if a digit or digit-symbol follows, then consider the number parts as a whole else if (i + 1 < codePoints.length && (Character.isDigit(codePoints[i + 1]) || (i + 2 < codePoints.length && Character.isDigit(codePoints[i + 2])))) { curBreak = Break.NONE; inNumber = true; } else { curBreak = Break.HARD; inNumber = false; } } result[i] = curBreak; } return result; } } private static final class NumberLexicon extends AbstractLexicon { private Category category; public NumberLexicon(Category category) { super(null); this.category = category; } /** * Define applicable categories in the subString. * <p> * In this case, if a digit is found in the subString, then the NUMBER category is added. * * @param subString The substring to define. * @param normalizer The normalizer to use. */ protected void define(StringWrapper.SubString subString, AbstractNormalizer normalizer) { if (!subString.hasDefinitiveDefinition()) { boolean isNumber = true; int lastNumberPos = -1; for (int i = subString.startPos; i < subString.endPos; ++i) { final int cp = subString.stringWrapper.getCodePoint(i); if (cp > '9' || cp < '0') { isNumber = false; break; } lastNumberPos = i; } if (!isNumber) { // check for "text" numbers if (lastNumberPos >= 0 && lastNumberPos == subString.endPos - 3) { // check for number suffix isNumber = TextNumber.isNumberEnding(subString.originalSubString.substring(lastNumberPos + 1).toLowerCase()); } else if (lastNumberPos < 0) { // check for number word isNumber = TextNumber.isNumber(subString.originalSubString.toLowerCase()); } } if (isNumber) { subString.setAttribute("name", NUMBER); subString.addCategory(category); subString.setDefinitive(true); } } } /** * Determine whether the categories container already has category type(s) * that this lexicon would add. * <p> * NOTE: this is used to avoid calling "define" when categories already exist * for the substring. * * @return true if this lexicon's category type(s) are already present. */ protected boolean alreadyHasTypes(Categories categories) { return categories.hasType(category); } } private static final class UnknownLexicon extends AbstractLexicon { private Category category; public UnknownLexicon(Category category) { super(null); this.category = category; } /** * Define applicable categories in the subString. * <p> * In this case, if a digit is found in the subString, then the NUMBER category is added. * * @param subString The substring to define. * @param normalizer The normalizer to use. */ protected void define(StringWrapper.SubString subString, AbstractNormalizer normalizer) { if (!subString.hasDefinitiveDefinition() && subString.length() == 1) { subString.addCategory(category); subString.setAttribute("name", UNDETERMINED_WORD); } } /** * Determine whether the categories container already has category type(s) * that this lexicon would add. * <p> * NOTE: this is used to avoid calling "define" when categories already exist * for the substring. * * @return true if this lexicon's category type(s) are already present. */ protected boolean alreadyHasTypes(Categories categories) { return categories.hasType(category); } } /** * Container class for a word. */ public static final class Word { public final StringWrapper.SubString word; public final String type; private Integer _score; public Word(StringWrapper.SubString word, String type) { this.word = word; this.type = type; this._score = null; } /** * Get this word's score. * <p> * A word's score is its number of defined letters. */ public int getScore() { if (_score == null) { _score = UNDETERMINED_WORD.equals(type) ? 0 : word.length() * word.length(); } return _score; } public String toString() { final StringBuilder result = new StringBuilder(); result.append(type).append('=').append(word.originalSubString); return result.toString(); } } /** * Container for a sequence of words for a string. */ public static final class WordSequence { public final String string; public final List<Word> words; private int score; public WordSequence(Tree<StringWrapper.SubString> leaf) { final LinkedList<Word> theWords = new LinkedList<Word>(); this.words = theWords; this.score = 0; String theString = null; while (leaf != null) { final StringWrapper.SubString subString = leaf.getData(); if (subString == null) break; // hit root. final String nameValue = subString.getAttribute("name"); final Word word = new Word(subString, nameValue == null ? UNDETERMINED_WORD : nameValue); theWords.addFirst(word); score += word.getScore(); if (theString == null) theString = subString.stringWrapper.string; leaf = leaf.getParent(); } this.string = theString; } /** * Get this sequence's score. * <p> * The score is the total number of defined letters in the sequence's words. */ public int getScore() { return score; } public int size() { return words.size(); } public String toString() { return asString(","); } public String asString(String delim) { final StringBuilder result = new StringBuilder(); for (Iterator<Word> wordIter = words.iterator(); wordIter.hasNext(); ) { final Word word = wordIter.next(); result.append(word.toString()); if (wordIter.hasNext()) result.append(delim); } // result.append('(').append(getScore()).append(')'); return result.toString(); } } //java -Xmx640m org.sd.nlp.MungedWordFinder wordSet="foo,bar,baz" wordSetName="fbb" foobarbaz "foo-bar-baz" "foobArbaz" gesundheit public static final void main(String[] args) throws IOException { // properties: // wordFiles="file1,file2,..." // wordSet="word1,word2,..." // wordSetName="name" // non-property arguments are munged strings to split. // STDIN has other munged strings or domains to split. final PropertiesParser propertiesParser = new PropertiesParser(args); final Properties properties = propertiesParser.getProperties(); final String wordFileNames = properties.getProperty("wordFiles"); final String wordSet = properties.getProperty("wordSet"); final String wordSetName = properties.getProperty("wordSetName"); final MungedWordFinder mungedWordFinder = new MungedWordFinder(); if (wordFileNames != null) { for (String wordFile : wordFileNames.split("\\s*,\\s*")) { final File file = new File(wordFile); mungedWordFinder.addWordFile(file.getName().split("\\.")[0], file); } } if (wordSet != null) { mungedWordFinder.addWordSet(wordSetName, wordSet.split("\\s*,\\s*")); } final String[] mungedWords = propertiesParser.getArgs(); for (String mungedWord : mungedWords) { final List<WordSequence> splits = mungedWordFinder.getBestDomainSplits(mungedWord); final String splitsString = mungedWordFinder.getSplitsAsString(splits); System.out.println(mungedWord + "|" + splitsString); } final BufferedReader reader = FileUtil.getReader(System.in); String line = null; while ((line = reader.readLine()) != null) { final List<WordSequence> splits = mungedWordFinder.getBestDomainSplits(line); final String splitsString = mungedWordFinder.getSplitsAsString(splits); System.out.println(line + "|" + splitsString); } reader.close(); } }
jtsay362/semanticdiscoverytoolkit-text
src/main/java/org/sd/text/MungedWordFinder.java
Java
lgpl-3.0
17,721
/******************************************************************************* * Copyright (c) 2015 Open Software Solutions GmbH. * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3.0 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl-3.0.html * * Contributors: * Open Software Solutions GmbH ******************************************************************************/ package org.oss.pdfreporter.sql.factory; import java.io.InputStream; import java.util.Date; import org.oss.pdfreporter.sql.IBlob; import org.oss.pdfreporter.sql.IConnection; import org.oss.pdfreporter.sql.IDate; import org.oss.pdfreporter.sql.IDateTime; import org.oss.pdfreporter.sql.ITime; import org.oss.pdfreporter.sql.ITimestamp; import org.oss.pdfreporter.sql.SQLException; /** * Sql connectivity factory. * The interface supports queries with prepared statements. * No DDL or modifying operations are supported, neither transactions or cursors. * @author donatmuller, 2013, last change 5:39:58 PM */ public interface ISqlFactory { /** * Returns a connection for the connection parameter. * It is up to the implementor to define the syntax of the connection parameter.<br> * The parameter could include a driver class name or just an url and assume that a driver * was already loaded. * @param url * @param user * @param password * @return */ IConnection newConnection(String url, String user, String password) throws SQLException; /** * used by dynamic loading of specific database driver and JDBC-URL, when the implementation don't know about the specific driver-implementation. * @param jdbcUrl * @param user * @param password * @return * @throws SQLException */ IConnection createConnection(String jdbcUrl, String user, String password) throws SQLException; /** * Creates a Date. * @param date * @return */ IDate newDate(Date date); /** * Creates a Time. * @param time * @return */ ITime newTime(Date time); /** * Creates a Timestamp. * @param timestamp * @return */ ITimestamp newTimestamp(long milliseconds); /** * Creates a DateTime. * @param datetime * @return */ IDateTime newDateTime(Date datetime); /** * Creates a Blob. * @param is * @return */ IBlob newBlob(InputStream is); /** * Creates a Blob. * @param bytes * @return */ IBlob newBlob(byte[] bytes); }
OpenSoftwareSolutions/PDFReporter
pdfreporter-core/src/org/oss/pdfreporter/sql/factory/ISqlFactory.java
Java
lgpl-3.0
2,507
/* * Copyright (C) 2005-2010 Alfresco Software Limited. * * This file is part of Alfresco * * Alfresco is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Alfresco is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Alfresco. If not, see <http://www.gnu.org/licenses/>. */ package org.alfresco.repo.admin.registry; import java.io.Serializable; import java.util.Collection; /** * Interface for service providing access to key-value pairs for storage * of system-controlled metadata. * * @author Derek Hulley */ public interface RegistryService { /** * Assign a value to the registry key, which must be of the form <b>/a/b/c</b>. * * @param key the registry key. * @param value any value that can be stored in the repository. */ void addProperty(RegistryKey key, Serializable value); /** * @param key the registry key. * @return Returns the value stored in the key or <tt>null</tt> if * no value exists at the path and name provided * * @see #addProperty(String, Serializable) */ Serializable getProperty(RegistryKey key); /** * Fetches all child elements for the given path. The key's property should be * <tt>null</tt> as it is completely ignored. * <code><pre> * ... * registryService.addValue(KEY_A_B_C_1, VALUE_ONE); * registryService.addValue(KEY_A_B_C_2, VALUE_TWO); * ... * assertTrue(registryService.getChildElements(KEY_A_B_null).contains("C")); * ... * </pre></code> * * @param key the registry key with the path. The last element in the path * will be ignored, and can be any acceptable value localname or <tt>null</tt>. * @return Returns all child elements (not values) for the given key, ignoring * the last element in the key. * * @see RegistryKey#getPath() */ Collection<String> getChildElements(RegistryKey key); /** * Copies the path or value from the source to the target location. The source and target * keys <b>must</b> be both either path-specific or property-specific. If the source doesn't * exist, then nothing will be done; there is no guarantee that the target will exist after * the call. * <p> * This is essentially a merge operation. Use {@link #delete(RegistryKey) delete} first * if the target must be cleaned. * * @param sourceKey the source registry key to take values from * @param targetKey the target registyr key to move the path or value to */ void copy(RegistryKey sourceKey, RegistryKey targetKey); /** * Delete the path element or value described by the key. If the key points to nothing, * then nothing is done. * <code>delete(/a/b/c)</code> will remove value <b>c</b> from path <b>/a/b</b>.<br/> * <code>delete(/a/b/null)</code> will remove node <b>/a/b</b> along with all values and child * elements. * * @param key the path or value to delete */ void delete(RegistryKey key); }
loftuxab/community-edition-old
projects/repository/source/java/org/alfresco/repo/admin/registry/RegistryService.java
Java
lgpl-3.0
3,781
import java.util.*; import Jakarta.util.FixDosOutputStream; import java.io.*; //------------------------ j2jBase layer ------------------- //------ mixin-layer for dealing with Overrides and New Modifier //------ offhand, I wonder why we can't let j2j map these modifiers //------ to nothing, instead of letting PJ do some of this mapping // it would make more sense for PJ and Mixin to have similar // output. public class ModOverrides { public void reduce2java( AstProperties props ) { // Step 1: the overrides modifier should not be present, UNLESS // there is a SoUrCe property. It's an error otherwise. if ( props.getProperty( "SoUrCe" ) == null ) { AstNode.error( tok[0], "overrides modifier should not be present" ); return; } // Step 2: it's OK to be present. If so, the reduction is to // print the white-space in front for pretty-printing props.print( getComment() ); } }
SergiyKolesnikov/fuji
examples/AHEAD/j2jBase/ModOverrides.java
Java
lgpl-3.0
1,048
/* * Copyright (C) 2003-2014 eXo Platform SAS. * * 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.exoplatform.social.core.storage.proxy; import java.lang.reflect.Proxy; import org.exoplatform.social.core.activity.model.ExoSocialActivity; /** * Created by The eXo Platform SAS * Author : eXoPlatform * [email protected] * Apr 28, 2014 */ public class ActivityProxyBuilder { @SuppressWarnings("unchecked") static <T> T of(ProxyInvocation invocation) { Class<?> targetClass = invocation.getTargetClass(); //1. loader - the class loader to define the proxy class //2. the list of interfaces for the proxy class to implement //3. the invocation handler to dispatch method invocations to return (T) Proxy.newProxyInstance(targetClass.getClassLoader(), new Class<?>[]{targetClass}, invocation); } public static <T> T of(Class<T> aClass, ExoSocialActivity activity) { return of(new ProxyInvocation(aClass, activity)); } }
thanhvc/poc-sam
services/src/main/java/org/exoplatform/social/core/storage/proxy/ActivityProxyBuilder.java
Java
lgpl-3.0
1,655
/* * XAdES4j - A Java library for generation and verification of XAdES signatures. * Copyright (C) 2010 Luis Goncalves. * * XAdES4j is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or any later version. * * XAdES4j is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License along * with XAdES4j. If not, see <http://www.gnu.org/licenses/>. */ package xades4j.xml.unmarshalling; import xades4j.algorithms.Algorithm; import xades4j.properties.SignatureTimeStampProperty; import xades4j.properties.data.SignatureTimeStampData; import xades4j.xml.bind.xades.XmlUnsignedSignaturePropertiesType; /** * * @author Luís */ class FromXmlSignatureTimeStampConverter extends FromXmlBaseTimeStampConverter<SignatureTimeStampData> implements UnsignedSigPropFromXmlConv { FromXmlSignatureTimeStampConverter() { super(SignatureTimeStampProperty.PROP_NAME); } @Override public void convertFromObjectTree( XmlUnsignedSignaturePropertiesType xmlProps, QualifyingPropertiesDataCollector propertyDataCollector) throws PropertyUnmarshalException { super.convertTimeStamps(xmlProps.getSignatureTimeStamp(), propertyDataCollector); } @Override protected SignatureTimeStampData createTSData(Algorithm c14n) { return new SignatureTimeStampData(c14n); } @Override protected void setTSData( SignatureTimeStampData tsData, QualifyingPropertiesDataCollector propertyDataCollector) { propertyDataCollector.addSignatureTimeStamp(tsData); } }
entaksi/xades4j
src/main/java/xades4j/xml/unmarshalling/FromXmlSignatureTimeStampConverter.java
Java
lgpl-3.0
1,991
/* * Unitex * * Copyright (C) 2001-2014 Université Paris-Est Marne-la-Vallée <[email protected]> * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * */ package fr.umlv.unitex.cassys; public class ConfigurationFileAnalyser { private String fileName; private boolean mergeMode; private boolean replaceMode; private boolean disabled; private boolean star; private boolean commentFound; /** * @return the fileName */ public String getFileName() { return fileName; } /** * @return the mergeMode */ public boolean isMergeMode() { return mergeMode; } /** * @return the replaceMode */ public boolean isReplaceMode() { return replaceMode; } /** * @return the commentFound */ public boolean isCommentFound() { return commentFound; } /** * * @return disabled */ public boolean isDisabled(){ return disabled; } public boolean isStar(){ return star; } public ConfigurationFileAnalyser(String line) throws EmptyLineException, InvalidLineException { // extract line comment final String lineSubstring[] = line.split("#", 2); if (lineSubstring.length > 1) { commentFound = true; } if (lineSubstring[0] == null || lineSubstring[0].equals("")) { throw new EmptyLineException(); } final String lineCore[] = lineSubstring[0].split(" "); if (!lineCore[0].startsWith("\"") || !lineCore[0].endsWith("\"")) { throw new InvalidLineException(lineSubstring[0] + " --> FileName must start and end with quote\n"); } lineCore[0] = lineCore[0].substring(1, lineCore[0].length() - 1); if (lineCore.length > 1) { fileName = lineCore[0]; if (lineCore[1].equals("M") || lineCore[1].equals("Merge") || lineCore[1].equals("merge")) { mergeMode = true; replaceMode = false; } else if (lineCore[1].equals("R") || lineCore[1].equals("Replace") || lineCore[1].equals("replace")) { mergeMode = false; replaceMode = true; } else { throw new InvalidLineException(lineSubstring[0] + " --> Second argument should be Merge or Replace\n"); } } else { throw new InvalidLineException( lineSubstring[0] + " --> FileName should be followed by a white space and Merge or Replace\n"); } if(lineCore.length>2){ if(lineCore[2].equals("Disabled")||lineCore[2].equals("Disabled")){ disabled = true; } else if(lineCore[2].equals("Enabled")){ disabled = false; } else { throw new InvalidLineException(lineSubstring[0] + " --> Third argument should be Disabled or Enabled\n"); } if(lineCore.length>3){ if(lineCore[3].equals("*")){ star = true; } else if(lineCore[3].equals("1")){ star = false; } else { throw new InvalidLineException(lineSubstring[0] + " --> Fourth argument should be 1 or *\n"); } } else { star = false; } } else { disabled = false; star = false; } } public class InvalidLineException extends Exception { public InvalidLineException(String s) { super(s); } public InvalidLineException() { /* NOP */ } } public class EmptyLineException extends Exception { public EmptyLineException() { /* NOP */ } } }
mdamis/unilabIDE
Unitex-Java/src/fr/umlv/unitex/cassys/ConfigurationFileAnalyser.java
Java
lgpl-3.0
3,912
/* * #-------------------------------------------------------------------------- * # Copyright (c) 2013 VITRO FP7 Consortium. * # All rights reserved. This program and the accompanying materials * # are made available under the terms of the GNU Lesser Public License v3.0 which accompanies this distribution, and is available at * # http://www.gnu.org/licenses/lgpl-3.0.html * # * # Contributors: * # Antoniou Thanasis (Research Academic Computer Technology Institute) * # Paolo Medagliani (Thales Communications & Security) * # D. Davide Lamanna (WLAB SRL) * # Alessandro Leoni (WLAB SRL) * # Francesco Ficarola (WLAB SRL) * # Stefano Puglia (WLAB SRL) * # Panos Trakadas (Technological Educational Institute of Chalkida) * # Panagiotis Karkazis (Technological Educational Institute of Chalkida) * # Andrea Kropp (Selex ES) * # Kiriakos Georgouleas (Hellenic Aerospace Industry) * # David Ferrer Figueroa (Telefonica Investigación y Desarrollo S.A.) * # * #-------------------------------------------------------------------------- */ package vitro.vspEngine.service.common.abstractservice.dao; import javax.persistence.EntityManager; import vitro.vspEngine.logic.model.Gateway; import vitro.vspEngine.service.common.abstractservice.model.ServiceInstance; import vitro.vspEngine.service.persistence.DBRegisteredGateway; import java.util.List; public class GatewayDAO { private static GatewayDAO instance = new GatewayDAO(); private GatewayDAO(){ super(); } public static GatewayDAO getInstance(){ return instance; } /** * * @param manager * @param incId the incremental auto id in the db * @return */ public DBRegisteredGateway getGatewayByIncId(EntityManager manager, int incId){ DBRegisteredGateway dbRegisteredGateway = manager.find(DBRegisteredGateway.class, incId); return dbRegisteredGateway; } /** * * @param manager * @param name the gateway (registered) name * @return */ public DBRegisteredGateway getGateway(EntityManager manager, String name){ StringBuffer sb = new StringBuffer(); sb.append("SELECT g "); sb.append("FROM DBRegisteredGateway g "); sb.append("WHERE g.registeredName = :gname "); DBRegisteredGateway result = manager.createQuery(sb.toString(), DBRegisteredGateway.class). setParameter("gname", name). getSingleResult(); return result; } public List<DBRegisteredGateway> getInstanceList(EntityManager manager){ List<DBRegisteredGateway> result = manager.createQuery("SELECT instance FROM DBRegisteredGateway instance", DBRegisteredGateway.class).getResultList(); return result; } }
vitrofp7/vitro
source/trunk/Demo/vitroUI/vspEngine/src/main/java/vitro/vspEngine/service/common/abstractservice/dao/GatewayDAO.java
Java
lgpl-3.0
2,739
package org.teaminfty.math_dragon.view.math.source.operation; import static org.teaminfty.math_dragon.view.math.Expression.lineWidth; import org.teaminfty.math_dragon.view.math.Empty; import org.teaminfty.math_dragon.view.math.source.Expression; import android.graphics.Canvas; import android.graphics.Paint; import android.graphics.Path; import android.graphics.Rect; /** A class that represents a source for new {@link Root}s in the drag-and-drop interface */ public class Root extends Expression { /** The paint we use to draw the operator */ private Paint paintOperator = new Paint(); /** Default constructor */ public Root() { // Initialise the paint paintOperator.setStyle(Paint.Style.STROKE); paintOperator.setAntiAlias(true); } @Override public org.teaminfty.math_dragon.view.math.Expression createMathObject() { return new org.teaminfty.math_dragon.view.math.operation.binary.Root(); } @Override public void draw(Canvas canvas, int w, int h) { // The width of the gap between the big box and the small box final int gapWidth = (int) (3 * lineWidth); // Get a boxes that fit the given width and height (we'll use it to draw the empty boxes) // We'll want one big and one small (2/3 times the big one) box Rect bigBox = getRectBoundingBox(3 * (w - gapWidth) / 5, 3 * h / 4, Empty.RATIO); Rect smallBox = getRectBoundingBox(2 * (w - gapWidth) / 5, 2 * h / 4, Empty.RATIO); // Position the boxes smallBox.offsetTo((w - bigBox.width() - smallBox.width() - gapWidth) / 2, (h - bigBox.height() - smallBox.height() / 2) / 2); bigBox.offsetTo(smallBox.right + gapWidth, smallBox.centerY()); // Draw the boxes drawEmptyBox(canvas, bigBox); drawEmptyBox(canvas, smallBox); // Create a path for the operator Path path = new Path(); path.moveTo(smallBox.left, smallBox.bottom + 2 * lineWidth); path.lineTo(smallBox.right - 2 * lineWidth, smallBox.bottom + 2 * lineWidth); path.lineTo(smallBox.right + 1.5f * lineWidth, bigBox.bottom - lineWidth / 2); path.lineTo(smallBox.right + 1.5f * lineWidth, bigBox.top - 2 * lineWidth); path.lineTo(bigBox.right, bigBox.top - 2 * lineWidth); // Draw the operator paintOperator.setStrokeWidth(lineWidth); canvas.drawPath(path, paintOperator); } }
Divendo/math-dragon
mathdragon/src/main/java/org/teaminfty/math_dragon/view/math/source/operation/Root.java
Java
lgpl-3.0
2,494
package br.gov.serpro.infoconv.proxy.businesscontroller; import java.lang.reflect.Field; import java.util.ArrayList; import java.util.List; import javax.inject.Inject; import br.gov.frameworkdemoiselle.stereotype.BusinessController; import br.gov.serpro.infoconv.proxy.exception.AcessoNegadoException; import br.gov.serpro.infoconv.proxy.exception.CNPJNaoEncontradoException; import br.gov.serpro.infoconv.proxy.exception.CpfNaoEncontradoException; import br.gov.serpro.infoconv.proxy.exception.DadosInvalidosException; import br.gov.serpro.infoconv.proxy.exception.InfraException; import br.gov.serpro.infoconv.proxy.exception.PerfilInvalidoException; import br.gov.serpro.infoconv.proxy.rest.dto.cnpj.Perfil1CNPJ; import br.gov.serpro.infoconv.proxy.rest.dto.cnpj.Perfil2CNPJ; import br.gov.serpro.infoconv.proxy.rest.dto.cnpj.Perfil3CNPJ; import br.gov.serpro.infoconv.proxy.util.InfoconvConfig; import br.gov.serpro.infoconv.ws.cnpj.ArrayOfCNPJPerfil1; import br.gov.serpro.infoconv.ws.cnpj.ArrayOfCNPJPerfil2; import br.gov.serpro.infoconv.ws.cnpj.ArrayOfCNPJPerfil3; import br.gov.serpro.infoconv.ws.cnpj.CNPJPerfil1; import br.gov.serpro.infoconv.ws.cnpj.CNPJPerfil2; import br.gov.serpro.infoconv.ws.cnpj.CNPJPerfil3; /** * Classe responsável por interagir com o componente infoconv-ws para obter as * consultas de cnpj e transformar os erros previstos em exceções. * */ @BusinessController public class ConsultaCNPJBC { /** Classe de configuração do infoconv. */ @Inject InfoconvConfig infoconv; private static final String CPF_CONSULTANTE = "79506240949"; /** * Verifica a propriedade ERRO para saber se houve algum problema na * consulta. * * Como se trata de um webservice sempre retorna com codigo http 200 e * dentro da msg de retorno o campo "erro" informa se teve algum problema. * * Alguns "erros" são na verdade avisos por isso não levantam exceção. segue * os erros que levantam exceção: * * - AcessoNegadoException: Todos os erros que começãm com ACS - Erro. Podem * ser por falta de permissão ou algum problema com certificado. A mensagem * explica qual o problema. * * - CNPJNaoEncontradoException: Quando o cpf não está na base. Erros: CPJ * 04 * * - DadosInvalidosException: Qualquer problema de validação no servidor. * Erros: CPJ 02,06 e 11 * * - InfraException: Erros no lado do servidor (WS) Erros: CPF 00 , 01, 03, * 08, 09 * * Documentação dos códigos de Erros: * https://github.com/infoconv/infoconv-ws * * @param response * @throws AcessoNegadoException * @throws DadosInvalidosException * @throws InfraException * @throws CNPJNaoEncontradoException */ private void verificarErros(final Object retorno) throws AcessoNegadoException, DadosInvalidosException, InfraException, CNPJNaoEncontradoException { try { Class<?> c = retorno.getClass(); Field erroField = c.getDeclaredField("erro"); erroField.setAccessible(true); String erroMsg = (String) erroField.get(retorno); if (erroMsg.indexOf("ACS - Erro") > -1) { throw new AcessoNegadoException(erroMsg); } else if (erroMsg.indexOf("CPJ - Erro 04") > -1) { throw new CNPJNaoEncontradoException(erroMsg); } else if (erroMsg.indexOf("CPJ - Erro 02") > -1 || erroMsg.indexOf("CPJ - Erro 06") > -1 || erroMsg.indexOf("CPJ - Erro 11") > -1) { throw new DadosInvalidosException(erroMsg); } else if (erroMsg.indexOf("CPJ - Erro 01") > -1 || erroMsg.indexOf("CPJ - Erro 03") > -1 || erroMsg.indexOf("CPJ - Erro 00") > -1 || erroMsg.indexOf("CPJ - Erro 08") > -1 || erroMsg.indexOf("CPJ - Erro 09") > -1) { throw new InfraException(erroMsg); } } catch (NoSuchFieldException e) { e.printStackTrace(); } catch (SecurityException e) { e.printStackTrace(); } catch (IllegalArgumentException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } } /** * Baseado no perfil indicado monta uma lista generia com o tipo de CNPJ do * perfil como Object. * * @param listaCNPJs * @param perfil * @return * @throws PerfilInvalidoException * @throws InfraException * @throws DadosInvalidosException * @throws AcessoNegadoException * @throws CNPJNaoEncontradoException */ public List<Object> consultarListaDeCnpjPorPerfil(final String listaCNPJs, final String perfil) throws PerfilInvalidoException, AcessoNegadoException, DadosInvalidosException, InfraException, CNPJNaoEncontradoException { List<Object> lista = new ArrayList<Object>(); String perfilUpper = perfil.toUpperCase(); if (perfil == null || "P1".equals(perfilUpper)) { ArrayOfCNPJPerfil1 p = infoconv.consultarCNPJSoap.consultarCNPJP1(listaCNPJs, CPF_CONSULTANTE); lista.addAll(p.getCNPJPerfil1()); } else if ("P1T".equals(perfilUpper)) { ArrayOfCNPJPerfil1 p = infoconv.consultarCNPJSoap.consultarCNPJP1T(listaCNPJs, CPF_CONSULTANTE); lista.addAll(p.getCNPJPerfil1()); } else if ("P2".equals(perfilUpper)) { ArrayOfCNPJPerfil2 p = infoconv.consultarCNPJSoap.consultarCNPJP2(listaCNPJs, CPF_CONSULTANTE); lista.addAll(p.getCNPJPerfil2()); } else if ("P2T".equals(perfilUpper)) { ArrayOfCNPJPerfil2 p = infoconv.consultarCNPJSoap.consultarCNPJP2T(listaCNPJs, CPF_CONSULTANTE); lista.addAll(p.getCNPJPerfil2()); } else if ("P3".equals(perfilUpper)) { ArrayOfCNPJPerfil3 p = infoconv.consultarCNPJSoap.consultarCNPJP3(listaCNPJs, CPF_CONSULTANTE); lista.addAll(p.getCNPJPerfil3()); } else if ("P3T".equals(perfilUpper)) { ArrayOfCNPJPerfil3 p = infoconv.consultarCNPJSoap.consultarCNPJP3T(listaCNPJs, CPF_CONSULTANTE); lista.addAll(p.getCNPJPerfil3()); } else { throw new PerfilInvalidoException(); } verificarErros(lista.get(0)); return lista; } /** * Consulta o webservice do infoconv ConsultarCNPJSoap/ConsultarCNPJP1 * * @param listaCNPJs * @return * @throws AcessoNegadoException * @throws CpfNaoEncontradoException * @throws DadosInvalidosException * @throws InfraException */ public List<Perfil1CNPJ> listarPerfil1(String listaCNPJs) throws AcessoNegadoException, CNPJNaoEncontradoException, DadosInvalidosException, InfraException{ ArrayOfCNPJPerfil1 result = infoconv.consultarCNPJSoap.consultarCNPJP1(listaCNPJs, CPF_CONSULTANTE); verificarErros(result.getCNPJPerfil1().get(0)); List<Perfil1CNPJ> lista = new ArrayList<Perfil1CNPJ>(); for (CNPJPerfil1 perfil1 : result.getCNPJPerfil1()) { lista.add(new Perfil1CNPJ(perfil1)); } return lista; } /** * Consulta o webservice do infoconv ConsultarCNPJSoap/ConsultarCNPJP2 * * @param listaCNPJs * @return * @throws AcessoNegadoException * @throws CpfNaoEncontradoException * @throws DadosInvalidosException * @throws InfraException */ public List<Perfil2CNPJ> listarPerfil2(String listaCNPJs) throws AcessoNegadoException, CNPJNaoEncontradoException, DadosInvalidosException, InfraException{ ArrayOfCNPJPerfil2 result = infoconv.consultarCNPJSoap.consultarCNPJP2(listaCNPJs, CPF_CONSULTANTE); verificarErros(result.getCNPJPerfil2().get(0)); List<Perfil2CNPJ> lista = new ArrayList<Perfil2CNPJ>(); for (CNPJPerfil2 perfil1 : result.getCNPJPerfil2()) { lista.add(new Perfil2CNPJ(perfil1)); } return lista; } /** * Consulta o webservice do infoconv ConsultarCNPJSoap/ConsultarCNPJP3 * * @param listaCNPJs * @return * @throws AcessoNegadoException * @throws CpfNaoEncontradoException * @throws DadosInvalidosException * @throws InfraException */ public List<Perfil3CNPJ> listarPerfil3(String listaCNPJs) throws AcessoNegadoException, CNPJNaoEncontradoException, DadosInvalidosException, InfraException{ ArrayOfCNPJPerfil3 result = infoconv.consultarCNPJSoap.consultarCNPJP3(listaCNPJs, CPF_CONSULTANTE); verificarErros(result.getCNPJPerfil3().get(0)); List<Perfil3CNPJ> lista = new ArrayList<Perfil3CNPJ>(); for (CNPJPerfil3 perfil1 : result.getCNPJPerfil3()) { lista.add(new Perfil3CNPJ(perfil1)); } return lista; } }
infoconv/infoconv-proxy
src/main/java/br/gov/serpro/infoconv/proxy/businesscontroller/ConsultaCNPJBC.java
Java
lgpl-3.0
8,058
/** * This file is part of the CRISTAL-iSE kernel. * Copyright (c) 2001-2015 The CRISTAL Consortium. All rights reserved. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation; either version 3 of the License, or (at * your option) any later version. * * This library is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; with out even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA. * * http://www.fsf.org/licensing/licenses/lgpl.html */ package org.cristalise.kernel.lifecycle.instance.stateMachine; import lombok.Getter; import lombok.Setter; @Getter @Setter public class TransitionQuery { /** * Name & version of the query to be run by the agent during this transition */ String name, version; public TransitionQuery() {} public TransitionQuery(String n, String v) { name = n; version = v; } }
cristal-ise/kernel
src/main/java/org/cristalise/kernel/lifecycle/instance/stateMachine/TransitionQuery.java
Java
lgpl-3.0
1,327
/* ========================================== * JGraphT : a free Java graph-theory library * ========================================== * * Project Info: http://jgrapht.sourceforge.net/ * Project Creator: Barak Naveh (http://sourceforge.net/users/barak_naveh) * * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * This library is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation; either version 2.1 of the License, or * (at your option) any later version. * * This library is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this library; if not, write to the Free Software Foundation, * Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307, USA. */ /* ------------------------- * GraphEdgeChangeEvent.java * ------------------------- * (C) Copyright 2003-2008, by Barak Naveh and Contributors. * * Original Author: Barak Naveh * Contributor(s): Christian Hammer * * $Id: GraphEdgeChangeEvent.java 645 2008-09-30 19:44:48Z perfecthash $ * * Changes * ------- * 10-Aug-2003 : Initial revision (BN); * 11-Mar-2004 : Made generic (CH); * */ package edu.nd.nina.event; /** * An event which indicates that a graph edge has changed, or is about to * change. The event can be used either as an indication <i>after</i> the edge * has been added or removed, or <i>before</i> it is added. The type of the * event can be tested using the {@link * edu.nd.nina.event.GraphChangeEvent#getType()} method. * * @author Barak Naveh * @since Aug 10, 2003 */ public class GraphEdgeChangeEvent<V, E> extends GraphChangeEvent { //~ Static fields/initializers --------------------------------------------- private static final long serialVersionUID = 3618134563335844662L; /** * Before edge added event. This event is fired before an edge is added to a * graph. */ public static final int BEFORE_EDGE_ADDED = 21; /** * Before edge removed event. This event is fired before an edge is removed * from a graph. */ public static final int BEFORE_EDGE_REMOVED = 22; /** * Edge added event. This event is fired after an edge is added to a graph. */ public static final int EDGE_ADDED = 23; /** * Edge removed event. This event is fired after an edge is removed from a * graph. */ public static final int EDGE_REMOVED = 24; //~ Instance fields -------------------------------------------------------- /** * The edge that this event is related to. */ protected E edge; //~ Constructors ----------------------------------------------------------- /** * Constructor for GraphEdgeChangeEvent. * * @param eventSource the source of this event. * @param type the event type of this event. * @param e the edge that this event is related to. */ public GraphEdgeChangeEvent(Object eventSource, int type, E e) { super(eventSource, type); edge = e; } //~ Methods ---------------------------------------------------------------- /** * Returns the edge that this event is related to. * * @return the edge that this event is related to. */ public E getEdge() { return edge; } } // End GraphEdgeChangeEvent.java
tweninger/nina
src/edu/nd/nina/event/GraphEdgeChangeEvent.java
Java
lgpl-3.0
3,785
package edu.mit.blocks.codeblockutil; import java.awt.BorderLayout; import java.awt.Color; import java.awt.Cursor; import java.awt.Dimension; import java.awt.Font; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Point; import java.awt.RenderingHints; import java.awt.Toolkit; import java.awt.event.ActionEvent; import java.awt.event.ActionListener; import java.awt.event.FocusEvent; import java.awt.event.FocusListener; import java.awt.event.InputEvent; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import java.awt.event.MouseEvent; import java.awt.event.MouseListener; import java.awt.event.MouseMotionListener; import java.awt.geom.AffineTransform; import java.awt.geom.GeneralPath; import javax.swing.BorderFactory; import javax.swing.JComponent; import javax.swing.JLabel; import javax.swing.JPanel; import javax.swing.JTextField; import javax.swing.JToolTip; import javax.swing.KeyStroke; import javax.swing.border.Border; import javax.swing.border.CompoundBorder; import javax.swing.border.EmptyBorder; import javax.swing.event.DocumentEvent; import javax.swing.event.DocumentListener; import edu.mit.blocks.renderable.BlockLabel; public class LabelWidget extends JComponent { public static final int DROP_DOWN_MENU_WIDTH = 7; private static final long serialVersionUID = 837647234895L; /** Border of textfield*/ private static final Border textFieldBorder = new CompoundBorder(BorderFactory.createLoweredBevelBorder(), new EmptyBorder(1, 2, 1, 2)); /** Number formatter for this label */ private static final NumberFormatter nf = new NumberFormatter(NumberFormatter.MEDIUM_PRECISION); /** Label that is visable iff editingText is false */ private final ShadowLabel textLabel = new ShadowLabel(); /** TextField that is visable iff editingText is true */ private final BlockLabelTextField textField = new BlockLabelTextField(); /** drop down menu icon */ private final LabelMenu menu = new LabelMenu(); ; /** The label text before user begins edit (applies only to editable labels)*/ private String labelBeforeEdit = ""; /** If this is a number, then only allow nagatvie signs and periods at certain spots */ private boolean isNumber = false; /** Is labelText editable by the user -- default true */ private boolean isEditable = false; /** If focus is true, then show the combo pop up menu */ private boolean isFocused = false; /** Has ComboPopup accessable selections */ private boolean hasSiblings = false; /** True if TEXTFIELD is being edited by user. */ private boolean editingText; /** the background color of the tooltip */ private Color tooltipBackground = new Color(255, 255, 225); private double zoom = 1.0; private BlockLabel blockLabel; /** * BlockLabel Constructor that takes in BlockID as well. * Unfortunately BlockID is needed, so the label can redirect mouse actions. * */ public LabelWidget(String initLabelText, Color fieldColor, Color tooltipBackground) { if (initLabelText == null) { initLabelText = ""; } this.setFocusTraversalKeysEnabled(false);//MOVE DEFAULT FOCUS TRAVERSAL KEYS SUCH AS TABS this.setLayout(new BorderLayout()); this.tooltipBackground = tooltipBackground; this.labelBeforeEdit = initLabelText; //set up textfield colors textField.setForeground(Color.WHITE);//white text textField.setBackground(fieldColor);//background matching block color textField.setCaretColor(Color.WHITE);//white caret textField.setSelectionColor(Color.BLACK);//black highlight textField.setSelectedTextColor(Color.WHITE);//white text when highlighted textField.setBorder(textFieldBorder); textField.setMargin(textFieldBorder.getBorderInsets(textField)); } public void setBlockLabel(BlockLabel blockLabel) { this.blockLabel = blockLabel; } protected void fireTextChanged(String text) { blockLabel.textChanged(text); } protected void fireGenusChanged(String genus) { blockLabel.genusChanged(genus); } protected void fireDimensionsChanged(Dimension value) { blockLabel.dimensionsChanged(value); } protected boolean isTextValid(String text) { return blockLabel.textValid(text); } public void addKeyListenerToTextField(KeyListener l) { textField.addKeyListener(l); } public void addMouseListenerToLabel(MouseListener l) { textLabel.addMouseListener(l); } public void addMouseMotionListenerToLabel(MouseMotionListener l) { textLabel.addMouseMotionListener(l); } ////////////////////////////// //// LABEL CONFIGURATION ///// ///////////////////////////// public void showMenuIcon(boolean show) { if (this.hasSiblings) { isFocused = show; // repaints the menu and items with the new zoom level menu.popupmenu.setZoomLevel(zoom); menu.repaint(); } } /** * setEditingState sets the current editing state of the BlockLabel. * Repaints BlockLabel to reflect the change. */ public void setEditingState(boolean editing) { if (editing) { editingText = true; textField.setText(textLabel.getText().trim()); labelBeforeEdit = textLabel.getText(); this.removeAll(); this.add(textField); textField.grabFocus(); } else { //update to current textfield.text //if text entered was not empty and if it was editing before if (editingText) { //make sure to remove leading and trailing spaces before testing if text is valid //TODO if allow labels to have leading and trailing spaces, will need to modify this if statement if (isTextValid(textField.getText().trim())) { setText(textField.getText()); } else { setText(labelBeforeEdit); } } editingText = false; } } /** * editingText returns if BlockLable is being edited * @return editingText */ public boolean editingText() { return editingText; } /** * setEditable state of BlockLabel * @param isEditable specifying editable state of BlockLabel */ public void setEditable(boolean isEditable) { this.isEditable = isEditable; } /** * isEditable returns if BlockLable is editable * @return isEditable */ public boolean isEditable() { return isEditable; } public void setNumeric(boolean isNumber) { this.isNumber = isNumber; } /** * isEditable returns if BlockLable is editable * @return isEditable */ public boolean isNumeric() { return isNumber; } public void setSiblings(boolean hasSiblings, String[][] siblings) { this.hasSiblings = hasSiblings; this.menu.setSiblings(siblings); } public boolean hasSiblings() { return this.hasSiblings; } /** * set up fonts * @param font */ public void setFont(Font font) { super.setFont(font); textLabel.setFont(font); textField.setFont(font); menu.setFont(font); } /** * sets the tool tip of the label */ public void assignToolTipToLabel(String text) { this.textLabel.setToolTipText(text); } /** * getText * @return String of the current BlockLabel */ public String getText() { return textLabel.getText().trim(); } /** * setText to a NumberFormatted double * @param value */ public void setText(double value) { //check for +/- Infinity if (Math.abs(value - Double.MAX_VALUE) < 1) { updateLabelText("Infinity"); } else if (Math.abs(value + Double.MAX_VALUE) < 1) { updateLabelText("-Infinity"); } else { updateLabelText(nf.format(value)); } } /** * setText to a String (trimmed to remove excess spaces) * @param string */ public void setText(String string) { if (string != null) { updateLabelText(string.trim()); } } /** * setText to a boolean * @param bool */ public void setText(boolean bool) { updateLabelText(bool ? "True" : "False"); } /** * updateLabelText updates labelText and sychronizes textField and textLabel to it * @param text */ public void updateLabelText(String text) { //leave some space to click on if (text.equals("")) { text = " "; } //update the text everywhere textLabel.setText(text); textField.setText(text); //resize to new text updateDimensions(); //the blockLabel needs to update the data in Block this.fireTextChanged(text); //show text label and additional ComboPopup if one exists this.removeAll(); this.add(textLabel, BorderLayout.CENTER); if (hasSiblings) { this.add(menu, BorderLayout.EAST); } } //////////////////// //// RENDERING ///// //////////////////// /** * Updates the dimensions of the textRect, textLabel, and textField to the minimum size needed * to contain all of the text in the current font. */ private void updateDimensions() { Dimension updatedDimension = new Dimension( textField.getPreferredSize().width, textField.getPreferredSize().height); if (this.hasSiblings) { updatedDimension.width += LabelWidget.DROP_DOWN_MENU_WIDTH; } textField.setSize(updatedDimension); textLabel.setSize(updatedDimension); this.setSize(updatedDimension); this.fireDimensionsChanged(this.getSize()); } /** * high lights the text of the editing text field from * 0 to the end of textfield */ public void highlightText() { this.textField.setSelectionStart(0); } /** * Toggles the visual suggestion that this label may be editable depending on the specified * suggest flag and properties of the block and label. If suggest is true, the visual suggestion will display. Otherwise, nothing * is shown. For now, the visual suggestion is a simple white line boder. * Other requirements for indicator to show: * - label type must be NAME * - label must be editable * - block can not be a factory block * @param suggest */ protected void suggestEditable(boolean suggest) { if (isEditable) { if (suggest) { setBorder(BorderFactory.createLineBorder(Color.white));//show white border } else { setBorder(null);//hide white border } } } public void setZoomLevel(double newZoom) { this.zoom = newZoom; Font renderingFont;// = new Font(font.getFontName(), font.getStyle(), (int)(font.getSize()*newZoom)); AffineTransform at = new AffineTransform(); at.setToScale(newZoom, newZoom); renderingFont = this.getFont().deriveFont(at); this.setFont(renderingFont); this.repaint(); this.updateDimensions(); } public String toString() { return "Label at " + this.getLocation() + " with text: \"" + textLabel.getText() + "\""; } /** * returns true if this block should can accept a negative sign */ public boolean canProcessNegativeSign() { if (this.getText() != null && this.getText().contains("-")) { //if it already has a negative sign, //make sure we're highlighting it if (textField.getSelectedText() != null && textField.getSelectedText().contains("-")) { return true; } else { return false; } } else { //if it does not have negative sign, //make sure our highlight covers index 0 if (textField.getCaretPosition() == 0) { return true; } else { if (textField.getSelectionStart() == 0) { return true; } } } return false; } /** * BlockLabelTextField is a java JtextField that internally handles various events * and provides the semantic to interface with the user. Unliek typical JTextFields, * the blockLabelTextField allows clients to only enter certain keys board input. * It also reacts to enters and escapse by delegating the KeyEvent to the parent * RenderableBlock. */ private class BlockLabelTextField extends JTextField implements MouseListener, DocumentListener, FocusListener, ActionListener { private static final long serialVersionUID = 873847239234L; /** These Key inputs are processed by this text field */ private final char[] validNumbers = {'1', '2', '3', '4', '5', '6', '7', '8', '9', '0', '.'}; /** These Key inputs are processed by this text field if NOT a number block*/ private final char[] validChar = {'1', '2', '3', '4', '5', '6', '7', '8', '9', '0', 'q', 'w', 'e', 'r', 't', 'y', 'u', 'i', 'o', 'p', 'a', 's', 'd', 'f', 'g', 'h', 'j', 'k', 'l', 'z', 'x', 'c', 'v', 'b', 'n', 'm', 'Q', 'W', 'E', 'R', 'T', 'Y', 'U', 'I', 'O', 'P', 'A', 'S', 'D', 'F', 'G', 'H', 'J', 'K', 'L', 'Z', 'X', 'C', 'V', 'B', 'N', 'M', '\'', '!', '@', '#', '$', '%', '^', '&', '*', '(', ')', '_', '+', '-', '=', '{', '}', '|', '[', ']', '\\', ' ', ':', '"', ';', '\'', '<', '>', '?', ',', '.', '/', '`', '~'}; /** These Key inputs are processed by all this text field */ private final int[] validMasks = {KeyEvent.VK_BACK_SPACE, KeyEvent.VK_UP, KeyEvent.VK_DOWN, KeyEvent.VK_LEFT, KeyEvent.VK_RIGHT, KeyEvent.VK_END, KeyEvent.VK_HOME, '-', KeyEvent.VK_DELETE, KeyEvent.VK_SHIFT, KeyEvent.VK_CONTROL, InputEvent.SHIFT_MASK, InputEvent.SHIFT_DOWN_MASK}; /** * Contructs new block label text field */ private BlockLabelTextField() { this.addActionListener(this); this.getDocument().addDocumentListener(this); this.addFocusListener(this); this.addMouseListener(this); /* * Sets whether focus traversal keys are enabled * for this Component. Components for which focus * traversal keys are disabled receive key events * for focus traversal keys. */ this.setFocusTraversalKeysEnabled(false); } public void mousePressed(MouseEvent e) { } public void mouseReleased(MouseEvent e) { } public void mouseEntered(MouseEvent e) { } public void mouseClicked(MouseEvent e) { } public void mouseExited(MouseEvent arg0) { //remove the white line border //note: make call here since text fields consume mouse events //preventing parent from responding to mouse exited events suggestEditable(false); } public void actionPerformed(ActionEvent e) { setEditingState(false); } public void changedUpdate(DocumentEvent e) { //listens for change in attributes } public void insertUpdate(DocumentEvent e) { updateDimensions(); } public void removeUpdate(DocumentEvent e) { updateDimensions(); } public void focusGained(FocusEvent e) { } public void focusLost(FocusEvent e) { setEditingState(false); } /** * for all user-generated AND/OR system generated key inputs, * either perform some action that should be triggered by * that key or */ protected boolean processKeyBinding(KeyStroke ks, KeyEvent e, int condition, boolean pressed) { if (isNumber) { if (e.getKeyChar() == '-' && canProcessNegativeSign()) { return super.processKeyBinding(ks, e, condition, pressed); } if (this.getText().contains(".") && e.getKeyChar() == '.') { return false; } for (char c : validNumbers) { if (e.getKeyChar() == c) { return super.processKeyBinding(ks, e, condition, pressed); } } } else { for (char c : validChar) { if (e.getKeyChar() == c) { return super.processKeyBinding(ks, e, condition, pressed); } } } for (int i : validMasks) { if (e.getKeyCode() == i) { return super.processKeyBinding(ks, e, condition, pressed); } } if ((e.getModifiers() & Toolkit.getDefaultToolkit().getMenuShortcutKeyMask()) != 0) { return super.processKeyBinding(ks, e, condition, pressed); } return false; } } private class LabelMenu extends JPanel implements MouseListener, MouseMotionListener { private static final long serialVersionUID = 328149080240L; private CPopupMenu popupmenu; private GeneralPath triangle; private LabelMenu() { this.setOpaque(false); this.addMouseListener(this); this.addMouseMotionListener(this); this.setCursor(new Cursor(Cursor.DEFAULT_CURSOR)); this.popupmenu = new CPopupMenu(); } /** * @param siblings = array of siblin's genus and initial label * { {genus, label}, {genus, label}, {genus, label} ....} */ private void setSiblings(String[][] siblings) { popupmenu = new CPopupMenu(); //if connected to a block, add self and add siblings for (int i = 0; i < siblings.length; i++) { final String selfGenus = siblings[i][0]; CMenuItem selfItem = new CMenuItem(siblings[i][1]); selfItem.addActionListener(new ActionListener() { public void actionPerformed(ActionEvent e) { fireGenusChanged(selfGenus); showMenuIcon(false); } }); popupmenu.add(selfItem); } } public boolean contains(Point p) { return triangle != null && triangle.contains(p); } public boolean contains(int x, int y) { return triangle != null && triangle.contains(x, y); } public void paint(Graphics g) { super.paint(g); if (isFocused) { Graphics2D g2 = (Graphics2D) g; g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); triangle = new GeneralPath(); triangle.moveTo(0, this.getHeight() / 4); triangle.lineTo(this.getWidth() - 1, this.getHeight() / 4); triangle.lineTo(this.getWidth() / 2 - 1, this.getHeight() / 4 + LabelWidget.DROP_DOWN_MENU_WIDTH); triangle.lineTo(0, this.getHeight() / 4); triangle.closePath(); g2.setColor(new Color(255, 255, 255, 100)); g2.fill(triangle); g2.setColor(Color.BLACK); g2.draw(triangle); } } public void mouseEntered(MouseEvent e) { } public void mouseExited(MouseEvent e) { } public void mousePressed(MouseEvent e) { if (hasSiblings) { popupmenu.show(this, 0, 0); } } public void mouseReleased(MouseEvent e) { } public void mouseClicked(MouseEvent e) { } public void mouseDragged(MouseEvent e) { } public void mouseMoved(MouseEvent e) { } } /** * Much like a JLabel, only the text is displayed with a shadow like outline */ private class ShadowLabel extends JLabel implements MouseListener, MouseMotionListener { private static final long serialVersionUID = 90123787382L; //To get the shadow effect the text must be displayed multiple times at //multiple locations. x represents the center, white label. // o is color values (0,0,0,0.5f) and b is black. // o o // o x b o // o b o // o //offsetArrays representing the translation movement needed to get from // the center location to a specific offset location given in {{x,y},{x,y}....} //..........................................grey points.............................................black points private final int[][] shadowPositionArray = {{0, -1}, {1, -1}, {-1, 0}, {2, 0}, {-1, 1}, {1, 1}, {0, 2}, {1, 0}, {0, 1}}; private final float[] shadowColorArray = {0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0.5f, 0, 0}; private double offsetSize = 1; private ShadowLabel() { this.addMouseListener(this); this.addMouseMotionListener(this); } public void paint(Graphics g) { Graphics2D g2 = (Graphics2D) g; g2.addRenderingHints(new RenderingHints(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON)); //DO NOT DRAW SUPER's to prevent drawing of label's string. //Implecations: background not automatically drawn //super.paint(g); //draw shadows for (int i = 0; i < shadowPositionArray.length; i++) { int dx = shadowPositionArray[i][0]; int dy = shadowPositionArray[i][1]; g2.setColor(new Color(0, 0, 0, shadowColorArray[i])); g2.drawString(this.getText(), (int) ((4 + dx) * offsetSize), this.getHeight() + (int) ((dy - 6) * offsetSize)); } //draw main Text g2.setColor(Color.white); g2.drawString(this.getText(), (int) ((4) * offsetSize), this.getHeight() + (int) ((-6) * offsetSize)); } public JToolTip createToolTip() { return new CToolTip(tooltipBackground); } /** * Set to editing state upon mouse click if this block label is editable */ public void mouseClicked(MouseEvent e) { //if clicked and if the label is editable, if ((e.getClickCount() == 1) && isEditable) { //if clicked and if the label is editable, //then set it to the editing state when the label is clicked on setEditingState(true); textField.setSelectionStart(0); } } public void mousePressed(MouseEvent e) { } public void mouseReleased(MouseEvent e) { } public void mouseEntered(MouseEvent e) { suggestEditable(true); } public void mouseExited(MouseEvent e) { suggestEditable(false); } public void mouseDragged(MouseEvent e) { suggestEditable(false); } public void mouseMoved(MouseEvent e) { suggestEditable(true); } } }
laurentschall/openblocks
src/main/java/edu/mit/blocks/codeblockutil/LabelWidget.java
Java
lgpl-3.0
24,554
/* * This class was automatically generated with * <a href="http://www.castor.org">Castor 1.3.1</a>, using an XML * Schema. * $Id: CreditCardCreditModRqTypeDescriptor.java,v 1.1.1.1 2010-05-04 22:06:01 ryan Exp $ */ package org.chocolate_milk.model.descriptors; //---------------------------------/ //- Imported classes and packages -/ //---------------------------------/ import org.chocolate_milk.model.CreditCardCreditModRqType; /** * Class CreditCardCreditModRqTypeDescriptor. * * @version $Revision: 1.1.1.1 $ $Date: 2010-05-04 22:06:01 $ */ public class CreditCardCreditModRqTypeDescriptor extends org.exolab.castor.xml.util.XMLClassDescriptorImpl { //--------------------------/ //- Class/Member Variables -/ //--------------------------/ /** * Field _elementDefinition. */ private boolean _elementDefinition; /** * Field _nsPrefix. */ private java.lang.String _nsPrefix; /** * Field _nsURI. */ private java.lang.String _nsURI; /** * Field _xmlName. */ private java.lang.String _xmlName; /** * Field _identity. */ private org.exolab.castor.xml.XMLFieldDescriptor _identity; //----------------/ //- Constructors -/ //----------------/ public CreditCardCreditModRqTypeDescriptor() { super(); _xmlName = "CreditCardCreditModRqType"; _elementDefinition = false; //-- set grouping compositor setCompositorAsSequence(); org.exolab.castor.xml.util.XMLFieldDescriptorImpl desc = null; org.exolab.castor.mapping.FieldHandler handler = null; org.exolab.castor.xml.FieldValidator fieldValidator = null; //-- initialize attribute descriptors //-- _requestID desc = new org.exolab.castor.xml.util.XMLFieldDescriptorImpl(java.lang.String.class, "_requestID", "requestID", org.exolab.castor.xml.NodeType.Attribute); desc.setImmutable(true); handler = new org.exolab.castor.xml.XMLFieldHandler() { @Override public java.lang.Object getValue( java.lang.Object object ) throws IllegalStateException { CreditCardCreditModRqType target = (CreditCardCreditModRqType) object; return target.getRequestID(); } @Override public void setValue( java.lang.Object object, java.lang.Object value) throws IllegalStateException, IllegalArgumentException { try { CreditCardCreditModRqType target = (CreditCardCreditModRqType) object; target.setRequestID( (java.lang.String) value); } catch (java.lang.Exception ex) { throw new IllegalStateException(ex.toString()); } } @Override @SuppressWarnings("unused") public java.lang.Object newInstance(java.lang.Object parent) { return null; } }; desc.setSchemaType("string"); desc.setHandler(handler); desc.setMultivalued(false); addFieldDescriptor(desc); //-- validation code for: _requestID fieldValidator = new org.exolab.castor.xml.FieldValidator(); { //-- local scope org.exolab.castor.xml.validators.StringValidator typeValidator; typeValidator = new org.exolab.castor.xml.validators.StringValidator(); fieldValidator.setValidator(typeValidator); typeValidator.setWhiteSpace("preserve"); } desc.setValidator(fieldValidator); //-- initialize element descriptors //-- _creditCardCreditMod desc = new org.exolab.castor.xml.util.XMLFieldDescriptorImpl(org.chocolate_milk.model.CreditCardCreditMod.class, "_creditCardCreditMod", "CreditCardCreditMod", org.exolab.castor.xml.NodeType.Element); handler = new org.exolab.castor.xml.XMLFieldHandler() { @Override public java.lang.Object getValue( java.lang.Object object ) throws IllegalStateException { CreditCardCreditModRqType target = (CreditCardCreditModRqType) object; return target.getCreditCardCreditMod(); } @Override public void setValue( java.lang.Object object, java.lang.Object value) throws IllegalStateException, IllegalArgumentException { try { CreditCardCreditModRqType target = (CreditCardCreditModRqType) object; target.setCreditCardCreditMod( (org.chocolate_milk.model.CreditCardCreditMod) value); } catch (java.lang.Exception ex) { throw new IllegalStateException(ex.toString()); } } @Override @SuppressWarnings("unused") public java.lang.Object newInstance(java.lang.Object parent) { return null; } }; desc.setSchemaType("org.chocolate_milk.model.CreditCardCreditMod"); desc.setHandler(handler); desc.setRequired(true); desc.setMultivalued(false); addFieldDescriptor(desc); addSequenceElement(desc); //-- validation code for: _creditCardCreditMod fieldValidator = new org.exolab.castor.xml.FieldValidator(); fieldValidator.setMinOccurs(1); { //-- local scope } desc.setValidator(fieldValidator); //-- _includeRetElementList desc = new org.exolab.castor.xml.util.XMLFieldDescriptorImpl(java.lang.String.class, "_includeRetElementList", "IncludeRetElement", org.exolab.castor.xml.NodeType.Element); desc.setImmutable(true); handler = new org.exolab.castor.xml.XMLFieldHandler() { @Override public java.lang.Object getValue( java.lang.Object object ) throws IllegalStateException { CreditCardCreditModRqType target = (CreditCardCreditModRqType) object; return target.getIncludeRetElement(); } @Override public void setValue( java.lang.Object object, java.lang.Object value) throws IllegalStateException, IllegalArgumentException { try { CreditCardCreditModRqType target = (CreditCardCreditModRqType) object; target.addIncludeRetElement( (java.lang.String) value); } catch (java.lang.Exception ex) { throw new IllegalStateException(ex.toString()); } } public void resetValue(Object object) throws IllegalStateException, IllegalArgumentException { try { CreditCardCreditModRqType target = (CreditCardCreditModRqType) object; target.removeAllIncludeRetElement(); } catch (java.lang.Exception ex) { throw new IllegalStateException(ex.toString()); } } @Override @SuppressWarnings("unused") public java.lang.Object newInstance(java.lang.Object parent) { return null; } }; desc.setSchemaType("list"); desc.setComponentType("string"); desc.setHandler(handler); desc.setMultivalued(true); addFieldDescriptor(desc); addSequenceElement(desc); //-- validation code for: _includeRetElementList fieldValidator = new org.exolab.castor.xml.FieldValidator(); fieldValidator.setMinOccurs(0); { //-- local scope org.exolab.castor.xml.validators.StringValidator typeValidator; typeValidator = new org.exolab.castor.xml.validators.StringValidator(); fieldValidator.setValidator(typeValidator); typeValidator.setWhiteSpace("preserve"); typeValidator.setMaxLength(50); } desc.setValidator(fieldValidator); } //-----------/ //- Methods -/ //-----------/ /** * Method getAccessMode. * * @return the access mode specified for this class. */ @Override() public org.exolab.castor.mapping.AccessMode getAccessMode( ) { return null; } /** * Method getIdentity. * * @return the identity field, null if this class has no * identity. */ @Override() public org.exolab.castor.mapping.FieldDescriptor getIdentity( ) { return _identity; } /** * Method getJavaClass. * * @return the Java class represented by this descriptor. */ @Override() public java.lang.Class getJavaClass( ) { return org.chocolate_milk.model.CreditCardCreditModRqType.class; } /** * Method getNameSpacePrefix. * * @return the namespace prefix to use when marshaling as XML. */ @Override() public java.lang.String getNameSpacePrefix( ) { return _nsPrefix; } /** * Method getNameSpaceURI. * * @return the namespace URI used when marshaling and * unmarshaling as XML. */ @Override() public java.lang.String getNameSpaceURI( ) { return _nsURI; } /** * Method getValidator. * * @return a specific validator for the class described by this * ClassDescriptor. */ @Override() public org.exolab.castor.xml.TypeValidator getValidator( ) { return this; } /** * Method getXMLName. * * @return the XML Name for the Class being described. */ @Override() public java.lang.String getXMLName( ) { return _xmlName; } /** * Method isElementDefinition. * * @return true if XML schema definition of this Class is that * of a global * element or element with anonymous type definition. */ public boolean isElementDefinition( ) { return _elementDefinition; } }
galleon1/chocolate-milk
src/org/chocolate_milk/model/descriptors/CreditCardCreditModRqTypeDescriptor.java
Java
lgpl-3.0
10,197
/* * SonarQube, open source software quality management tool. * Copyright (C) 2008-2014 SonarSource * mailto:contact AT sonarsource DOT com * * SonarQube is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * SonarQube is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.api.technicaldebt.server.internal; import org.junit.Test; import org.sonar.api.rule.RuleKey; import org.sonar.api.utils.WorkUnit; import org.sonar.api.utils.internal.WorkDuration; import static org.fest.assertions.Assertions.assertThat; public class DefaultCharacteristicTest { @Test public void test_setters_and_getters_for_characteristic() throws Exception { DefaultCharacteristic characteristic = new DefaultCharacteristic() .setId(1) .setKey("NETWORK_USE") .setName("Network use") .setOrder(5) .setParentId(2) .setRootId(2); assertThat(characteristic.id()).isEqualTo(1); assertThat(characteristic.key()).isEqualTo("NETWORK_USE"); assertThat(characteristic.name()).isEqualTo("Network use"); assertThat(characteristic.order()).isEqualTo(5); assertThat(characteristic.ruleKey()).isNull(); assertThat(characteristic.function()).isNull(); assertThat(characteristic.factorValue()).isNull(); assertThat(characteristic.factorUnit()).isNull(); assertThat(characteristic.offsetValue()).isNull(); assertThat(characteristic.offsetUnit()).isNull(); assertThat(characteristic.parentId()).isEqualTo(2); assertThat(characteristic.rootId()).isEqualTo(2); } @Test public void test_setters_and_getters_for_requirement() throws Exception { DefaultCharacteristic requirement = new DefaultCharacteristic() .setId(1) .setRuleKey(RuleKey.of("repo", "rule")) .setFunction("linear_offset") .setFactorValue(2) .setFactorUnit(WorkDuration.UNIT.MINUTES) .setOffsetValue(1) .setOffsetUnit(WorkDuration.UNIT.HOURS) .setRootId(3) .setParentId(2); assertThat(requirement.id()).isEqualTo(1); assertThat(requirement.key()).isNull(); assertThat(requirement.name()).isNull(); assertThat(requirement.order()).isNull(); assertThat(requirement.ruleKey()).isEqualTo(RuleKey.of("repo", "rule")); assertThat(requirement.function()).isEqualTo("linear_offset"); assertThat(requirement.factorValue()).isEqualTo(2); assertThat(requirement.factorUnit()).isEqualTo(WorkDuration.UNIT.MINUTES); assertThat(requirement.offsetValue()).isEqualTo(1); assertThat(requirement.offsetUnit()).isEqualTo(WorkDuration.UNIT.HOURS); assertThat(requirement.parentId()).isEqualTo(2); assertThat(requirement.rootId()).isEqualTo(3); } @Test public void is_root() throws Exception { DefaultCharacteristic characteristic = new DefaultCharacteristic() .setId(1) .setKey("NETWORK_USE") .setName("Network use") .setOrder(5) .setParentId(null) .setRootId(null); assertThat(characteristic.isRoot()).isTrue(); } @Test public void is_requirement() throws Exception { DefaultCharacteristic requirement = new DefaultCharacteristic() .setId(1) .setRuleKey(RuleKey.of("repo", "rule")) .setFunction("linear_offset") .setFactorValue(2) .setFactorUnit(WorkDuration.UNIT.MINUTES) .setOffsetValue(1) .setOffsetUnit(WorkDuration.UNIT.HOURS) .setRootId(3) .setParentId(2); assertThat(requirement.isRequirement()).isTrue(); } @Test public void test_equals() throws Exception { assertThat(new DefaultCharacteristic().setKey("NETWORK_USE")).isEqualTo(new DefaultCharacteristic().setKey("NETWORK_USE")); assertThat(new DefaultCharacteristic().setKey("NETWORK_USE")).isNotEqualTo(new DefaultCharacteristic().setKey("MAINTABILITY")); assertThat(new DefaultCharacteristic().setRuleKey(RuleKey.of("repo", "rule"))).isEqualTo(new DefaultCharacteristic().setRuleKey(RuleKey.of("repo", "rule"))); assertThat(new DefaultCharacteristic().setRuleKey(RuleKey.of("repo", "rule"))).isNotEqualTo(new DefaultCharacteristic().setRuleKey(RuleKey.of("repo2", "rule2"))); } @Test public void test_hascode() throws Exception { assertThat(new DefaultCharacteristic().setKey("NETWORK_USE").hashCode()).isEqualTo(new DefaultCharacteristic().setKey("NETWORK_USE").hashCode()); assertThat(new DefaultCharacteristic().setKey("NETWORK_USE").hashCode()).isNotEqualTo(new DefaultCharacteristic().setKey("MAINTABILITY").hashCode()); assertThat(new DefaultCharacteristic().setRuleKey(RuleKey.of("repo", "rule")).hashCode()).isEqualTo(new DefaultCharacteristic().setRuleKey(RuleKey.of("repo", "rule")).hashCode()); assertThat(new DefaultCharacteristic().setRuleKey(RuleKey.of("repo", "rule")).hashCode()).isNotEqualTo(new DefaultCharacteristic().setRuleKey(RuleKey.of("repo2", "rule2")).hashCode()); } @Test public void test_deprecated_setters_and_getters_for_characteristic() throws Exception { DefaultCharacteristic requirement = new DefaultCharacteristic() .setId(1) .setRuleKey(RuleKey.of("repo", "rule")) .setFunction("linear_offset") .setFactor(WorkUnit.create(2d, WorkUnit.MINUTES)) .setOffset(WorkUnit.create(1d, WorkUnit.HOURS)); assertThat(requirement.factor()).isEqualTo(WorkUnit.create(2d, WorkUnit.MINUTES)); assertThat(requirement.offset()).isEqualTo(WorkUnit.create(1d, WorkUnit.HOURS)); assertThat(new DefaultCharacteristic() .setId(1) .setRuleKey(RuleKey.of("repo", "rule")) .setFunction("linear") .setFactor(WorkUnit.create(2d, WorkUnit.DAYS)) .factor()).isEqualTo(WorkUnit.create(2d, WorkUnit.DAYS)); } }
teryk/sonarqube
sonar-plugin-api/src/test/java/org/sonar/api/technicaldebt/server/internal/DefaultCharacteristicTest.java
Java
lgpl-3.0
6,276
/* * Copyright (c) 2005–2012 Goethe Center for Scientific Computing - Simulation and Modelling (G-CSC Frankfurt) * Copyright (c) 2012-2015 Goethe Center for Scientific Computing - Computational Neuroscience (G-CSC Frankfurt) * * This file is part of NeuGen. * * NeuGen is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License version 3 * as published by the Free Software Foundation. * * see: http://opensource.org/licenses/LGPL-3.0 * file://path/to/NeuGen/LICENSE * * NeuGen is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * This version of NeuGen includes copyright notice and attribution requirements. * According to the LGPL this information must be displayed even if you modify * the source code of NeuGen. The copyright statement/attribution may not be removed. * * Attribution Requirements: * * If you create derived work you must do the following regarding copyright * notice and author attribution. * * Add an additional notice, stating that you modified NeuGen. In addition * you must cite the publications listed below. A suitable notice might read * "NeuGen source code modified by YourName 2012". * * Note, that these requirements are in full accordance with the LGPL v3 * (see 7. Additional Terms, b). * * Publications: * * S. Wolf, S. Grein, G. Queisser. NeuGen 2.0 - * Employing NeuGen 2.0 to automatically generate realistic * morphologies of hippocapal neurons and neural networks in 3D. * Neuroinformatics, 2013, 11(2), pp. 137-148, doi: 10.1007/s12021-012-9170-1 * * * J. P. Eberhard, A. Wanner, G. Wittum. NeuGen - * A tool for the generation of realistic morphology * of cortical neurons and neural networks in 3D. * Neurocomputing, 70(1-3), pp. 327-343, doi: 10.1016/j.neucom.2006.01.028 * */ package org.neugen.gui; import org.jdesktop.application.Action; /** * @author Sergei Wolf */ public final class NGAboutBox extends javax.swing.JDialog { private static final long serialVersionUID = 1L; public NGAboutBox(java.awt.Frame parent) { super(parent); initComponents(); getRootPane().setDefaultButton(closeButton); } @Action public void closeAboutBox() { dispose(); } /** * This method is called from within the constructor to * initialize the form. * WARNING: Do NOT modify this code. The content of this method is * always regenerated by the Form Editor. */ // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents private void initComponents() { closeButton = new javax.swing.JButton(); javax.swing.JLabel appTitleLabel = new javax.swing.JLabel(); javax.swing.JLabel versionLabel = new javax.swing.JLabel(); javax.swing.JLabel appVersionLabel = new javax.swing.JLabel(); javax.swing.JLabel vendorLabel = new javax.swing.JLabel(); javax.swing.JLabel appVendorLabel = new javax.swing.JLabel(); javax.swing.JLabel homepageLabel = new javax.swing.JLabel(); javax.swing.JLabel appHomepageLabel = new javax.swing.JLabel(); javax.swing.JLabel appDescLabel = new javax.swing.JLabel(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); org.jdesktop.application.ResourceMap resourceMap = org.jdesktop.application.Application.getInstance(org.neugen.gui.NeuGenApp.class).getContext().getResourceMap(NGAboutBox.class); setTitle(resourceMap.getString("title")); // NOI18N setModal(true); setName("aboutBox"); // NOI18N setResizable(false); javax.swing.ActionMap actionMap = org.jdesktop.application.Application.getInstance(org.neugen.gui.NeuGenApp.class).getContext().getActionMap(NGAboutBox.class, this); closeButton.setAction(actionMap.get("closeAboutBox")); // NOI18N closeButton.setName("closeButton"); // NOI18N appTitleLabel.setFont(appTitleLabel.getFont().deriveFont(appTitleLabel.getFont().getStyle() | java.awt.Font.BOLD, appTitleLabel.getFont().getSize()+4)); appTitleLabel.setText(resourceMap.getString("Application.title")); // NOI18N appTitleLabel.setName("appTitleLabel"); // NOI18N versionLabel.setFont(versionLabel.getFont().deriveFont(versionLabel.getFont().getStyle() | java.awt.Font.BOLD)); versionLabel.setText(resourceMap.getString("versionLabel.text")); // NOI18N versionLabel.setName("versionLabel"); // NOI18N appVersionLabel.setText(resourceMap.getString("Application.version")); // NOI18N appVersionLabel.setName("appVersionLabel"); // NOI18N vendorLabel.setFont(vendorLabel.getFont().deriveFont(vendorLabel.getFont().getStyle() | java.awt.Font.BOLD)); vendorLabel.setText(resourceMap.getString("vendorLabel.text")); // NOI18N vendorLabel.setName("vendorLabel"); // NOI18N appVendorLabel.setText(resourceMap.getString("Application.vendor")); // NOI18N appVendorLabel.setName("appVendorLabel"); // NOI18N homepageLabel.setFont(homepageLabel.getFont().deriveFont(homepageLabel.getFont().getStyle() | java.awt.Font.BOLD)); homepageLabel.setText(resourceMap.getString("homepageLabel.text")); // NOI18N homepageLabel.setName("homepageLabel"); // NOI18N appHomepageLabel.setText(resourceMap.getString("Application.homepage")); // NOI18N appHomepageLabel.setName("appHomepageLabel"); // NOI18N appDescLabel.setText(resourceMap.getString("appDescLabel.text")); // NOI18N appDescLabel.setName("appDescLabel"); // NOI18N org.jdesktop.layout.GroupLayout layout = new org.jdesktop.layout.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(layout.createSequentialGroup() .addContainerGap() .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(vendorLabel) .add(appTitleLabel) .add(appDescLabel, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, 269, Short.MAX_VALUE) .add(layout.createSequentialGroup() .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(versionLabel) .add(homepageLabel)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(appVendorLabel) .add(appVersionLabel) .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING) .add(closeButton) .add(appHomepageLabel))))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(org.jdesktop.layout.GroupLayout.TRAILING, layout.createSequentialGroup() .addContainerGap() .add(appTitleLabel) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(appDescLabel, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED) .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.BASELINE) .add(versionLabel) .add(appVersionLabel)) .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED) .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.TRAILING) .add(layout.createSequentialGroup() .add(appVendorLabel) .addPreferredGap(org.jdesktop.layout.LayoutStyle.UNRELATED) .add(appHomepageLabel)) .add(homepageLabel)) .add(layout.createParallelGroup(org.jdesktop.layout.GroupLayout.LEADING) .add(layout.createSequentialGroup() .addPreferredGap(org.jdesktop.layout.LayoutStyle.RELATED, org.jdesktop.layout.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE) .add(vendorLabel) .add(49, 49, 49)) .add(layout.createSequentialGroup() .add(18, 18, 18) .add(closeButton, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE, 23, org.jdesktop.layout.GroupLayout.PREFERRED_SIZE) .addContainerGap()))) ); pack(); }// </editor-fold>//GEN-END:initComponents // Variables declaration - do not modify//GEN-BEGIN:variables private javax.swing.JButton closeButton; // End of variables declaration//GEN-END:variables }
NeuroBox3D/NeuGen
NeuGen/src/org/neugen/gui/NGAboutBox.java
Java
lgpl-3.0
9,348
// // This file is auto-generated. Please don't modify it! // package org.opencv.video; import java.util.List; import org.opencv.core.Mat; import org.opencv.core.MatOfByte; import org.opencv.core.MatOfFloat; import org.opencv.core.MatOfPoint2f; import org.opencv.core.Rect; import org.opencv.core.RotatedRect; import org.opencv.core.Size; import org.opencv.core.TermCriteria; import org.opencv.utils.Converters; public class Video { public static final int OPTFLOW_USE_INITIAL_FLOW = 4, OPTFLOW_LK_GET_MIN_EIGENVALS = 8, OPTFLOW_FARNEBACK_GAUSSIAN = 256, MOTION_TRANSLATION = 0, MOTION_EUCLIDEAN = 1, MOTION_AFFINE = 2, MOTION_HOMOGRAPHY = 3; private static final int CV_LKFLOW_INITIAL_GUESSES = 4, CV_LKFLOW_GET_MIN_EIGENVALS = 8; // // C++: Mat estimateRigidTransform(Mat src, Mat dst, bool fullAffine) // //javadoc: estimateRigidTransform(src, dst, fullAffine) public static Mat estimateRigidTransform(Mat src, Mat dst, boolean fullAffine) { Mat retVal = new Mat(estimateRigidTransform_0(src.nativeObj, dst.nativeObj, fullAffine)); return retVal; } // // C++: Ptr_BackgroundSubtractorKNN createBackgroundSubtractorKNN(int history = 500, double dist2Threshold = 400.0, bool detectShadows = true) // //javadoc: createBackgroundSubtractorKNN(history, dist2Threshold, detectShadows) public static BackgroundSubtractorKNN createBackgroundSubtractorKNN(int history, double dist2Threshold, boolean detectShadows) { BackgroundSubtractorKNN retVal = new BackgroundSubtractorKNN(createBackgroundSubtractorKNN_0(history, dist2Threshold, detectShadows)); return retVal; } //javadoc: createBackgroundSubtractorKNN() public static BackgroundSubtractorKNN createBackgroundSubtractorKNN() { BackgroundSubtractorKNN retVal = new BackgroundSubtractorKNN(createBackgroundSubtractorKNN_1()); return retVal; } // // C++: Ptr_BackgroundSubtractorMOG2 createBackgroundSubtractorMOG2(int history = 500, double varThreshold = 16, bool detectShadows = true) // //javadoc: createBackgroundSubtractorMOG2(history, varThreshold, detectShadows) public static BackgroundSubtractorMOG2 createBackgroundSubtractorMOG2(int history, double varThreshold, boolean detectShadows) { BackgroundSubtractorMOG2 retVal = new BackgroundSubtractorMOG2(createBackgroundSubtractorMOG2_0(history, varThreshold, detectShadows)); return retVal; } //javadoc: createBackgroundSubtractorMOG2() public static BackgroundSubtractorMOG2 createBackgroundSubtractorMOG2() { BackgroundSubtractorMOG2 retVal = new BackgroundSubtractorMOG2(createBackgroundSubtractorMOG2_1()); return retVal; } // // C++: Ptr_DualTVL1OpticalFlow createOptFlow_DualTVL1() // //javadoc: createOptFlow_DualTVL1() public static DualTVL1OpticalFlow createOptFlow_DualTVL1() { DualTVL1OpticalFlow retVal = new DualTVL1OpticalFlow(createOptFlow_DualTVL1_0()); return retVal; } // // C++: RotatedRect CamShift(Mat probImage, Rect& window, TermCriteria criteria) // //javadoc: CamShift(probImage, window, criteria) public static RotatedRect CamShift(Mat probImage, Rect window, TermCriteria criteria) { double[] window_out = new double[4]; RotatedRect retVal = new RotatedRect(CamShift_0(probImage.nativeObj, window.x, window.y, window.width, window.height, window_out, criteria.type, criteria.maxCount, criteria.epsilon)); if (window != null) { window.x = (int) window_out[0]; window.y = (int) window_out[1]; window.width = (int) window_out[2]; window.height = (int) window_out[3]; } return retVal; } // // C++: double findTransformECC(Mat templateImage, Mat inputImage, Mat& warpMatrix, int motionType = MOTION_AFFINE, TermCriteria criteria = TermCriteria // (TermCriteria::COUNT+TermCriteria::EPS, 50, 0.001), Mat inputMask = Mat()) // //javadoc: findTransformECC(templateImage, inputImage, warpMatrix, motionType, criteria, inputMask) public static double findTransformECC(Mat templateImage, Mat inputImage, Mat warpMatrix, int motionType, TermCriteria criteria, Mat inputMask) { double retVal = findTransformECC_0(templateImage.nativeObj, inputImage.nativeObj, warpMatrix.nativeObj, motionType, criteria.type, criteria.maxCount, criteria.epsilon, inputMask.nativeObj); return retVal; } //javadoc: findTransformECC(templateImage, inputImage, warpMatrix, motionType) public static double findTransformECC(Mat templateImage, Mat inputImage, Mat warpMatrix, int motionType) { double retVal = findTransformECC_1(templateImage.nativeObj, inputImage.nativeObj, warpMatrix.nativeObj, motionType); return retVal; } //javadoc: findTransformECC(templateImage, inputImage, warpMatrix) public static double findTransformECC(Mat templateImage, Mat inputImage, Mat warpMatrix) { double retVal = findTransformECC_2(templateImage.nativeObj, inputImage.nativeObj, warpMatrix.nativeObj); return retVal; } // // C++: int buildOpticalFlowPyramid(Mat img, vector_Mat& pyramid, Size winSize, int maxLevel, bool withDerivatives = true, int pyrBorder = BORDER_REFLECT_101, int // derivBorder = BORDER_CONSTANT, bool tryReuseInputImage = true) // //javadoc: buildOpticalFlowPyramid(img, pyramid, winSize, maxLevel, withDerivatives, pyrBorder, derivBorder, tryReuseInputImage) public static int buildOpticalFlowPyramid(Mat img, List<Mat> pyramid, Size winSize, int maxLevel, boolean withDerivatives, int pyrBorder, int derivBorder, boolean tryReuseInputImage) { Mat pyramid_mat = new Mat(); int retVal = buildOpticalFlowPyramid_0(img.nativeObj, pyramid_mat.nativeObj, winSize.width, winSize.height, maxLevel, withDerivatives, pyrBorder, derivBorder, tryReuseInputImage); Converters.Mat_to_vector_Mat(pyramid_mat, pyramid); pyramid_mat.release(); return retVal; } //javadoc: buildOpticalFlowPyramid(img, pyramid, winSize, maxLevel) public static int buildOpticalFlowPyramid(Mat img, List<Mat> pyramid, Size winSize, int maxLevel) { Mat pyramid_mat = new Mat(); int retVal = buildOpticalFlowPyramid_1(img.nativeObj, pyramid_mat.nativeObj, winSize.width, winSize.height, maxLevel); Converters.Mat_to_vector_Mat(pyramid_mat, pyramid); pyramid_mat.release(); return retVal; } // // C++: int meanShift(Mat probImage, Rect& window, TermCriteria criteria) // //javadoc: meanShift(probImage, window, criteria) public static int meanShift(Mat probImage, Rect window, TermCriteria criteria) { double[] window_out = new double[4]; int retVal = meanShift_0(probImage.nativeObj, window.x, window.y, window.width, window.height, window_out, criteria.type, criteria.maxCount, criteria.epsilon); if (window != null) { window.x = (int) window_out[0]; window.y = (int) window_out[1]; window.width = (int) window_out[2]; window.height = (int) window_out[3]; } return retVal; } // // C++: void calcOpticalFlowFarneback(Mat prev, Mat next, Mat& flow, double pyr_scale, int levels, int winsize, int iterations, int poly_n, double poly_sigma, int flags) // //javadoc: calcOpticalFlowFarneback(prev, next, flow, pyr_scale, levels, winsize, iterations, poly_n, poly_sigma, flags) public static void calcOpticalFlowFarneback(Mat prev, Mat next, Mat flow, double pyr_scale, int levels, int winsize, int iterations, int poly_n, double poly_sigma, int flags) { calcOpticalFlowFarneback_0(prev.nativeObj, next.nativeObj, flow.nativeObj, pyr_scale, levels, winsize, iterations, poly_n, poly_sigma, flags); return; } // // C++: void calcOpticalFlowPyrLK(Mat prevImg, Mat nextImg, vector_Point2f prevPts, vector_Point2f& nextPts, vector_uchar& status, vector_float& err, Size winSize = Size // (21,21), int maxLevel = 3, TermCriteria criteria = TermCriteria(TermCriteria::COUNT+TermCriteria::EPS, 30, 0.01), int flags = 0, double minEigThreshold = 1e-4) // //javadoc: calcOpticalFlowPyrLK(prevImg, nextImg, prevPts, nextPts, status, err, winSize, maxLevel, criteria, flags, minEigThreshold) public static void calcOpticalFlowPyrLK(Mat prevImg, Mat nextImg, MatOfPoint2f prevPts, MatOfPoint2f nextPts, MatOfByte status, MatOfFloat err, Size winSize, int maxLevel, TermCriteria criteria, int flags, double minEigThreshold) { Mat prevPts_mat = prevPts; Mat nextPts_mat = nextPts; Mat status_mat = status; Mat err_mat = err; calcOpticalFlowPyrLK_0(prevImg.nativeObj, nextImg.nativeObj, prevPts_mat.nativeObj, nextPts_mat.nativeObj, status_mat.nativeObj, err_mat.nativeObj, winSize.width, winSize.height, maxLevel, criteria.type, criteria.maxCount, criteria.epsilon, flags, minEigThreshold); return; } //javadoc: calcOpticalFlowPyrLK(prevImg, nextImg, prevPts, nextPts, status, err, winSize, maxLevel) public static void calcOpticalFlowPyrLK(Mat prevImg, Mat nextImg, MatOfPoint2f prevPts, MatOfPoint2f nextPts, MatOfByte status, MatOfFloat err, Size winSize, int maxLevel) { Mat prevPts_mat = prevPts; Mat nextPts_mat = nextPts; Mat status_mat = status; Mat err_mat = err; calcOpticalFlowPyrLK_1(prevImg.nativeObj, nextImg.nativeObj, prevPts_mat.nativeObj, nextPts_mat.nativeObj, status_mat.nativeObj, err_mat.nativeObj, winSize.width, winSize.height, maxLevel); return; } //javadoc: calcOpticalFlowPyrLK(prevImg, nextImg, prevPts, nextPts, status, err) public static void calcOpticalFlowPyrLK(Mat prevImg, Mat nextImg, MatOfPoint2f prevPts, MatOfPoint2f nextPts, MatOfByte status, MatOfFloat err) { Mat prevPts_mat = prevPts; Mat nextPts_mat = nextPts; Mat status_mat = status; Mat err_mat = err; calcOpticalFlowPyrLK_2(prevImg.nativeObj, nextImg.nativeObj, prevPts_mat.nativeObj, nextPts_mat.nativeObj, status_mat.nativeObj, err_mat.nativeObj); return; } // C++: Mat estimateRigidTransform(Mat src, Mat dst, bool fullAffine) private static native long estimateRigidTransform_0(long src_nativeObj, long dst_nativeObj, boolean fullAffine); // C++: Ptr_BackgroundSubtractorKNN createBackgroundSubtractorKNN(int history = 500, double dist2Threshold = 400.0, bool detectShadows = true) private static native long createBackgroundSubtractorKNN_0(int history, double dist2Threshold, boolean detectShadows); private static native long createBackgroundSubtractorKNN_1(); // C++: Ptr_BackgroundSubtractorMOG2 createBackgroundSubtractorMOG2(int history = 500, double varThreshold = 16, bool detectShadows = true) private static native long createBackgroundSubtractorMOG2_0(int history, double varThreshold, boolean detectShadows); private static native long createBackgroundSubtractorMOG2_1(); // C++: Ptr_DualTVL1OpticalFlow createOptFlow_DualTVL1() private static native long createOptFlow_DualTVL1_0(); // C++: RotatedRect CamShift(Mat probImage, Rect& window, TermCriteria criteria) private static native double[] CamShift_0(long probImage_nativeObj, int window_x, int window_y, int window_width, int window_height, double[] window_out, int criteria_type, int criteria_maxCount, double criteria_epsilon); // C++: double findTransformECC(Mat templateImage, Mat inputImage, Mat& warpMatrix, int motionType = MOTION_AFFINE, TermCriteria criteria = TermCriteria // (TermCriteria::COUNT+TermCriteria::EPS, 50, 0.001), Mat inputMask = Mat()) private static native double findTransformECC_0(long templateImage_nativeObj, long inputImage_nativeObj, long warpMatrix_nativeObj, int motionType, int criteria_type, int criteria_maxCount, double criteria_epsilon, long inputMask_nativeObj); private static native double findTransformECC_1(long templateImage_nativeObj, long inputImage_nativeObj, long warpMatrix_nativeObj, int motionType); private static native double findTransformECC_2(long templateImage_nativeObj, long inputImage_nativeObj, long warpMatrix_nativeObj); // C++: int buildOpticalFlowPyramid(Mat img, vector_Mat& pyramid, Size winSize, int maxLevel, bool withDerivatives = true, int pyrBorder = BORDER_REFLECT_101, int // derivBorder = BORDER_CONSTANT, bool tryReuseInputImage = true) private static native int buildOpticalFlowPyramid_0(long img_nativeObj, long pyramid_mat_nativeObj, double winSize_width, double winSize_height, int maxLevel, boolean withDerivatives, int pyrBorder, int derivBorder, boolean tryReuseInputImage); private static native int buildOpticalFlowPyramid_1(long img_nativeObj, long pyramid_mat_nativeObj, double winSize_width, double winSize_height, int maxLevel); // C++: int meanShift(Mat probImage, Rect& window, TermCriteria criteria) private static native int meanShift_0(long probImage_nativeObj, int window_x, int window_y, int window_width, int window_height, double[] window_out, int criteria_type, int criteria_maxCount, double criteria_epsilon); // C++: void calcOpticalFlowFarneback(Mat prev, Mat next, Mat& flow, double pyr_scale, int levels, int winsize, int iterations, int poly_n, double poly_sigma, int flags) private static native void calcOpticalFlowFarneback_0(long prev_nativeObj, long next_nativeObj, long flow_nativeObj, double pyr_scale, int levels, int winsize, int iterations, int poly_n, double poly_sigma, int flags); // C++: void calcOpticalFlowPyrLK(Mat prevImg, Mat nextImg, vector_Point2f prevPts, vector_Point2f& nextPts, vector_uchar& status, vector_float& err, Size winSize = Size // (21,21), int maxLevel = 3, TermCriteria criteria = TermCriteria(TermCriteria::COUNT+TermCriteria::EPS, 30, 0.01), int flags = 0, double minEigThreshold = 1e-4) private static native void calcOpticalFlowPyrLK_0(long prevImg_nativeObj, long nextImg_nativeObj, long prevPts_mat_nativeObj, long nextPts_mat_nativeObj, long status_mat_nativeObj, long err_mat_nativeObj, double winSize_width, double winSize_height, int maxLevel, int criteria_type, int criteria_maxCount, double criteria_epsilon, int flags, double minEigThreshold); private static native void calcOpticalFlowPyrLK_1(long prevImg_nativeObj, long nextImg_nativeObj, long prevPts_mat_nativeObj, long nextPts_mat_nativeObj, long status_mat_nativeObj, long err_mat_nativeObj, double winSize_width, double winSize_height, int maxLevel); private static native void calcOpticalFlowPyrLK_2(long prevImg_nativeObj, long nextImg_nativeObj, long prevPts_mat_nativeObj, long nextPts_mat_nativeObj, long status_mat_nativeObj, long err_mat_nativeObj); }
openstreetview/android
sensorlib/src/main/java/org/opencv/video/Video.java
Java
lgpl-3.0
15,311
/* * HA-JDBC: High-Availability JDBC * Copyright (C) 2013 Paul Ferraro * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package net.sf.hajdbc.sql.io; import java.io.OutputStream; import java.sql.SQLException; import java.util.Map; import net.sf.hajdbc.Database; import net.sf.hajdbc.invocation.Invoker; import net.sf.hajdbc.sql.ProxyFactory; /** * @author Paul Ferraro */ public class OutputStreamProxyFactory<Z, D extends Database<Z>, P> extends OutputProxyFactory<Z, D, P, OutputStream> { public OutputStreamProxyFactory(P parentProxy, ProxyFactory<Z, D, P, SQLException> parent, Invoker<Z, D, P, OutputStream, SQLException> invoker, Map<D, OutputStream> outputs) { super(parentProxy, parent, invoker, outputs); } @Override public OutputStream createProxy() { return new OutputStreamProxy<>(this); } }
ha-jdbc/ha-jdbc
core/src/main/java/net/sf/hajdbc/sql/io/OutputStreamProxyFactory.java
Java
lgpl-3.0
1,449
/** * Copyright © 2002 Instituto Superior Técnico * * This file is part of FenixEdu Academic. * * FenixEdu Academic is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * FenixEdu Academic is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with FenixEdu Academic. If not, see <http://www.gnu.org/licenses/>. */ package org.fenixedu.academic.domain.accounting; import java.util.Collection; import java.util.Collections; import java.util.Comparator; import java.util.List; import java.util.Optional; import java.util.Set; import java.util.stream.Stream; import org.apache.commons.lang.StringUtils; import org.fenixedu.academic.domain.Person; import org.fenixedu.academic.domain.exceptions.DomainException; import org.fenixedu.academic.domain.exceptions.DomainExceptionWithLabelFormatter; import org.fenixedu.academic.domain.organizationalStructure.Party; import org.fenixedu.academic.util.LabelFormatter; import org.fenixedu.academic.util.Money; import org.fenixedu.bennu.core.domain.Bennu; import org.fenixedu.bennu.core.domain.User; import org.fenixedu.bennu.core.security.Authenticate; import org.fenixedu.bennu.core.signals.DomainObjectEvent; import org.fenixedu.bennu.core.signals.Signal; import org.joda.time.DateTime; import org.joda.time.LocalDate; import org.joda.time.YearMonthDay; /** * Two-ledged accounting transaction * * @author naat * */ public class AccountingTransaction extends AccountingTransaction_Base { public static final String SIGNAL_ANNUL = AccountingTransaction.class.getName() + ".annul"; public static Comparator<AccountingTransaction> COMPARATOR_BY_WHEN_REGISTERED = (leftAccountingTransaction, rightAccountingTransaction) -> { int comparationResult = leftAccountingTransaction.getWhenRegistered().compareTo(rightAccountingTransaction.getWhenRegistered()); return (comparationResult == 0) ? leftAccountingTransaction.getExternalId().compareTo( rightAccountingTransaction.getExternalId()) : comparationResult; }; protected AccountingTransaction() { super(); super.setRootDomainObject(Bennu.getInstance()); } public AccountingTransaction(User responsibleUser, Event event, Entry debit, Entry credit, AccountingTransactionDetail transactionDetail) { this(); init(responsibleUser, event, debit, credit, transactionDetail); } private AccountingTransaction(User responsibleUser, Entry debit, Entry credit, AccountingTransactionDetail transactionDetail, AccountingTransaction transactionToAdjust) { this(); init(responsibleUser, transactionToAdjust.getEvent(), debit, credit, transactionDetail, transactionToAdjust); } protected void init(User responsibleUser, Event event, Entry debit, Entry credit, AccountingTransactionDetail transactionDetail) { init(responsibleUser, event, debit, credit, transactionDetail, null); } protected void init(User responsibleUser, Event event, Entry debit, Entry credit, AccountingTransactionDetail transactionDetail, AccountingTransaction transactionToAdjust) { checkParameters(event, debit, credit); // check for operations after registered date List<String> operationsAfter = event.getOperationsAfter(transactionDetail.getWhenProcessed()); if (!operationsAfter.isEmpty()) { throw new DomainException("error.accounting.AccountingTransaction.cannot.create.transaction", String.join(",", operationsAfter)); } super.setEvent(event); super.setResponsibleUser(responsibleUser); super.addEntries(debit); super.addEntries(credit); super.setAdjustedTransaction(transactionToAdjust); super.setTransactionDetail(transactionDetail); } private void checkParameters(Event event, Entry debit, Entry credit) { if (event == null) { throw new DomainException("error.accounting.accountingTransaction.event.cannot.be.null"); } if (debit == null) { throw new DomainException("error.accounting.accountingTransaction.debit.cannot.be.null"); } if (credit == null) { throw new DomainException("error.accounting.accountingTransaction.credit.cannot.be.null"); } } @Override public void addEntries(Entry entries) { throw new DomainException("error.accounting.accountingTransaction.cannot.add.entries"); } @Override public Set<Entry> getEntriesSet() { return Collections.unmodifiableSet(super.getEntriesSet()); } @Override public void removeEntries(Entry entries) { throw new DomainException("error.accounting.accountingTransaction.cannot.remove.entries"); } @Override public void setEvent(Event event) { super.setEvent(event); } @Override public void setResponsibleUser(User responsibleUser) { throw new DomainException("error.accounting.accountingTransaction.cannot.modify.responsibleUser"); } @Override public void setAdjustedTransaction(AccountingTransaction adjustedTransaction) { throw new DomainException("error.accounting.accountingTransaction.cannot.modify.adjustedTransaction"); } @Override public void setTransactionDetail(AccountingTransactionDetail transactionDetail) { throw new DomainException("error.accounting.AccountingTransaction.cannot.modify.transactionDetail"); } @Override public void addAdjustmentTransactions(AccountingTransaction accountingTransaction) { throw new DomainException( "error.org.fenixedu.academic.domain.accounting.AccountingTransaction.cannot.add.accountingTransaction"); } @Override public Set<AccountingTransaction> getAdjustmentTransactionsSet() { return Collections.unmodifiableSet(super.getAdjustmentTransactionsSet()); } public Stream<AccountingTransaction> getAdjustmentTransactionStream() { return super.getAdjustmentTransactionsSet().stream(); } @Override public void removeAdjustmentTransactions(AccountingTransaction adjustmentTransactions) { throw new DomainException( "error.org.fenixedu.academic.domain.accounting.AccountingTransaction.cannot.remove.accountingTransaction"); } public LabelFormatter getDescriptionForEntryType(EntryType entryType) { return getEvent().getDescriptionForEntryType(entryType); } public Account getFromAccount() { return getEntry(false).getAccount(); } public Account getToAccount() { return getEntry(true).getAccount(); } public Entry getToAccountEntry() { return getEntry(true); } public Entry getFromAccountEntry() { return getEntry(false); } private Entry getEntry(boolean positive) { for (final Entry entry : super.getEntriesSet()) { if (entry.isPositiveAmount() == positive) { return entry; } } throw new DomainException("error.accounting.accountingTransaction.transaction.data.is.corrupted"); } public AccountingTransaction reimburse(User responsibleUser, PaymentMethod paymentMethod,String paymentReference, Money amountToReimburse) { return reimburse(responsibleUser, paymentMethod,paymentReference, amountToReimburse, null); } public AccountingTransaction reimburse(User responsibleUser, PaymentMethod paymentMethod, String paymentReference, Money amountToReimburse, String comments) { return reimburse(responsibleUser, paymentMethod, paymentReference, amountToReimburse, comments, true); } public AccountingTransaction reimburse(User responsibleUser, PaymentMethod paymentMethod, String paymentReference, Money amountToReimburse, DateTime reimburseDate, String comments) { return reimburse(responsibleUser, paymentMethod, paymentReference, amountToReimburse, comments, true, reimburseDate); } public AccountingTransaction reimburseWithoutRules(User responsibleUser, PaymentMethod paymentMethod, String paymentReference, Money amountToReimburse) { return reimburseWithoutRules(responsibleUser, paymentMethod, paymentReference, amountToReimburse, null); } public AccountingTransaction reimburseWithoutRules(User responsibleUser, PaymentMethod paymentMethod, String paymentReference, Money amountToReimburse, String comments) { return reimburse(responsibleUser, paymentMethod, paymentReference, amountToReimburse, comments, false); } public void annul(final User responsibleUser, final String reason) { if (StringUtils.isEmpty(reason)) { throw new DomainException( "error.org.fenixedu.academic.domain.accounting.AccountingTransaction.cannot.annul.without.reason"); } checkRulesToAnnul(); annulReceipts(); Signal.emit(SIGNAL_ANNUL, new DomainObjectEvent<AccountingTransaction>(this)); reimburseWithoutRules(responsibleUser, getTransactionDetail().getPaymentMethod(), getTransactionDetail() .getPaymentReference(), getAmountWithAdjustment(), reason); } private void checkRulesToAnnul() { final List<String> operationsAfter = getEvent().getOperationsAfter(getWhenProcessed()); if (!operationsAfter.isEmpty()) { throw new DomainException("error.accounting.AccountingTransaction.cannot.annul.operations.after", String.join(",", operationsAfter)); } } private void annulReceipts() { getToAccountEntry().getReceiptsSet().stream().filter(Receipt::isActive).forEach(r -> { Person responsible = Optional.ofNullable(Authenticate.getUser()).map(User::getPerson).orElse(null); r.annul(responsible); }); } private AccountingTransaction reimburse(User responsibleUser, PaymentMethod paymentMethod, String paymentReference, Money amountToReimburse, String comments, boolean checkRules) { return reimburse(responsibleUser, paymentMethod, paymentReference, amountToReimburse, comments, checkRules, new DateTime ()); } private AccountingTransaction reimburse(User responsibleUser, PaymentMethod paymentMethod, String paymentReference, Money amountToReimburse, String comments, boolean checkRules, DateTime reimburseDate) { if (checkRules && !canApplyReimbursement(amountToReimburse)) { throw new DomainException("error.accounting.AccountingTransaction.cannot.reimburse.events.that.may.open"); } if (!getToAccountEntry().canApplyReimbursement(amountToReimburse)) { throw new DomainExceptionWithLabelFormatter( "error.accounting.AccountingTransaction.amount.to.reimburse.exceeds.entry.amount", getToAccountEntry() .getDescription()); } final AccountingTransaction transaction = new AccountingTransaction(responsibleUser, new Entry(EntryType.ADJUSTMENT, amountToReimburse.negate(), getToAccount()), new Entry(EntryType.ADJUSTMENT, amountToReimburse, getFromAccount()), new AccountingTransactionDetail(reimburseDate, paymentMethod, paymentReference, comments), this); getEvent().recalculateState(new DateTime()); return transaction; } public DateTime getWhenRegistered() { return getTransactionDetail().getWhenRegistered(); } public DateTime getWhenProcessed() { return getTransactionDetail().getWhenProcessed(); } public String getComments() { return getTransactionDetail().getComments(); } public boolean isPayed(final int civilYear) { return getWhenRegistered().getYear() == civilYear; } public boolean isAdjustingTransaction() { return getAdjustedTransaction() != null; } public boolean hasBeenAdjusted() { return !super.getAdjustmentTransactionsSet().isEmpty(); } public Entry getEntryFor(final Account account) { for (final Entry accountingEntry : super.getEntriesSet()) { if (accountingEntry.getAccount() == account) { return accountingEntry; } } throw new DomainException( "error.accounting.accountingTransaction.transaction.data.is.corrupted.because.no.entry.belongs.to.account"); } private boolean canApplyReimbursement(final Money amount) { return getEvent().canApplyReimbursement(amount); } public boolean isSourceAccountFromParty(Party party) { return getFromAccount().getParty() == party; } @Override protected void checkForDeletionBlockers(Collection<String> blockers) { super.checkForDeletionBlockers(blockers); blockers.addAll(getEvent().getOperationsAfter(getWhenProcessed())); } public void delete() { DomainException.throwWhenDeleteBlocked(getDeletionBlockers()); super.setAdjustedTransaction(null); for (; !getAdjustmentTransactionsSet().isEmpty(); getAdjustmentTransactionsSet().iterator().next().delete()) { ; } if (getTransactionDetail() != null) { getTransactionDetail().delete(); } for (; !getEntriesSet().isEmpty(); getEntriesSet().iterator().next().delete()) { ; } super.setResponsibleUser(null); super.setEvent(null); setRootDomainObject(null); super.deleteDomainObject(); } public Money getAmountWithAdjustment() { return getToAccountEntry().getAmountWithAdjustment(); } public boolean isInsidePeriod(final YearMonthDay startDate, final YearMonthDay endDate) { return isInsidePeriod(startDate.toLocalDate(), endDate.toLocalDate()); } public boolean isInsidePeriod(final LocalDate startDate, final LocalDate endDate) { return !getWhenRegistered().toLocalDate().isBefore(startDate) && !getWhenRegistered().toLocalDate().isAfter(endDate); } public boolean isInstallment() { return false; } public PaymentMethod getPaymentMethod() { return getTransactionDetail().getPaymentMethod(); } public Money getOriginalAmount() { return getToAccountEntry().getOriginalAmount(); } }
sergiofbsilva/fenixedu-academic
src/main/java/org/fenixedu/academic/domain/accounting/AccountingTransaction.java
Java
lgpl-3.0
15,077
package net.amygdalum.testrecorder.profile; import static org.assertj.core.api.Assertions.assertThat; import java.io.ByteArrayOutputStream; import java.io.FileNotFoundException; import java.io.IOException; import java.net.URL; import java.nio.file.Path; import java.util.Enumeration; import java.util.stream.Stream; import org.junit.jupiter.api.Nested; import org.junit.jupiter.api.Test; import org.junit.jupiter.api.extension.ExtendWith; import net.amygdalum.testrecorder.util.ExtensibleClassLoader; import net.amygdalum.testrecorder.util.LogLevel; import net.amygdalum.testrecorder.util.LoggerExtension; public class ClassPathConfigurationLoaderTest { @Nested class testLoad { @Test void common() throws Exception { ExtensibleClassLoader classLoader = new ExtensibleClassLoader(ClassPathConfigurationLoaderTest.class.getClassLoader()); classLoader.defineResource("agentconfig/net.amygdalum.testrecorder.profile.ConfigNoArgumentsNonExclusive", "net.amygdalum.testrecorder.profile.DefaultConfigNoArguments".getBytes()); ClassPathConfigurationLoader loader = new ClassPathConfigurationLoader(classLoader); assertThat(loader.load(ConfigNoArgumentsNonExclusive.class).findFirst()).containsInstanceOf(DefaultConfigNoArguments.class); } @ExtendWith(LoggerExtension.class) @Test void withClassLoaderError(@LogLevel("error") ByteArrayOutputStream error) throws Exception { ExtensibleClassLoader classLoader = new ExtensibleClassLoader(ClassPathConfigurationLoaderTest.class.getClassLoader()) { @Override public Enumeration<URL> getResources(String name) throws IOException { throw new IOException(); } }; classLoader.defineResource("agentconfig/net.amygdalum.testrecorder.profile.ConfigNoArgumentsNonExclusive", "net.amygdalum.testrecorder.profile.DefaultConfigNoArguments".getBytes()); ClassPathConfigurationLoader loader = new ClassPathConfigurationLoader(classLoader); assertThat(loader.load(ConfigNoArgumentsNonExclusive.class).findFirst()).isNotPresent(); assertThat(error.toString()).contains("cannot load configuration from classpath"); } @ExtendWith(LoggerExtension.class) @Test void withFileNotFound(@LogLevel("debug") ByteArrayOutputStream debug) throws Exception { ExtensibleClassLoader classLoader = new ExtensibleClassLoader(ClassPathConfigurationLoaderTest.class.getClassLoader()); classLoader.defineResource("agentconfig/net.amygdalum.testrecorder.profile.ConfigNoArgumentsNonExclusive", "net.amygdalum.testrecorder.profile.DefaultConfigNoArguments".getBytes()); ClassPathConfigurationLoader loader = new ClassPathConfigurationLoader(classLoader) { @Override protected <T> Stream<T> configsFrom(Path path, Class<T> clazz, Object[] args) throws IOException { throw new FileNotFoundException(); } }; assertThat(loader.load(ConfigNoArgumentsNonExclusive.class).findFirst()).isNotPresent(); assertThat(debug.toString()).contains("did not find configuration file"); } @ExtendWith(LoggerExtension.class) @Test void withIOException(@LogLevel("error") ByteArrayOutputStream error) throws Exception { ExtensibleClassLoader classLoader = new ExtensibleClassLoader(ClassPathConfigurationLoaderTest.class.getClassLoader()); classLoader.defineResource("agentconfig/net.amygdalum.testrecorder.profile.ConfigNoArgumentsNonExclusive", "net.amygdalum.testrecorder.profile.DefaultConfigNoArguments".getBytes()); ClassPathConfigurationLoader loader = new ClassPathConfigurationLoader(classLoader) { @Override protected <T> Stream<T> configsFrom(Path path, Class<T> clazz, Object[] args) throws IOException { throw new IOException(); } }; assertThat(loader.load(ConfigNoArgumentsNonExclusive.class).findFirst()).isNotPresent(); assertThat(error.toString()).contains("cannot load configuration file"); } } }
almondtools/testrecorder
testrecorder-agent/src/test/java/net/amygdalum/testrecorder/profile/ClassPathConfigurationLoaderTest.java
Java
lgpl-3.0
3,862
/* ======================================================================== * PlantUML : a free UML diagram generator * ======================================================================== * * (C) Copyright 2009-2014, Arnaud Roques * * Project Info: http://plantuml.sourceforge.net * * This file is part of PlantUML. * * PlantUML is free software; you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * PlantUML distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, * USA. * * * Original Author: Arnaud Roques */ package net.sourceforge.plantuml.graphic; import java.awt.geom.Dimension2D; import net.sourceforge.plantuml.ugraphic.UChangeBackColor; import net.sourceforge.plantuml.ugraphic.UChangeColor; import net.sourceforge.plantuml.ugraphic.UGraphic; import net.sourceforge.plantuml.ugraphic.URectangle; import net.sourceforge.plantuml.ugraphic.UStroke; public class TextBlockGeneric implements TextBlock { private final TextBlock textBlock; private final HtmlColor background; private final HtmlColor border; public TextBlockGeneric(TextBlock textBlock, HtmlColor background, HtmlColor border) { this.textBlock = textBlock; this.border = border; this.background = background; } public Dimension2D calculateDimension(StringBounder stringBounder) { final Dimension2D dim = textBlock.calculateDimension(stringBounder); return dim; } public void drawU(UGraphic ug) { ug = ug.apply(new UChangeBackColor(background)); ug = ug.apply(new UChangeColor(border)); final Dimension2D dim = calculateDimension(ug.getStringBounder()); ug.apply(new UStroke(2, 2, 1)).draw(new URectangle(dim.getWidth(), dim.getHeight())); textBlock.drawU(ug); } }
mar9000/plantuml
src/net/sourceforge/plantuml/graphic/TextBlockGeneric.java
Java
lgpl-3.0
2,272
/* * SonarQube * Copyright (C) 2009-2022 SonarSource SA * mailto:info AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.authentication.ws; import org.junit.Test; import org.sonar.core.platform.ListContainer; import static org.assertj.core.api.Assertions.assertThat; public class AuthenticationWsModuleTest { @Test public void verify_count_of_added_components() { ListContainer container = new ListContainer(); new AuthenticationWsModule().configure(container); assertThat(container.getAddedObjects()).hasSize(4); } }
SonarSource/sonarqube
server/sonar-webserver-webapi/src/test/java/org/sonar/server/authentication/ws/AuthenticationWsModuleTest.java
Java
lgpl-3.0
1,286
/******************************************************************************* * Este arquivo é parte do Biblivre5. * * Biblivre5 é um software livre; você pode redistribuí-lo e/ou * modificá-lo dentro dos termos da Licença Pública Geral GNU como * publicada pela Fundação do Software Livre (FSF); na versão 3 da * Licença, ou (caso queira) qualquer versão posterior. * * Este programa é distribuído na esperança de que possa ser útil, * mas SEM NENHUMA GARANTIA; nem mesmo a garantia implícita de * MERCANTIBILIDADE OU ADEQUAÇÃO PARA UM FIM PARTICULAR. Veja a * Licença Pública Geral GNU para maiores detalhes. * * Você deve ter recebido uma cópia da Licença Pública Geral GNU junto * com este programa, Se não, veja em <http://www.gnu.org/licenses/>. * * @author Alberto Wagner <[email protected]> * @author Danniel Willian <[email protected]> ******************************************************************************/ package biblivre.core; import java.io.File; import java.util.LinkedList; import org.json.JSONArray; public class JavascriptCacheableList<T extends IFJson> extends LinkedList<T> implements IFCacheableJavascript { private static final long serialVersionUID = 1L; private String variable; private String prefix; private String suffix; private JavascriptCache cache; public JavascriptCacheableList(String variable, String prefix, String suffix) { this.variable = variable; this.prefix = prefix; this.suffix = suffix; } @Override public String getCacheFileNamePrefix() { return this.prefix; } @Override public String getCacheFileNameSuffix() { return this.suffix; } @Override public String toJavascriptString() { JSONArray array = new JSONArray(); for (T el : this) { array.put(el.toJSONObject()); } return this.variable + " = " + array.toString() + ";"; } @Override public File getCacheFile() { if (this.cache == null) { this.cache = new JavascriptCache(this); } return this.cache.getCacheFile(); } @Override public String getCacheFileName() { if (this.cache == null) { this.cache = new JavascriptCache(this); } return this.cache.getFileName(); } @Override public void invalidateCache() { this.cache = null; } }
Biblivre/Biblivre-5
src/java/biblivre/core/JavascriptCacheableList.java
Java
lgpl-3.0
2,296
package yaycrawler.admin; import org.springframework.boot.builder.SpringApplicationBuilder; import org.springframework.boot.context.web.SpringBootServletInitializer; public class ServletInitializer extends SpringBootServletInitializer { @Override protected SpringApplicationBuilder configure(SpringApplicationBuilder application) { return application.sources(Application.class); } }
liushuishang/YayCrawler
yaycrawler.admin/src/main/java/yaycrawler/admin/ServletInitializer.java
Java
lgpl-3.0
392
package br.com.vepo.datatransform.model; import org.springframework.beans.factory.annotation.Autowired; public abstract class Repository<T> { @Autowired protected MongoConnection mongoConnection; public <V> T find(Class<T> clazz, V key) { return mongoConnection.getMorphiaDataStore().get(clazz, key); } public void persist(T obj) { mongoConnection.getMorphiaDataStore().save(obj); } }
vepo/data-refine
src/main/java/br/com/vepo/datatransform/model/Repository.java
Java
lgpl-3.0
399
package org.com.json; /* Copyright (c) 2002 JSON.org Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. The Software shall be used for Good, not Evil. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ import java.util.Iterator; /** * This provides static methods to convert an XML text into a JSONObject, * and to covert a JSONObject into an XML text. * @author JSON.org * @version 2008-10-14 */ public class XML { /** The Character '&'. */ public static final Character AMP = new Character('&'); /** The Character '''. */ public static final Character APOS = new Character('\''); /** The Character '!'. */ public static final Character BANG = new Character('!'); /** The Character '='. */ public static final Character EQ = new Character('='); /** The Character '>'. */ public static final Character GT = new Character('>'); /** The Character '<'. */ public static final Character LT = new Character('<'); /** The Character '?'. */ public static final Character QUEST = new Character('?'); /** The Character '"'. */ public static final Character QUOT = new Character('"'); /** The Character '/'. */ public static final Character SLASH = new Character('/'); /** * Replace special characters with XML escapes: * <pre> * &amp; <small>(ampersand)</small> is replaced by &amp;amp; * &lt; <small>(less than)</small> is replaced by &amp;lt; * &gt; <small>(greater than)</small> is replaced by &amp;gt; * &quot; <small>(double quote)</small> is replaced by &amp;quot; * </pre> * @param string The string to be escaped. * @return The escaped string. */ public static String escape(String string) { StringBuffer sb = new StringBuffer(); for (int i = 0, len = string.length(); i < len; i++) { char c = string.charAt(i); switch (c) { case '&': sb.append("&amp;"); break; case '<': sb.append("&lt;"); break; case '>': sb.append("&gt;"); break; case '"': sb.append("&quot;"); break; default: sb.append(c); } } return sb.toString(); } /** * Throw an exception if the string contains whitespace. * Whitespace is not allowed in tagNames and attributes. * @param string * @throws JSONException */ public static void noSpace(String string) throws JSONException { int i, length = string.length(); if (length == 0) { throw new JSONException("Empty string."); } for (i = 0; i < length; i += 1) { if (Character.isWhitespace(string.charAt(i))) { throw new JSONException("'" + string + "' contains a space character."); } } } /** * Scan the content following the named tag, attaching it to the context. * @param x The XMLTokener containing the source string. * @param context The JSONObject that will include the new material. * @param name The tag name. * @return true if the close tag is processed. * @throws JSONException */ private static boolean parse(XMLTokener x, JSONObject context, String name) throws JSONException { char c; int i; String n; JSONObject o = null; String s; Object t; // Test for and skip past these forms: // <!-- ... --> // <! ... > // <![ ... ]]> // <? ... ?> // Report errors for these forms: // <> // <= // << t = x.nextToken(); // <! if (t == BANG) { c = x.next(); if (c == '-') { if (x.next() == '-') { x.skipPast("-->"); return false; } x.back(); } else if (c == '[') { t = x.nextToken(); if (t.equals("CDATA")) { if (x.next() == '[') { s = x.nextCDATA(); if (s.length() > 0) { context.accumulate("content", s); } return false; } } throw x.syntaxError("Expected 'CDATA['"); } i = 1; do { t = x.nextMeta(); if (t == null) { throw x.syntaxError("Missing '>' after '<!'."); } else if (t == LT) { i += 1; } else if (t == GT) { i -= 1; } } while (i > 0); return false; } else if (t == QUEST) { // <? x.skipPast("?>"); return false; } else if (t == SLASH) { // Close tag </ t = x.nextToken(); if (name == null) { throw x.syntaxError("Mismatched close tag" + t); } if (!t.equals(name)) { throw x.syntaxError("Mismatched " + name + " and " + t); } if (x.nextToken() != GT) { throw x.syntaxError("Misshaped close tag"); } return true; } else if (t instanceof Character) { throw x.syntaxError("Misshaped tag"); // Open tag < } else { n = (String)t; t = null; o = new JSONObject(); for (;;) { if (t == null) { t = x.nextToken(); } // attribute = value if (t instanceof String) { s = (String)t; t = x.nextToken(); if (t == EQ) { t = x.nextToken(); if (!(t instanceof String)) { throw x.syntaxError("Missing value"); } o.accumulate(s, JSONObject.stringToValue((String)t)); t = null; } else { o.accumulate(s, ""); } // Empty tag <.../> } else if (t == SLASH) { if (x.nextToken() != GT) { throw x.syntaxError("Misshaped tag"); } context.accumulate(n, o); return false; // Content, between <...> and </...> } else if (t == GT) { for (;;) { t = x.nextContent(); if (t == null) { if (n != null) { throw x.syntaxError("Unclosed tag " + n); } return false; } else if (t instanceof String) { s = (String)t; if (s.length() > 0) { o.accumulate("content", JSONObject.stringToValue(s)); } // Nested element } else if (t == LT) { if (parse(x, o, n)) { if (o.length() == 0) { context.accumulate(n, ""); } else if (o.length() == 1 && o.opt("content") != null) { context.accumulate(n, o.opt("content")); } else { context.accumulate(n, o); } return false; } } } } else { throw x.syntaxError("Misshaped tag"); } } } } /** * Convert a well-formed (but not necessarily valid) XML string into a * JSONObject. Some information may be lost in this transformation * because JSON is a data format and XML is a document format. XML uses * elements, attributes, and content text, while JSON uses unordered * collections of name/value pairs and arrays of values. JSON does not * does not like to distinguish between elements and attributes. * Sequences of similar elements are represented as JSONArrays. Content * text may be placed in a "content" member. Comments, prologs, DTDs, and * <code>&lt;[ [ ]]></code> are ignored. * @param string The source string. * @return A JSONObject containing the structured data from the XML string. * @throws JSONException */ public static JSONObject toJSONObject(String string) throws JSONException { JSONObject o = new JSONObject(); XMLTokener x = new XMLTokener(string); while (x.more() && x.skipPast("<")) { parse(x, o, null); } return o; } /** * Convert a JSONObject into a well-formed, element-normal XML string. * @param o A JSONObject. * @return A string. * @throws JSONException */ public static String toString(Object o) throws JSONException { return toString(o, null); } /** * Convert a JSONObject into a well-formed, element-normal XML string. * @param o A JSONObject. * @param tagName The optional name of the enclosing tag. * @return A string. * @throws JSONException */ public static String toString(Object o, String tagName) throws JSONException { StringBuffer b = new StringBuffer(); int i; JSONArray ja; JSONObject jo; String k; Iterator keys; int len; String s; Object v; if (o instanceof JSONObject) { // Emit <tagName> if (tagName != null) { b.append('<'); b.append(tagName); b.append('>'); } // Loop thru the keys. jo = (JSONObject)o; keys = jo.keys(); while (keys.hasNext()) { k = keys.next().toString(); v = jo.opt(k); if (v == null) { v = ""; } if (v instanceof String) { s = (String)v; } else { s = null; } // Emit content in body if (k.equals("content")) { if (v instanceof JSONArray) { ja = (JSONArray)v; len = ja.length(); for (i = 0; i < len; i += 1) { if (i > 0) { b.append('\n'); } b.append(escape(ja.get(i).toString())); } } else { b.append(escape(v.toString())); } // Emit an array of similar keys } else if (v instanceof JSONArray) { ja = (JSONArray)v; len = ja.length(); for (i = 0; i < len; i += 1) { v = ja.get(i); if (v instanceof JSONArray) { b.append('<'); b.append(k); b.append('>'); b.append(toString(v)); b.append("</"); b.append(k); b.append('>'); } else { b.append(toString(v, k)); } } } else if (v.equals("")) { b.append('<'); b.append(k); b.append("/>"); // Emit a new tag <k> } else { b.append(toString(v, k)); } } if (tagName != null) { // Emit the </tagname> close tag b.append("</"); b.append(tagName); b.append('>'); } return b.toString(); // XML does not have good support for arrays. If an array appears in a place // where XML is lacking, synthesize an <array> element. } else if (o instanceof JSONArray) { ja = (JSONArray)o; len = ja.length(); for (i = 0; i < len; ++i) { v = ja.opt(i); b.append(toString(v, (tagName == null) ? "array" : tagName)); } return b.toString(); } else { s = (o == null) ? "null" : escape(o.toString()); return (tagName == null) ? "\"" + s + "\"" : (s.length() == 0) ? "<" + tagName + "/>" : "<" + tagName + ">" + s + "</" + tagName + ">"; } } }
jongos/Question_Box_Desktop
Json/src/org/com/json/XML.java
Java
lgpl-3.0
14,112
package com.silicolife.textmining.processes.ie.ner.nerlexicalresources; import java.util.ArrayList; import java.util.Calendar; import java.util.Collection; import java.util.Date; import java.util.Iterator; import java.util.List; import java.util.Properties; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.TimeUnit; import com.fasterxml.jackson.annotation.JsonIgnore; import com.silicolife.textmining.core.datastructures.documents.AnnotatedDocumentImpl; import com.silicolife.textmining.core.datastructures.exceptions.process.InvalidConfigurationException; import com.silicolife.textmining.core.datastructures.init.InitConfiguration; import com.silicolife.textmining.core.datastructures.process.ProcessOriginImpl; import com.silicolife.textmining.core.datastructures.report.processes.NERProcessReportImpl; import com.silicolife.textmining.core.datastructures.utils.GenerateRandomId; import com.silicolife.textmining.core.datastructures.utils.Utils; import com.silicolife.textmining.core.datastructures.utils.conf.GlobalOptions; import com.silicolife.textmining.core.datastructures.utils.conf.OtherConfigurations; import com.silicolife.textmining.core.datastructures.utils.multithearding.IParallelJob; import com.silicolife.textmining.core.interfaces.core.dataaccess.exception.ANoteException; import com.silicolife.textmining.core.interfaces.core.document.IAnnotatedDocument; import com.silicolife.textmining.core.interfaces.core.document.IPublication; import com.silicolife.textmining.core.interfaces.core.document.corpus.ICorpus; import com.silicolife.textmining.core.interfaces.core.report.processes.INERProcessReport; import com.silicolife.textmining.core.interfaces.process.IProcessOrigin; import com.silicolife.textmining.core.interfaces.process.IE.IIEProcess; import com.silicolife.textmining.core.interfaces.process.IE.INERProcess; import com.silicolife.textmining.core.interfaces.process.IE.ner.INERConfiguration; import com.silicolife.textmining.processes.ie.ner.nerlexicalresources.configuration.INERLexicalResourcesConfiguration; import com.silicolife.textmining.processes.ie.ner.nerlexicalresources.configuration.INERLexicalResourcesPreProcessingModel; import com.silicolife.textmining.processes.ie.ner.nerlexicalresources.configuration.NERLexicalResourcesPreProssecingEnum; import com.silicolife.textmining.processes.ie.ner.nerlexicalresources.multithreading.NERParallelStep; import com.silicolife.textmining.processes.ie.ner.nerlexicalresources.preprocessingmodel.NERPreprocessingFactory; public class NERLexicalResources implements INERProcess{ public static String nerlexicalresourcesTagger = "NER Lexical Resources Tagger"; public static final IProcessOrigin nerlexicalresourcesOrigin= new ProcessOriginImpl(GenerateRandomId.generateID(),nerlexicalresourcesTagger); private boolean stop = false; private ExecutorService executor; public NERLexicalResources() { } public INERProcessReport executeCorpusNER(INERConfiguration configuration) throws ANoteException, InvalidConfigurationException { validateConfiguration(configuration); INERLexicalResourcesConfiguration lexicalResurcesConfiguration = (INERLexicalResourcesConfiguration) configuration; NERLexicalResourcesPreProssecingEnum preprocessing = lexicalResurcesConfiguration.getPreProcessingOption(); INERLexicalResourcesPreProcessingModel model = NERPreprocessingFactory.build(lexicalResurcesConfiguration,preprocessing); IIEProcess processToRun = getIEProcess(lexicalResurcesConfiguration,model); // creates the thread executor that in each thread executes the ner for a document executor = Executors.newFixedThreadPool(OtherConfigurations.getThreadsNumber()); InitConfiguration.getDataAccess().createIEProcess(processToRun); InitConfiguration.getDataAccess().registerCorpusProcess(configuration.getCorpus(), processToRun); NERProcessReportImpl report = new NERProcessReportImpl(nerlexicalresourcesTagger,processToRun); stop = false; if(!stop) { processingParallelNER(report,lexicalResurcesConfiguration,processToRun,model); } else { report.setFinishing(false); } return report; } private IIEProcess getIEProcess(INERLexicalResourcesConfiguration lexicalResurcesConfiguration,INERLexicalResourcesPreProcessingModel model) { String description = NERLexicalResources.nerlexicalresourcesTagger + " " +Utils.SimpleDataFormat.format(new Date()); Properties properties = model.getProperties(lexicalResurcesConfiguration); IIEProcess processToRun = lexicalResurcesConfiguration.getIEProcess(); processToRun.setName(description); processToRun.setProperties(properties); if(processToRun.getCorpus() == null) processToRun.setCorpus(lexicalResurcesConfiguration.getCorpus()); return processToRun; } private void processingParallelNER(NERProcessReportImpl report,INERLexicalResourcesConfiguration configuration,IIEProcess process,INERLexicalResourcesPreProcessingModel model) throws ANoteException { int size = process.getCorpus().getCorpusStatistics().getDocumentNumber(); long startTime = Calendar.getInstance().getTimeInMillis(); long actualTime,differTime; int i=0; Collection<IPublication> docs = process.getCorpus().getArticlesCorpus().getAllDocuments().values(); List<IParallelJob<Integer>> jobs = new ArrayList<>(); for(IPublication pub:docs) { if(!stop) { List<Long> classIdCaseSensative = new ArrayList<Long>(); IAnnotatedDocument annotDoc = new AnnotatedDocumentImpl(pub,process, process.getCorpus()); String text = annotDoc.getDocumentAnnotationText(); if(text==null) { // Logger logger = Logger.getLogger(Workbench.class.getName()); // logger.warn("The article whit id: "+pub.getId()+"not contains abstract "); System.err.println("The article whit id: "+pub.getId()+"not contains abstract "); } else { jobs.add(executeNER(process.getCorpus(), executor,classIdCaseSensative, annotDoc, text,configuration,model,process)); } report.incrementDocument(); } else { report.setFinishing(false); break; } } startTime = Calendar.getInstance().getTimeInMillis(); executor.shutdown(); // loop to give the progress bar of jobs while(!jobs.isEmpty() && !stop){ actualTime = Calendar.getInstance().getTimeInMillis(); differTime = actualTime - startTime; Iterator<IParallelJob<Integer>> itjobs = jobs.iterator(); while(itjobs.hasNext() && !stop){ IParallelJob<Integer> job = itjobs.next(); if(job.isFinished()){ report.incrementEntitiesAnnotated(job.getResultJob()); itjobs.remove(); } } if(differTime > 10000 * i) { int step = size-jobs.size(); memoryAndProgressAndTime(step, size, startTime); i++; } } //in case of stop, that will kill the running jobs if(stop){ for(IParallelJob<Integer> job : jobs) job.kill(); } try { executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS); } catch (InterruptedException e) { throw new ANoteException(e); } actualTime = Calendar.getInstance().getTimeInMillis(); report.setTime(actualTime-startTime); } @JsonIgnore protected void memoryAndProgress(int step, int total) { System.out.println((GlobalOptions.decimalformat.format((double) step / (double) total * 100)) + " %..."); // System.gc(); // System.out.println((Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / (1024 * 1024) + " MB "); } @JsonIgnore protected void memoryAndProgressAndTime(int step, int total, long startTime) { System.out.println((GlobalOptions.decimalformat.format((double) step / (double) total * 100)) + " %..."); // System.gc(); // System.out.println((Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()) / (1024 * 1024) + " MB "); } private IParallelJob<Integer> executeNER(ICorpus corpus,ExecutorService executor,List<Long> classIdCaseSensative,IAnnotatedDocument annotDoc,String text,INERLexicalResourcesConfiguration confguration,INERLexicalResourcesPreProcessingModel nerpreprocessingmodel,IIEProcess process) { IParallelJob<Integer> job = new NERParallelStep(nerpreprocessingmodel,annotDoc, process, corpus, text, classIdCaseSensative,confguration.getCaseSensitive(),confguration.isNormalized()); executor.submit(job); return job; } public void stop() { stop = true; //removes the jobs from executor and attempts to interrput the threads executor.shutdownNow(); } @Override public void validateConfiguration(INERConfiguration configuration)throws InvalidConfigurationException { if(configuration instanceof INERLexicalResourcesConfiguration) { INERLexicalResourcesConfiguration lexicalResurcesConfiguration = (INERLexicalResourcesConfiguration) configuration; if(lexicalResurcesConfiguration.getCorpus()==null) { throw new InvalidConfigurationException("Corpus can not be null"); } } else throw new InvalidConfigurationException("configuration must be INERLexicalResourcesConfiguration isntance"); } }
biotextmining/processes
src/main/java/com/silicolife/textmining/processes/ie/ner/nerlexicalresources/NERLexicalResources.java
Java
lgpl-3.0
9,063
package repack.org.bouncycastle.crypto.agreement; import repack.org.bouncycastle.crypto.BasicAgreement; import repack.org.bouncycastle.crypto.CipherParameters; import repack.org.bouncycastle.crypto.params.ECDomainParameters; import repack.org.bouncycastle.crypto.params.ECPrivateKeyParameters; import repack.org.bouncycastle.crypto.params.ECPublicKeyParameters; import repack.org.bouncycastle.crypto.params.MQVPrivateParameters; import repack.org.bouncycastle.crypto.params.MQVPublicParameters; import repack.org.bouncycastle.math.ec.ECAlgorithms; import repack.org.bouncycastle.math.ec.ECConstants; import repack.org.bouncycastle.math.ec.ECPoint; import java.math.BigInteger; public class ECMQVBasicAgreement implements BasicAgreement { MQVPrivateParameters privParams; public void init( CipherParameters key) { this.privParams = (MQVPrivateParameters) key; } public BigInteger calculateAgreement(CipherParameters pubKey) { MQVPublicParameters pubParams = (MQVPublicParameters) pubKey; ECPrivateKeyParameters staticPrivateKey = privParams.getStaticPrivateKey(); ECPoint agreement = calculateMqvAgreement(staticPrivateKey.getParameters(), staticPrivateKey, privParams.getEphemeralPrivateKey(), privParams.getEphemeralPublicKey(), pubParams.getStaticPublicKey(), pubParams.getEphemeralPublicKey()); return agreement.getX().toBigInteger(); } // The ECMQV Primitive as described in SEC-1, 3.4 private ECPoint calculateMqvAgreement( ECDomainParameters parameters, ECPrivateKeyParameters d1U, ECPrivateKeyParameters d2U, ECPublicKeyParameters Q2U, ECPublicKeyParameters Q1V, ECPublicKeyParameters Q2V) { BigInteger n = parameters.getN(); int e = (n.bitLength() + 1) / 2; BigInteger powE = ECConstants.ONE.shiftLeft(e); // The Q2U public key is optional ECPoint q; if(Q2U == null) { q = parameters.getG().multiply(d2U.getD()); } else { q = Q2U.getQ(); } BigInteger x = q.getX().toBigInteger(); BigInteger xBar = x.mod(powE); BigInteger Q2UBar = xBar.setBit(e); BigInteger s = d1U.getD().multiply(Q2UBar).mod(n).add(d2U.getD()).mod(n); BigInteger xPrime = Q2V.getQ().getX().toBigInteger(); BigInteger xPrimeBar = xPrime.mod(powE); BigInteger Q2VBar = xPrimeBar.setBit(e); BigInteger hs = parameters.getH().multiply(s).mod(n); // ECPoint p = Q1V.getQ().multiply(Q2VBar).add(Q2V.getQ()).multiply(hs); ECPoint p = ECAlgorithms.sumOfTwoMultiplies( Q1V.getQ(), Q2VBar.multiply(hs).mod(n), Q2V.getQ(), hs); if(p.isInfinity()) { throw new IllegalStateException("Infinity is not a valid agreement value for MQV"); } return p; } }
SafetyCulture/DroidText
app/src/main/java/bouncycastle/repack/org/bouncycastle/crypto/agreement/ECMQVBasicAgreement.java
Java
lgpl-3.0
2,651
/** * Copyright (C) 2015 Łukasz Tomczak <[email protected]>. * * This file is part of OpenInTerminal plugin. * * OpenInTerminal plugin is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * OpenInTerminal plugin is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with OpenInTerminal plugin. If not, see <http://www.gnu.org/licenses/>. */ package settings; /** * @author Łukasz Tomczak <[email protected]> */ public class OpenInTerminalSettingsState { private String terminalCommand; private String terminalCommandOptions; public OpenInTerminalSettingsState() { } public OpenInTerminalSettingsState(String terminalCommand, String terminalCommandOptions) { this.terminalCommand = terminalCommand; this.terminalCommandOptions = terminalCommandOptions; } public String getTerminalCommand() { return terminalCommand; } public void setTerminalCommand(String terminalCommand) { this.terminalCommand = terminalCommand; } public String getTerminalCommandOptions() { return terminalCommandOptions; } public void setTerminalCommandOptions(String terminalCommandOptions) { this.terminalCommandOptions = terminalCommandOptions; } @Override public boolean equals(Object o) { if (this == o) return true; if (o == null || getClass() != o.getClass()) return false; OpenInTerminalSettingsState that = (OpenInTerminalSettingsState) o; if (!terminalCommand.equals(that.terminalCommand)) return false; return terminalCommandOptions.equals(that.terminalCommandOptions); } @Override public int hashCode() { int result = terminalCommand.hashCode(); result = 31 * result + terminalCommandOptions.hashCode(); return result; } }
luktom/OpenInTerminal
src/main/java/settings/OpenInTerminalSettingsState.java
Java
lgpl-3.0
2,288
package org.ocbc.utils; import org.json.JSONObject; import java.io.BufferedReader; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL; import java.util.HashMap; public class request { public static JSONObject get(String url, HashMap<String, String> headers) { BufferedReader in = null; StringBuffer response = null; try { URL obj = new URL(url); HttpURLConnection con = (HttpURLConnection) obj.openConnection(); con.setRequestMethod("GET"); for (String key : headers.keySet()) { con.setRequestProperty(key, headers.get(key)); } in = new BufferedReader(new InputStreamReader(con.getInputStream())); response = new StringBuffer(); String inputLine; while ((inputLine = in.readLine()) != null) { response.append(inputLine); } in.close(); } catch(Exception exception) { System.out.println(exception); return null; } return new JSONObject(response.toString()); } }
connect2ocbc/jocbc
src/main/java/org/ocbc/utils/request.java
Java
lgpl-3.0
1,151
package org.openbase.bco.device.openhab.communication; /*- * #%L * BCO Openhab Device Manager * %% * Copyright (C) 2015 - 2021 openbase.org * %% * 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/gpl-3.0.html>. * #L% */ import com.google.gson.*; import org.eclipse.smarthome.core.internal.service.CommandDescriptionServiceImpl; import org.eclipse.smarthome.core.internal.types.CommandDescriptionImpl; import org.eclipse.smarthome.core.types.CommandDescription; import org.eclipse.smarthome.core.types.CommandDescriptionBuilder; import org.eclipse.smarthome.core.types.CommandOption; import org.openbase.bco.device.openhab.jp.JPOpenHABURI; import org.openbase.jps.core.JPService; import org.openbase.jps.exception.JPNotAvailableException; import org.openbase.jul.exception.InstantiationException; import org.openbase.jul.exception.*; import org.openbase.jul.exception.printer.ExceptionPrinter; import org.openbase.jul.exception.printer.LogLevel; import org.openbase.jul.iface.Shutdownable; import org.openbase.jul.pattern.Observable; import org.openbase.jul.pattern.ObservableImpl; import org.openbase.jul.pattern.Observer; import org.openbase.jul.schedule.GlobalScheduledExecutorService; import org.openbase.jul.schedule.SyncObject; import org.openbase.type.domotic.state.ConnectionStateType.ConnectionState; import org.openbase.type.domotic.state.ConnectionStateType.ConnectionState.State; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.ws.rs.ProcessingException; import javax.ws.rs.client.Client; import javax.ws.rs.client.ClientBuilder; import javax.ws.rs.client.Entity; import javax.ws.rs.client.WebTarget; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.ws.rs.sse.InboundSseEvent; import javax.ws.rs.sse.SseEventSource; import java.lang.reflect.Type; import java.util.HashMap; import java.util.List; import java.util.Map; import java.util.Map.Entry; import java.util.concurrent.RejectedExecutionException; import java.util.concurrent.ScheduledFuture; import java.util.concurrent.TimeUnit; import java.util.function.Consumer; public abstract class OpenHABRestConnection implements Shutdownable { public static final String SEPARATOR = "/"; public static final String REST_TARGET = "rest"; public static final String APPROVE_TARGET = "approve"; public static final String EVENTS_TARGET = "events"; public static final String TOPIC_KEY = "topic"; public static final String TOPIC_SEPARATOR = SEPARATOR; private static final Logger LOGGER = LoggerFactory.getLogger(OpenHABRestConnection.class); private final SyncObject topicObservableMapLock = new SyncObject("topicObservableMapLock"); private final SyncObject connectionStateSyncLock = new SyncObject("connectionStateSyncLock"); private final Map<String, ObservableImpl<Object, JsonObject>> topicObservableMap; private final Client restClient; private final WebTarget restTarget; private SseEventSource sseSource; private boolean shutdownInitiated = false; protected final JsonParser jsonParser; protected final Gson gson; private ScheduledFuture<?> connectionTask; protected ConnectionState.State openhabConnectionState = State.DISCONNECTED; public OpenHABRestConnection() throws InstantiationException { try { this.topicObservableMap = new HashMap<>(); this.gson = new GsonBuilder().setExclusionStrategies(new ExclusionStrategy() { @Override public boolean shouldSkipField(FieldAttributes fieldAttributes) { return false; } @Override public boolean shouldSkipClass(Class<?> aClass) { // ignore Command Description because its an interface and can not be serialized without any instance creator. if(aClass.equals(CommandDescription.class)) { return true; } return false; } }).create(); this.jsonParser = new JsonParser(); this.restClient = ClientBuilder.newClient(); this.restTarget = restClient.target(JPService.getProperty(JPOpenHABURI.class).getValue().resolve(SEPARATOR + REST_TARGET)); this.setConnectState(State.CONNECTING); } catch (JPNotAvailableException ex) { throw new InstantiationException(this, ex); } } private boolean isTargetReachable() { try { testConnection(); } catch (CouldNotPerformException e) { if (e.getCause() instanceof ProcessingException) { return false; } } return true; } protected abstract void testConnection() throws CouldNotPerformException; public void waitForConnectionState(final ConnectionState.State connectionState, final long timeout, final TimeUnit timeUnit) throws InterruptedException { synchronized (connectionStateSyncLock) { while (getOpenhabConnectionState() != connectionState) { connectionStateSyncLock.wait(timeUnit.toMillis(timeout)); } } } public void waitForConnectionState(final ConnectionState.State connectionState) throws InterruptedException { synchronized (connectionStateSyncLock) { while (getOpenhabConnectionState() != connectionState) { connectionStateSyncLock.wait(); } } } private void setConnectState(final ConnectionState.State connectState) { synchronized (connectionStateSyncLock) { // filter non changing states if (connectState == this.openhabConnectionState) { return; } LOGGER.trace("Openhab Connection State changed to: "+connectState); // update state this.openhabConnectionState = connectState; // handle state change switch (connectState) { case CONNECTING: LOGGER.info("Wait for openHAB..."); try { connectionTask = GlobalScheduledExecutorService.scheduleWithFixedDelay(() -> { if (isTargetReachable()) { // set connected setConnectState(State.CONNECTED); // cleanup own task connectionTask.cancel(false); } }, 0, 15, TimeUnit.SECONDS); } catch (NotAvailableException | RejectedExecutionException ex) { // if global executor service is not available we have no chance to connect. LOGGER.warn("Wait for openHAB...", ex); setConnectState(State.DISCONNECTED); } break; case CONNECTED: LOGGER.info("Connection to OpenHAB established."); initSSE(); break; case RECONNECTING: LOGGER.warn("Connection to OpenHAB lost!"); resetConnection(); setConnectState(State.CONNECTING); break; case DISCONNECTED: LOGGER.info("Connection to OpenHAB closed."); resetConnection(); break; } // notify state change connectionStateSyncLock.notifyAll(); // apply next state if required switch (connectState) { case RECONNECTING: setConnectState(State.CONNECTING); break; } } } private void initSSE() { // activate sse source if not already done if (sseSource != null) { LOGGER.warn("SSE already initialized!"); return; } final WebTarget webTarget = restTarget.path(EVENTS_TARGET); sseSource = SseEventSource.target(webTarget).reconnectingEvery(15, TimeUnit.SECONDS).build(); sseSource.open(); final Consumer<InboundSseEvent> evenConsumer = inboundSseEvent -> { // dispatch event try { final JsonObject payload = jsonParser.parse(inboundSseEvent.readData()).getAsJsonObject(); for (Entry<String, ObservableImpl<Object, JsonObject>> topicObserverEntry : topicObservableMap.entrySet()) { try { if (payload.get(TOPIC_KEY).getAsString().matches(topicObserverEntry.getKey())) { topicObserverEntry.getValue().notifyObservers(payload); } } catch (Exception ex) { ExceptionPrinter.printHistory(new CouldNotPerformException("Could not notify listeners on topic[" + topicObserverEntry.getKey() + "]", ex), LOGGER); } } } catch (Exception ex) { ExceptionPrinter.printHistory(new CouldNotPerformException("Could not handle SSE payload!", ex), LOGGER); } }; final Consumer<Throwable> errorHandler = ex -> { ExceptionPrinter.printHistory("Openhab connection error detected!", ex, LOGGER, LogLevel.DEBUG); checkConnectionState(); }; final Runnable reconnectHandler = () -> { checkConnectionState(); }; sseSource.register(evenConsumer, errorHandler, reconnectHandler); } public State getOpenhabConnectionState() { return openhabConnectionState; } public void checkConnectionState() { synchronized (connectionStateSyncLock) { // only validate if connected if (!isConnected()) { return; } // if not reachable init a reconnect if (!isTargetReachable()) { setConnectState(State.RECONNECTING); } } } public boolean isConnected() { return getOpenhabConnectionState() == State.CONNECTED; } public void addSSEObserver(Observer<Object, JsonObject> observer) { addSSEObserver(observer, ""); } public void addSSEObserver(final Observer<Object, JsonObject> observer, final String topicRegex) { synchronized (topicObservableMapLock) { if (topicObservableMap.containsKey(topicRegex)) { topicObservableMap.get(topicRegex).addObserver(observer); return; } final ObservableImpl<Object, JsonObject> observable = new ObservableImpl<>(this); observable.addObserver(observer); topicObservableMap.put(topicRegex, observable); } } public void removeSSEObserver(Observer<Object, JsonObject> observer) { removeSSEObserver(observer, ""); } public void removeSSEObserver(Observer<Object, JsonObject> observer, final String topicFilter) { synchronized (topicObservableMapLock) { if (topicObservableMap.containsKey(topicFilter)) { topicObservableMap.get(topicFilter).removeObserver(observer); } } } private void resetConnection() { // cancel ongoing connection task if (!connectionTask.isDone()) { connectionTask.cancel(false); } // close sse if (sseSource != null) { sseSource.close(); sseSource = null; } } public void validateConnection() throws CouldNotPerformException { if (!isConnected()) { throw new InvalidStateException("Openhab not reachable yet!"); } } private String validateResponse(final Response response) throws CouldNotPerformException, ProcessingException { return validateResponse(response, false); } private String validateResponse(final Response response, final boolean skipConnectionValidation) throws CouldNotPerformException, ProcessingException { final String result = response.readEntity(String.class); if (response.getStatus() == 200 || response.getStatus() == 201 || response.getStatus() == 202) { return result; } else if (response.getStatus() == 404) { if (!skipConnectionValidation) { checkConnectionState(); } throw new NotAvailableException("URL"); } else if (response.getStatus() == 503) { if (!skipConnectionValidation) { checkConnectionState(); } // throw a processing exception to indicate that openHAB is still not fully started, this is used to wait for openHAB throw new ProcessingException("OpenHAB server not ready"); } else { throw new CouldNotPerformException("Response returned with ErrorCode[" + response.getStatus() + "], Result[" + result + "] and ErrorMessage[" + response.getStatusInfo().getReasonPhrase() + "]"); } } protected String get(final String target) throws CouldNotPerformException { return get(target, false); } protected String get(final String target, final boolean skipValidation) throws CouldNotPerformException { try { // handle validation if (!skipValidation) { validateConnection(); } final WebTarget webTarget = restTarget.path(target); final Response response = webTarget.request().get(); return validateResponse(response, skipValidation); } catch (CouldNotPerformException | ProcessingException ex) { if (isShutdownInitiated()) { ExceptionProcessor.setInitialCause(ex, new ShutdownInProgressException(this)); } throw new CouldNotPerformException("Could not get sub-URL[" + target + "]", ex); } } protected String delete(final String target) throws CouldNotPerformException { try { validateConnection(); final WebTarget webTarget = restTarget.path(target); final Response response = webTarget.request().delete(); return validateResponse(response); } catch (CouldNotPerformException | ProcessingException ex) { if (isShutdownInitiated()) { ExceptionProcessor.setInitialCause(ex, new ShutdownInProgressException(this)); } throw new CouldNotPerformException("Could not delete sub-URL[" + target + "]", ex); } } protected String putJson(final String target, final Object value) throws CouldNotPerformException { return put(target, gson.toJson(value), MediaType.APPLICATION_JSON_TYPE); } protected String put(final String target, final String value, final MediaType mediaType) throws CouldNotPerformException { try { validateConnection(); final WebTarget webTarget = restTarget.path(target); final Response response = webTarget.request().put(Entity.entity(value, mediaType)); return validateResponse(response); } catch (CouldNotPerformException | ProcessingException ex) { if (isShutdownInitiated()) { ExceptionProcessor.setInitialCause(ex, new ShutdownInProgressException(this)); } throw new CouldNotPerformException("Could not put value[" + value + "] on sub-URL[" + target + "]", ex); } } protected String postJson(final String target, final Object value) throws CouldNotPerformException { return post(target, gson.toJson(value), MediaType.APPLICATION_JSON_TYPE); } protected String post(final String target, final String value, final MediaType mediaType) throws CouldNotPerformException { try { validateConnection(); final WebTarget webTarget = restTarget.path(target); final Response response = webTarget.request().post(Entity.entity(value, mediaType)); return validateResponse(response); } catch (CouldNotPerformException | ProcessingException ex) { if (isShutdownInitiated()) { ExceptionProcessor.setInitialCause(ex, new ShutdownInProgressException(this)); } throw new CouldNotPerformException("Could not post Value[" + value + "] of MediaType[" + mediaType + "] on sub-URL[" + target + "]", ex); } } public boolean isShutdownInitiated() { return shutdownInitiated; } @Override public void shutdown() { // prepare shutdown shutdownInitiated = true; setConnectState(State.DISCONNECTED); // stop rest service restClient.close(); // stop sse service synchronized (topicObservableMapLock) { for (final Observable<Object, JsonObject> jsonObjectObservable : topicObservableMap.values()) { jsonObjectObservable.shutdown(); } topicObservableMap.clear(); resetConnection(); } } }
DivineCooperation/bco.core-manager
openhab/src/main/java/org/openbase/bco/device/openhab/communication/OpenHABRestConnection.java
Java
lgpl-3.0
17,838
/* * SonarQube * Copyright (C) 2009-2016 SonarSource SA * mailto:contact AT sonarsource DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.api.server.authentication; import javax.annotation.concurrent.Immutable; import static com.google.common.base.Preconditions.checkArgument; import static org.apache.commons.lang.StringUtils.isNotBlank; /** * Display information provided by the Identity Provider to be displayed into the login form. * * @since 5.4 */ @Immutable public final class Display { private final String iconPath; private final String backgroundColor; private Display(Builder builder) { this.iconPath = builder.iconPath; this.backgroundColor = builder.backgroundColor; } /** * URL path to the provider icon, as deployed at runtime, for example "/static/authgithub/github.svg" (in this * case "authgithub" is the plugin key. Source file is "src/main/resources/static/github.svg"). * It can also be an external URL, for example "http://www.mydomain/myincon.png". * * Must not be blank. * <br> * The recommended format is SVG with a size of 24x24 pixels. * Other supported format is PNG, with a size of 40x40 pixels. */ public String getIconPath() { return iconPath; } /** * Background color for the provider button displayed in the login form. * It's a Hexadecimal value, for instance #205081. * <br> * If not provided, the default value is #236a97 */ public String getBackgroundColor() { return backgroundColor; } public static Builder builder() { return new Builder(); } public static class Builder { private String iconPath; private String backgroundColor = "#236a97"; private Builder() { } /** * @see Display#getIconPath() */ public Builder setIconPath(String iconPath) { this.iconPath = iconPath; return this; } /** * @see Display#getBackgroundColor() */ public Builder setBackgroundColor(String backgroundColor) { this.backgroundColor = backgroundColor; return this; } public Display build() { checkArgument(isNotBlank(iconPath), "Icon path must not be blank"); validateBackgroundColor(); return new Display(this); } private void validateBackgroundColor() { checkArgument(isNotBlank(backgroundColor), "Background color must not be blank"); checkArgument(backgroundColor.length() == 7 && backgroundColor.indexOf('#') == 0, "Background color must begin with a sharp followed by 6 characters"); } } }
Builders-SonarSource/sonarqube-bis
sonar-plugin-api/src/main/java/org/sonar/api/server/authentication/Display.java
Java
lgpl-3.0
3,286
/* * SonarQube, open source software quality management tool. * Copyright (C) 2008-2014 SonarSource * mailto:contact AT sonarsource DOT com * * SonarQube is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * SonarQube is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.computation.step; import com.google.common.collect.ImmutableMap; import java.util.ArrayList; import java.util.HashMap; import java.util.List; import java.util.Map; import org.apache.commons.codec.digest.DigestUtils; import org.apache.ibatis.session.ResultContext; import org.apache.ibatis.session.ResultHandler; import org.sonar.api.utils.System2; import org.sonar.batch.protocol.output.BatchReport; import org.sonar.core.persistence.DbSession; import org.sonar.core.persistence.MyBatis; import org.sonar.core.source.db.FileSourceDto; import org.sonar.core.source.db.FileSourceDto.Type; import org.sonar.server.computation.batch.BatchReportReader; import org.sonar.server.computation.component.Component; import org.sonar.server.computation.component.DepthTraversalTypeAwareVisitor; import org.sonar.server.computation.component.TreeRootHolder; import org.sonar.server.computation.source.ComputeFileSourceData; import org.sonar.server.computation.source.CoverageLineReader; import org.sonar.server.computation.source.DuplicationLineReader; import org.sonar.server.computation.source.HighlightingLineReader; import org.sonar.server.computation.source.LineReader; import org.sonar.server.computation.source.ScmLineReader; import org.sonar.server.computation.source.SymbolsLineReader; import org.sonar.server.db.DbClient; import org.sonar.server.source.db.FileSourceDb; import org.sonar.server.util.CloseableIterator; import static org.sonar.server.computation.component.DepthTraversalTypeAwareVisitor.Order.PRE_ORDER; public class PersistFileSourcesStep implements ComputationStep { private final DbClient dbClient; private final System2 system2; private final TreeRootHolder treeRootHolder; private final BatchReportReader reportReader; public PersistFileSourcesStep(DbClient dbClient, System2 system2, TreeRootHolder treeRootHolder, BatchReportReader reportReader) { this.dbClient = dbClient; this.system2 = system2; this.treeRootHolder = treeRootHolder; this.reportReader = reportReader; } @Override public void execute() { // Don't use batch insert for file_sources since keeping all data in memory can produce OOM for big files DbSession session = dbClient.openSession(false); try { new FileSourceVisitor(session).visit(treeRootHolder.getRoot()); } finally { MyBatis.closeQuietly(session); } } private class FileSourceVisitor extends DepthTraversalTypeAwareVisitor { private final DbSession session; private Map<String, FileSourceDto> previousFileSourcesByUuid = new HashMap<>(); private String projectUuid; private FileSourceVisitor(DbSession session) { super(Component.Type.FILE, PRE_ORDER); this.session = session; } @Override public void visitProject(Component project) { this.projectUuid = project.getUuid(); session.select("org.sonar.core.source.db.FileSourceMapper.selectHashesForProject", ImmutableMap.of("projectUuid", projectUuid, "dataType", Type.SOURCE), new ResultHandler() { @Override public void handleResult(ResultContext context) { FileSourceDto dto = (FileSourceDto) context.getResultObject(); previousFileSourcesByUuid.put(dto.getFileUuid(), dto); } }); } @Override public void visitFile(Component file) { int fileRef = file.getRef(); BatchReport.Component component = reportReader.readComponent(fileRef); CloseableIterator<String> linesIterator = reportReader.readFileSource(fileRef); LineReaders lineReaders = new LineReaders(reportReader, fileRef); try { ComputeFileSourceData computeFileSourceData = new ComputeFileSourceData(linesIterator, lineReaders.readers(), component.getLines()); ComputeFileSourceData.Data fileSourceData = computeFileSourceData.compute(); persistSource(fileSourceData, file.getUuid()); } catch (Exception e) { throw new IllegalStateException(String.format("Cannot persist sources of %s", file.getKey()), e); } finally { linesIterator.close(); lineReaders.close(); } } private void persistSource(ComputeFileSourceData.Data fileSourceData, String componentUuid) { FileSourceDb.Data fileData = fileSourceData.getFileSourceData(); byte[] data = FileSourceDto.encodeSourceData(fileData); String dataHash = DigestUtils.md5Hex(data); String srcHash = fileSourceData.getSrcHash(); String lineHashes = fileSourceData.getLineHashes(); FileSourceDto previousDto = previousFileSourcesByUuid.get(componentUuid); if (previousDto == null) { FileSourceDto dto = new FileSourceDto() .setProjectUuid(projectUuid) .setFileUuid(componentUuid) .setDataType(Type.SOURCE) .setBinaryData(data) .setSrcHash(srcHash) .setDataHash(dataHash) .setLineHashes(lineHashes) .setCreatedAt(system2.now()) .setUpdatedAt(system2.now()); dbClient.fileSourceDao().insert(session, dto); session.commit(); } else { // Update only if data_hash has changed or if src_hash is missing (progressive migration) boolean binaryDataUpdated = !dataHash.equals(previousDto.getDataHash()); boolean srcHashUpdated = !srcHash.equals(previousDto.getSrcHash()); if (binaryDataUpdated || srcHashUpdated) { previousDto .setBinaryData(data) .setDataHash(dataHash) .setSrcHash(srcHash) .setLineHashes(lineHashes); // Optimization only change updated at when updating binary data to avoid unnecessary indexation by E/S if (binaryDataUpdated) { previousDto.setUpdatedAt(system2.now()); } dbClient.fileSourceDao().update(previousDto); session.commit(); } } } } private static class LineReaders { private final List<LineReader> readers = new ArrayList<>(); private final List<CloseableIterator<?>> iterators = new ArrayList<>(); LineReaders(BatchReportReader reportReader, int componentRef) { CloseableIterator<BatchReport.Coverage> coverageReportIterator = reportReader.readComponentCoverage(componentRef); BatchReport.Changesets scmReport = reportReader.readChangesets(componentRef); CloseableIterator<BatchReport.SyntaxHighlighting> highlightingIterator = reportReader.readComponentSyntaxHighlighting(componentRef); List<BatchReport.Symbols.Symbol> symbols = reportReader.readComponentSymbols(componentRef); List<BatchReport.Duplication> duplications = reportReader.readComponentDuplications(componentRef); if (coverageReportIterator != null) { iterators.add(coverageReportIterator); readers.add(new CoverageLineReader(coverageReportIterator)); } if (scmReport != null) { readers.add(new ScmLineReader(scmReport)); } if (highlightingIterator != null) { iterators.add(highlightingIterator); readers.add(new HighlightingLineReader(highlightingIterator)); } if (!duplications.isEmpty()) { readers.add(new DuplicationLineReader(duplications)); } if (!symbols.isEmpty()) { readers.add(new SymbolsLineReader(symbols)); } } List<LineReader> readers() { return readers; } void close() { for (CloseableIterator<?> reportIterator : iterators) { reportIterator.close(); } } } @Override public String getDescription() { return "Persist file sources"; } }
jblievremont/sonarqube
server/sonar-server/src/main/java/org/sonar/server/computation/step/PersistFileSourcesStep.java
Java
lgpl-3.0
8,521
package com.wangdaye.common.base.fragment; import com.wangdaye.common.base.activity.LoadableActivity; import java.util.List; /** * Loadable fragment. * */ public abstract class LoadableFragment<T> extends MysplashFragment { /** * {@link LoadableActivity#loadMoreData(List, int, boolean)}. * */ public abstract List<T> loadMoreData(List<T> list, int headIndex, boolean headDirection); }
WangDaYeeeeee/Mysplash
common/src/main/java/com/wangdaye/common/base/fragment/LoadableFragment.java
Java
lgpl-3.0
411
/*--- iGeo - http://igeo.jp Copyright (c) 2002-2013 Satoru Sugihara This file is part of iGeo. iGeo is free software: you can redistribute it and/or modify it under the terms of the GNU Lesser General Public License as published by the Free Software Foundation, version 3. iGeo is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. You should have received a copy of the GNU Lesser General Public License along with iGeo. If not, see <http://www.gnu.org/licenses/>. ---*/ package igeo; import java.awt.*; import igeo.gui.*; /** Class of point object. @author Satoru Sugihara */ public class IPoint extends IGeometry implements IVecI{ //public IVecI pos; public IVec pos; public IPoint(){ pos = new IVec(); initPoint(null); } public IPoint(IVec v){ pos = v; initPoint(null); } public IPoint(IVecI v){ pos = v.get(); initPoint(null); } public IPoint(double x, double y, double z){ pos = new IVec(x,y,z); initPoint(null); } public IPoint(double x, double y){ pos = new IVec(x,y); initPoint(null); } public IPoint(IServerI s){ super(s); pos = new IVec(0,0,0); initPoint(s); } public IPoint(IServerI s, IVec v){ super(s); pos = v; initPoint(s); } public IPoint(IServerI s, IVecI v){ super(s); pos = v.get(); initPoint(s); } public IPoint(IServerI s, double x, double y, double z){ super(s); pos = new IVec(x,y,z); initPoint(s); } public IPoint(IServerI s, double x, double y){ super(s); pos = new IVec(x,y); initPoint(s); } public IPoint(IPoint p){ super(p); pos = p.pos.dup(); initPoint(p.server); //setColor(p.getColor()); } public IPoint(IServerI s, IPoint p){ super(s,p); pos = p.pos.dup(); initPoint(s); //setColor(p.getColor()); } public /*protected*/ void initPoint(IServerI s){ if(pos==null){ IOut.err("null value is set in IPoint"); // return; } // // costly to use instanceof? //if(pos instanceof IVec) parameter = (IVec)pos; //else if(pos instanceof IVecR) parameter = (IVecR)pos; //else if(pos instanceof IVec4) parameter = (IVec4)pos; //else if(pos instanceof IVec4R) parameter = (IVec4R)pos; //addGraphic(new IPointGraphic(this)); if(graphics==null) initGraphic(s); // not init when using copy constructor } public IGraphicObject createGraphic(IGraphicMode m){ if(m.isNone()) return null; return new IPointGraphic(this); } synchronized public double x(){ return pos.x(); } synchronized public double y(){ return pos.y(); } synchronized public double z(){ return pos.z(); } synchronized public IPoint x(double vx){ pos.x(vx); return this; } synchronized public IPoint y(double vy){ pos.y(vy); return this; } synchronized public IPoint z(double vz){ pos.z(vz); return this; } synchronized public IPoint x(IDoubleI vx){ pos.x(vx); return this; } synchronized public IPoint y(IDoubleI vy){ pos.y(vy); return this; } synchronized public IPoint z(IDoubleI vz){ pos.z(vz); return this; } synchronized public IPoint x(IVecI vx){ pos.x(vx); return this; } synchronized public IPoint y(IVecI vy){ pos.y(vy); return this; } synchronized public IPoint z(IVecI vz){ pos.z(vz); return this; } synchronized public IPoint x(IVec2I vx){ pos.x(vx); return this; } synchronized public IPoint y(IVec2I vy){ pos.y(vy); return this; } synchronized public double x(ISwitchE e){ return pos.x(e); } synchronized public double y(ISwitchE e){ return pos.y(e); } synchronized public double z(ISwitchE e){ return pos.z(e); } synchronized public IDouble x(ISwitchR r){ return pos.x(r); } synchronized public IDouble y(ISwitchR r){ return pos.y(r); } synchronized public IDouble z(ISwitchR r){ return pos.z(r); } //synchronized public IVec get(){ return pos.get(); } // when pos is IVecI synchronized public IVec get(){ return pos; } /** passing position field */ synchronized public IVec pos(){ return pos; } /** center is same with position */ synchronized public IVec center(){ return pos(); } synchronized public IPoint dup(){ return new IPoint(this); } synchronized public IVec2 to2d(){ return pos.to2d(); } synchronized public IVec2 to2d(IVecI projectionDir){ return pos.to2d(projectionDir); } synchronized public IVec2 to2d(IVecI xaxis, IVecI yaxis){ return pos.to2d(xaxis,yaxis); } synchronized public IVec2 to2d(IVecI xaxis, IVecI yaxis, IVecI origin){ return pos.to2d(xaxis,yaxis,origin); } synchronized public IVec4 to4d(){ return pos.to4d(); } synchronized public IVec4 to4d(double w){ return pos.to4d(w); } synchronized public IVec4 to4d(IDoubleI w){ return pos.to4d(w); } synchronized public IDouble getX(){ return pos.getX(); } synchronized public IDouble getY(){ return pos.getY(); } synchronized public IDouble getZ(){ return pos.getZ(); } synchronized public IPoint set(IVecI v){ pos.set(v); return this; } synchronized public IPoint set(double x, double y, double z){ pos.set(x,y,z); return this;} synchronized public IPoint set(IDoubleI x, IDoubleI y, IDoubleI z){ pos.set(x,y,z); return this; } synchronized public IPoint add(double x, double y, double z){ pos.add(x,y,z); return this; } synchronized public IPoint add(IDoubleI x, IDoubleI y, IDoubleI z){ pos.add(x,y,z); return this; } synchronized public IPoint add(IVecI v){ pos.add(v); return this; } synchronized public IPoint sub(double x, double y, double z){ pos.sub(x,y,z); return this; } synchronized public IPoint sub(IDoubleI x, IDoubleI y, IDoubleI z){ pos.sub(x,y,z); return this; } synchronized public IPoint sub(IVecI v){ pos.sub(v); return this; } synchronized public IPoint mul(IDoubleI v){ pos.mul(v); return this; } synchronized public IPoint mul(double v){ pos.mul(v); return this; } synchronized public IPoint div(IDoubleI v){ pos.div(v); return this; } synchronized public IPoint div(double v){ pos.div(v); return this; } synchronized public IPoint neg(){ pos.neg(); return this; } synchronized public IPoint rev(){ return neg(); } synchronized public IPoint flip(){ return neg(); } synchronized public IPoint zero(){ pos.zero(); return this; } /** scale add */ synchronized public IPoint add(IVecI v, double f){ pos.add(v,f); return this; } synchronized public IPoint add(IVecI v, IDoubleI f){ pos.add(v,f); return this; } /** scale add alias */ synchronized public IPoint add(double f, IVecI v){ return add(v,f); } synchronized public IPoint add(IDoubleI f, IVecI v){ return add(v,f); } synchronized public double dot(IVecI v){ return pos.dot(v); } synchronized public double dot(double vx, double vy, double vz){ return pos.dot(vx,vy,vz); } synchronized public double dot(ISwitchE e, IVecI v){ return pos.dot(e,v); } synchronized public IDouble dot(ISwitchR r, IVecI v){ return pos.dot(r,v); } // creating IPoint is too much (in terms of memory occupancy) //synchronized public IPoint cross(IVecI v){ return dup().set(pos.cross(v)); } synchronized public IVec cross(IVecI v){ return pos.cross(v); } synchronized public IVec cross(double vx, double vy, double vz){ return pos.cross(vx,vy,vz); } synchronized public double len(){ return pos.len(); } synchronized public double len(ISwitchE e){ return pos.len(e); } synchronized public IDouble len(ISwitchR r){ return pos.len(r); } synchronized public double len2(){ return pos.len2(); } synchronized public double len2(ISwitchE e){ return pos.len2(e); } synchronized public IDouble len2(ISwitchR r){ return pos.len2(r); } synchronized public IPoint len(IDoubleI l){ pos.len(l); return this; } synchronized public IPoint len(double l){ pos.len(l); return this; } synchronized public IPoint unit(){ pos.unit(); return this; } synchronized public double dist(IVecI v){ return pos.dist(v); } synchronized public double dist(double vx, double vy, double vz){ return pos.dist(vx,vy,vz); } synchronized public double dist(ISwitchE e, IVecI v){ return pos.dist(e,v); } synchronized public IDouble dist(ISwitchR r, IVecI v){ return pos.dist(r,v); } synchronized public double dist2(IVecI v){ return pos.dist2(v); } synchronized public double dist2(double vx, double vy, double vz){ return pos.dist2(vx,vy,vz); } synchronized public double dist2(ISwitchE e, IVecI v){ return pos.dist2(e,v); } synchronized public IDouble dist2(ISwitchR r, IVecI v){ return pos.dist2(r,v); } synchronized public boolean eq(IVecI v){ return pos.eq(v); } synchronized public boolean eq(double vx, double vy, double vz){ return pos.eq(vx,vy,vz); } synchronized public boolean eq(ISwitchE e, IVecI v){ return pos.eq(e,v); } synchronized public IBool eq(ISwitchR r, IVecI v){ return pos.eq(r,v); } synchronized public boolean eq(IVecI v, double tolerance){ return pos.eq(v,tolerance); } synchronized public boolean eq(double vx, double vy, double vz, double tolerance){ return pos.eq(vx,vy,vz,tolerance); } synchronized public boolean eq(ISwitchE e, IVecI v, double tolerance){ return pos.eq(e,v,tolerance); } synchronized public IBool eq(ISwitchR r, IVecI v, IDoubleI tolerance){ return pos.eq(r,v,tolerance); } synchronized public boolean eqX(IVecI v){ return pos.eqX(v); } synchronized public boolean eqY(IVecI v){ return pos.eqY(v); } synchronized public boolean eqZ(IVecI v){ return pos.eqZ(v); } synchronized public boolean eqX(double vx){ return pos.eqX(vx); } synchronized public boolean eqY(double vy){ return pos.eqY(vy); } synchronized public boolean eqZ(double vz){ return pos.eqZ(vz); } synchronized public boolean eqX(ISwitchE e, IVecI v){ return pos.eqX(e,v); } synchronized public boolean eqY(ISwitchE e, IVecI v){ return pos.eqY(e,v); } synchronized public boolean eqZ(ISwitchE e, IVecI v){ return pos.eqZ(e,v); } synchronized public IBool eqX(ISwitchR r, IVecI v){ return pos.eqX(r,v); } synchronized public IBool eqY(ISwitchR r, IVecI v){ return pos.eqY(r,v); } synchronized public IBool eqZ(ISwitchR r, IVecI v){ return pos.eqZ(r,v); } synchronized public boolean eqX(IVecI v, double tolerance){ return pos.eqX(v,tolerance); } synchronized public boolean eqY(IVecI v, double tolerance){ return pos.eqY(v,tolerance); } synchronized public boolean eqZ(IVecI v, double tolerance){ return pos.eqZ(v,tolerance); } synchronized public boolean eqX(double vx, double tolerance){ return pos.eqX(vx,tolerance); } synchronized public boolean eqY(double vy, double tolerance){ return pos.eqY(vy,tolerance); } synchronized public boolean eqZ(double vz, double tolerance){ return pos.eqZ(vz,tolerance); } synchronized public boolean eqX(ISwitchE e, IVecI v, double tolerance){ return pos.eqX(e,v,tolerance); } synchronized public boolean eqY(ISwitchE e, IVecI v, double tolerance){ return pos.eqY(e,v,tolerance); } synchronized public boolean eqZ(ISwitchE e, IVecI v, double tolerance){ return pos.eqZ(e,v,tolerance); } synchronized public IBool eqX(ISwitchR r, IVecI v, IDoubleI tolerance){ return pos.eqX(r,v,tolerance); } synchronized public IBool eqY(ISwitchR r, IVecI v, IDoubleI tolerance){ return pos.eqY(r,v,tolerance); } synchronized public IBool eqZ(ISwitchR r, IVecI v, IDoubleI tolerance){ return pos.eqZ(r,v,tolerance); } synchronized public double angle(IVecI v){ return pos.angle(v); } synchronized public double angle(double vx, double vy, double vz){ return pos.angle(vx,vy,vz); } synchronized public double angle(ISwitchE e, IVecI v){ return pos.angle(e,v); } synchronized public IDouble angle(ISwitchR r, IVecI v){ return pos.angle(r,v); } synchronized public double angle(IVecI v, IVecI axis){ return pos.angle(v,axis); } synchronized public double angle(double vx, double vy, double vz, double axisX, double axisY, double axisZ){ return pos.angle(vx,vy,vz,axisX,axisY,axisZ); } synchronized public double angle(ISwitchE e, IVecI v, IVecI axis){ return pos.angle(e,v,axis); } synchronized public IDouble angle(ISwitchR r, IVecI v, IVecI axis){ return pos.angle(r,v,axis); } synchronized public IPoint rot(IDoubleI angle){ pos.rot(angle); return this; } synchronized public IPoint rot(double angle){ pos.rot(angle); return this; } synchronized public IPoint rot(IVecI axis, IDoubleI angle){ pos.rot(axis,angle); return this; } synchronized public IPoint rot(IVecI axis, double angle){ pos.rot(axis,angle); return this; } synchronized public IPoint rot(double axisX, double axisY, double axisZ, double angle){ pos.rot(axisX,axisY,axisZ,angle); return this; } synchronized public IPoint rot(IVecI center, IVecI axis, double angle){ pos.rot(center, axis,angle); return this; } synchronized public IPoint rot(double centerX, double centerY, double centerZ, double axisX, double axisY, double axisZ, double angle){ pos.rot(centerX, centerY, centerZ, axisX, axisY, axisZ, angle); return this; } synchronized public IPoint rot(IVecI center, IVecI axis, IDoubleI angle){ pos.rot(center, axis,angle); return this; } /** Rotate to destination direction vector. */ synchronized public IPoint rot(IVecI axis, IVecI destDir){ pos.rot(axis,destDir); return this; } /** Rotate to destination point location. */ synchronized public IPoint rot(IVecI center, IVecI axis, IVecI destPt){ pos.rot(center,axis,destPt); return this; } synchronized public IPoint rot2(IDoubleI angle){ pos.rot2(angle); return this; } synchronized public IPoint rot2(double angle){ pos.rot2(angle); return this; } synchronized public IPoint rot2(IVecI center, double angle){ pos.rot2(center, angle); return this; } synchronized public IPoint rot2(double centerX, double centerY, double angle){ pos.rot2(centerX, centerY, angle); return this; } synchronized public IPoint rot2(IVecI center, IDoubleI angle){ pos.rot2(center, angle); return this; } /** Rotate to destination direction vector. */ synchronized public IPoint rot2(IVecI destDir){ pos.rot2(destDir); return this; } /** Rotate to destination point location. */ synchronized public IPoint rot2(IVecI center, IVecI destPt){ pos.rot2(center,destPt); return this; } /** alias of mul */ synchronized public IPoint scale(IDoubleI f){ pos.scale(f); return this; } /** alias of mul */ synchronized public IPoint scale(double f){ pos.scale(f); return this; } synchronized public IPoint scale(IVecI center, IDoubleI f){ pos.scale(center,f); return this; } synchronized public IPoint scale(IVecI center, double f){ pos.scale(center,f); return this; } synchronized public IPoint scale(double centerX, double centerY, double centerZ, double f){ pos.scale(centerX, centerY, centerZ, f); return this; } /** scale only in 1 direction */ synchronized public IPoint scale1d(IVecI axis, double f){ pos.scale1d(axis,f); return this; } synchronized public IPoint scale1d(double axisX, double axisY, double axisZ, double f){ pos.scale1d(axisX,axisY,axisZ,f); return this; } synchronized public IPoint scale1d(IVecI axis, IDoubleI f){ pos.scale1d(axis,f); return this; } synchronized public IPoint scale1d(IVecI center, IVecI axis, double f){ pos.scale1d(center,axis,f); return this; } synchronized public IPoint scale1d(double centerX, double centerY, double centerZ, double axisX, double axisY, double axisZ, double f){ pos.scale1d(centerX,centerY,centerZ,axisX,axisY,axisZ,f); return this; } synchronized public IPoint scale1d(IVecI center, IVecI axis, IDoubleI f){ pos.scale1d(center,axis,f); return this; } /** reflect (mirror) 3 dimensionally to the other side of the plane */ synchronized public IPoint ref(IVecI planeDir){ pos.ref(planeDir); return this; } /** reflect (mirror) 3 dimensionally to the other side of the plane */ synchronized public IPoint ref(double planeX, double planeY, double planeZ){ pos.ref(planeX,planeY,planeZ); return this; } /** reflect (mirror) 3 dimensionally to the other side of the plane */ synchronized public IPoint ref(IVecI center, IVecI planeDir){ pos.ref(center,planeDir); return this; } /** reflect (mirror) 3 dimensionally to the other side of the plane */ synchronized public IPoint ref(double centerX, double centerY, double centerZ, double planeX, double planeY, double planeZ){ pos.ref(centerX,centerY,centerZ,planeX,planeY,planeZ); return this; } /** reflect (mirror) 3 dimensionally to the other side of the plane */ synchronized public IPoint mirror(IVecI planeDir){ pos.ref(planeDir); return this; } /** reflect (mirror) 3 dimensionally to the other side of the plane */ synchronized public IPoint mirror(double planeX, double planeY, double planeZ){ pos.ref(planeX,planeY,planeZ); return this; } /** reflect (mirror) 3 dimensionally to the other side of the plane */ synchronized public IPoint mirror(IVecI center, IVecI planeDir){ pos.ref(center,planeDir); return this; } /** reflect (mirror) 3 dimensionally to the other side of the plane */ synchronized public IPoint mirror(double centerX, double centerY, double centerZ, double planeX, double planeY, double planeZ){ pos.ref(centerX,centerY,centerZ,planeX,planeY,planeZ); return this; } /** shear operation */ synchronized public IPoint shear(double sxy, double syx, double syz, double szy, double szx, double sxz){ pos.shear(sxy,syx,syz,szy,szx,sxz); return this; } synchronized public IPoint shear(IDoubleI sxy, IDoubleI syx, IDoubleI syz, IDoubleI szy, IDoubleI szx, IDoubleI sxz){ pos.shear(sxy,syx,syz,szy,szx,sxz); return this; } synchronized public IPoint shear(IVecI center, double sxy, double syx, double syz, double szy, double szx, double sxz){ pos.shear(center,sxy,syx,syz,szy,szx,sxz); return this; } synchronized public IPoint shear(IVecI center, IDoubleI sxy, IDoubleI syx, IDoubleI syz, IDoubleI szy, IDoubleI szx, IDoubleI sxz){ pos.shear(center,sxy,syx,syz,szy,szx,sxz); return this; } synchronized public IPoint shearXY(double sxy, double syx){ pos.shearXY(sxy,syx); return this; } synchronized public IPoint shearXY(IDoubleI sxy, IDoubleI syx){ pos.shearXY(sxy,syx); return this; } synchronized public IPoint shearXY(IVecI center, double sxy, double syx){ pos.shearXY(center,sxy,syx); return this; } synchronized public IPoint shearXY(IVecI center, IDoubleI sxy, IDoubleI syx){ pos.shearXY(center,sxy,syx); return this; } synchronized public IPoint shearYZ(double syz, double szy){ pos.shearYZ(syz,szy); return this; } synchronized public IPoint shearYZ(IDoubleI syz, IDoubleI szy){ pos.shearYZ(syz,szy); return this; } synchronized public IPoint shearYZ(IVecI center, double syz, double szy){ pos.shearYZ(center,syz,szy); return this; } synchronized public IPoint shearYZ(IVecI center, IDoubleI syz, IDoubleI szy){ pos.shearYZ(center,syz,szy); return this; } synchronized public IPoint shearZX(double szx, double sxz){ pos.shearZX(szx,sxz); return this; } synchronized public IPoint shearZX(IDoubleI szx, IDoubleI sxz){ pos.shearZX(szx,sxz); return this; } synchronized public IPoint shearZX(IVecI center, double szx, double sxz){ pos.shearZX(center,szx,sxz); return this; } synchronized public IPoint shearZX(IVecI center, IDoubleI szx, IDoubleI sxz){ pos.shearZX(center,szx,sxz); return this; } /** translate is alias of add() */ synchronized public IPoint translate(double x, double y, double z){ pos.translate(x,y,z); return this; } synchronized public IPoint translate(IDoubleI x, IDoubleI y, IDoubleI z){ pos.translate(x,y,z); return this; } synchronized public IPoint translate(IVecI v){ pos.translate(v); return this; } synchronized public IPoint transform(IMatrix3I mat){ pos.transform(mat); return this; } synchronized public IPoint transform(IMatrix4I mat){ pos.transform(mat); return this; } synchronized public IPoint transform(IVecI xvec, IVecI yvec, IVecI zvec){ pos.transform(xvec,yvec,zvec); return this; } synchronized public IPoint transform(IVecI xvec, IVecI yvec, IVecI zvec, IVecI translate){ pos.transform(xvec,yvec,zvec,translate); return this; } /** mv() is alias of add() */ synchronized public IPoint mv(double x, double y, double z){ return add(x,y,z); } synchronized public IPoint mv(IDoubleI x, IDoubleI y, IDoubleI z){ return add(x,y,z); } synchronized public IPoint mv(IVecI v){ return add(v); } // method name cp() is used as getting control point method in curve and surface but here used also as copy because of the priority of variable fitting of diversed users' mind set over the clarity of the code organization /** cp() is alias of dup() */ synchronized public IPoint cp(){ return dup(); } /** cp() is alias of dup().add() */ synchronized public IPoint cp(double x, double y, double z){ return dup().add(x,y,z); } synchronized public IPoint cp(IDoubleI x, IDoubleI y, IDoubleI z){ return dup().add(x,y,z); } synchronized public IPoint cp(IVecI v){ return dup().add(v); } // methods creating new instance // returns IPoint?, not IVec? // returns IVec, not IPoint (2011/10/12) //synchronized public IPoint diff(IVecI v){ return dup().sub(v); } synchronized public IVec dif(IVecI v){ return pos.dif(v); } synchronized public IVec dif(double vx, double vy, double vz){ return pos.dif(vx,vy,vz); } synchronized public IVec diff(IVecI v){ return dif(v); } synchronized public IVec diff(double vx, double vy, double vz){ return dif(vx,vy,vz); } //synchronized public IPoint mid(IVecI v){ return dup().add(v).div(2); } synchronized public IVec mid(IVecI v){ return pos.mid(v); } synchronized public IVec mid(double vx, double vy, double vz){ return pos.mid(vx,vy,vz); } //synchronized public IPoint sum(IVecI v){ return dup().add(v); } synchronized public IVec sum(IVecI v){ return pos.sum(v); } synchronized public IVec sum(double vx, double vy, double vz){ return pos.sum(vx,vy,vz); } //synchronized public IPoint sum(IVecI... v){ IPoint ret = this.dup(); for(IVecI vi: v) ret.add(vi); return ret; } synchronized public IVec sum(IVecI... v){ return pos.sum(v); } //synchronized public IPoint bisect(IVecI v){ return dup().unit().add(v.dup().unit()); } synchronized public IVec bisect(IVecI v){ return pos.bisect(v); } synchronized public IVec bisect(double vx, double vy, double vz){ return pos.bisect(vx,vy,vz); } /** weighted sum. @return IVec */ //synchronized public IPoint sum(IVecI v2, double w1, double w2){ return dup().mul(w1).add(v2,w2); } synchronized public IVec sum(IVecI v2, double w1, double w2){ return pos.sum(v2,w1,w2); } //synchronized public IPoint sum(IVecI v2, double w2){ return dup().mul(1.0-w2).add(v2,w2); } synchronized public IVec sum(IVecI v2, double w2){ return pos.sum(v2,w2); } //synchronized public IPoint sum(IVecI v2, IDoubleI w1, IDoubleI w2){ return dup().mul(w1).add(v2,w2); } synchronized public IVec sum(IVecI v2, IDoubleI w1, IDoubleI w2){ return sum(v2,w1,w2); } //synchronized public IPoint sum(IVecI v2, IDoubleI w2){ return dup().mul(new IDouble(1.0).sub(w2)).add(v2,w2); } synchronized public IVec sum(IVecI v2, IDoubleI w2){ return sum(v2,w2); } /** alias of cross. (not unitized ... ?) */ //synchronized public IPoint nml(IVecI v){ return cross(v); } synchronized public IVec nml(IVecI v){ return pos.nml(v); } synchronized public IVec nml(double vx, double vy, double vz){ return pos.nml(vx,vy,vz); } /** create normal vector from 3 points of self, pt1 and pt2 */ //synchronized public IPoint nml(IVecI pt1, IVecI pt2){ return this.diff(pt1).cross(this.diff(pt2)).unit(); } synchronized public IVec nml(IVecI pt1, IVecI pt2){ return pos.nml(pt1,pt2); } synchronized public IVec nml(double vx1, double vy1, double vz1, double vx2, double vy2, double vz2){ return pos.nml(vx1,vy1,vz1,vx2,vy2,vz2); } /** checking x, y, and z is valid number (not Infinite, nor NaN). */ synchronized public boolean isValid(){ if(pos==null){ return false; } return pos.isValid(); } synchronized public String toString(){ if(pos==null) return super.toString(); return pos.toString(); } /** default setting in each object class; to be overridden in a child class */ public IAttribute defaultAttribute(){ IAttribute a = new IAttribute(); a.weight = IConfig.pointSize; return a; } /** set size of dot in graphic ; it's just alias of weight() */ synchronized public IPoint setSize(double sz){ return weight(sz); } synchronized public IPoint size(double sz){ return weight(sz); } /* synchronized public IPoint setSize(double sz){ return size(sz); } synchronized public IPoint size(double sz){ for(int i=0; graphics!=null && i<graphics.size(); i++) if(graphics.get(i) instanceof IPointGraphic) ((IPointGraphic)graphics.get(i)).size(sz); return this; } */ synchronized public double getSize(){ return size(); } public double size(){ if(graphics==null){ IOut.err("no graphics is set"); // return -1; } for(int i=0; graphics!=null && i<graphics.size(); i++) if(graphics.get(i) instanceof IPointGraphic) return ((IPointGraphic)graphics.get(i)).size(); return -1; } synchronized public IPoint name(String nm){ super.name(nm); return this; } synchronized public IPoint layer(ILayer l){ super.layer(l); return this; } synchronized public IPoint layer(String l){ super.layer(l); return this; } synchronized public IPoint attr(IAttribute at){ super.attr(at); return this; } synchronized public IPoint hide(){ super.hide(); return this; } synchronized public IPoint show(){ super.show(); return this; } synchronized public IPoint clr(IColor c){ super.clr(c); return this; } synchronized public IPoint clr(IColor c, int alpha){ super.clr(c,alpha); return this; } synchronized public IPoint clr(IColor c, float alpha){ super.clr(c,alpha); return this; } synchronized public IPoint clr(IColor c, double alpha){ super.clr(c,alpha); return this; } synchronized public IPoint clr(IObject o){ super.clr(o); return this; } synchronized public IPoint clr(Color c){ super.clr(c); return this; } synchronized public IPoint clr(Color c, int alpha){ super.clr(c,alpha); return this; } synchronized public IPoint clr(Color c, float alpha){ super.clr(c,alpha); return this; } synchronized public IPoint clr(Color c, double alpha){ super.clr(c,alpha); return this; } synchronized public IPoint clr(int gray){ super.clr(gray); return this; } synchronized public IPoint clr(float fgray){ super.clr(fgray); return this; } synchronized public IPoint clr(double dgray){ super.clr(dgray); return this; } synchronized public IPoint clr(int gray, int alpha){ super.clr(gray,alpha); return this; } synchronized public IPoint clr(float fgray, float falpha){ super.clr(fgray,falpha); return this; } synchronized public IPoint clr(double dgray, double dalpha){ super.clr(dgray,dalpha); return this; } synchronized public IPoint clr(int r, int g, int b){ super.clr(r,g,b); return this; } synchronized public IPoint clr(float fr, float fg, float fb){ super.clr(fr,fg,fb); return this; } synchronized public IPoint clr(double dr, double dg, double db){ super.clr(dr,dg,db); return this; } synchronized public IPoint clr(int r, int g, int b, int a){ super.clr(r,g,b,a); return this; } synchronized public IPoint clr(float fr, float fg, float fb, float fa){ super.clr(fr,fg,fb,fa); return this; } synchronized public IPoint clr(double dr, double dg, double db, double da){ super.clr(dr,dg,db,da); return this; } synchronized public IPoint hsb(float h, float s, float b, float a){ super.hsb(h,s,b,a); return this; } synchronized public IPoint hsb(double h, double s, double b, double a){ super.hsb(h,s,b,a); return this; } synchronized public IPoint hsb(float h, float s, float b){ super.hsb(h,s,b); return this; } synchronized public IPoint hsb(double h, double s, double b){ super.hsb(h,s,b); return this; } synchronized public IPoint setColor(IColor c){ super.setColor(c); return this; } synchronized public IPoint setColor(IColor c, int alpha){ super.setColor(c,alpha); return this; } synchronized public IPoint setColor(IColor c, float alpha){ super.setColor(c,alpha); return this; } synchronized public IPoint setColor(IColor c, double alpha){ super.setColor(c,alpha); return this; } synchronized public IPoint setColor(Color c){ super.setColor(c); return this; } synchronized public IPoint setColor(Color c, int alpha){ super.setColor(c,alpha); return this; } synchronized public IPoint setColor(Color c, float alpha){ super.setColor(c,alpha); return this; } synchronized public IPoint setColor(Color c, double alpha){ super.setColor(c,alpha); return this; } synchronized public IPoint setColor(int gray){ super.setColor(gray); return this; } synchronized public IPoint setColor(float fgray){ super.setColor(fgray); return this; } synchronized public IPoint setColor(double dgray){ super.setColor(dgray); return this; } synchronized public IPoint setColor(int gray, int alpha){ super.setColor(gray,alpha); return this; } synchronized public IPoint setColor(float fgray, float falpha){ super.setColor(fgray,falpha); return this; } synchronized public IPoint setColor(double dgray, double dalpha){ super.setColor(dgray,dalpha); return this; } synchronized public IPoint setColor(int r, int g, int b){ super.setColor(r,g,b); return this; } synchronized public IPoint setColor(float fr, float fg, float fb){ super.setColor(fr,fg,fb); return this; } synchronized public IPoint setColor(double dr, double dg, double db){ super.setColor(dr,dg,db); return this; } synchronized public IPoint setColor(int r, int g, int b, int a){ super.setColor(r,g,b,a); return this; } synchronized public IPoint setColor(float fr, float fg, float fb, float fa){ super.setColor(fr,fg,fb,fa); return this; } synchronized public IPoint setColor(double dr, double dg, double db, double da){ super.setColor(dr,dg,db,da); return this; } synchronized public IPoint setHSBColor(float h, float s, float b, float a){ super.setHSBColor(h,s,b,a); return this; } synchronized public IPoint setHSBColor(double h, double s, double b, double a){ super.setHSBColor(h,s,b,a); return this; } synchronized public IPoint setHSBColor(float h, float s, float b){ super.setHSBColor(h,s,b); return this; } synchronized public IPoint setHSBColor(double h, double s, double b){ super.setHSBColor(h,s,b); return this; } synchronized public IPoint weight(double w){ super.weight(w); return this; } synchronized public IPoint weight(float w){ super.weight(w); return this; } }
sghr/iGeo
IPoint.java
Java
lgpl-3.0
31,733
package org.yawlfoundation.yawl.worklet.client; import org.yawlfoundation.yawl.editor.ui.specification.SpecificationModel; import org.yawlfoundation.yawl.engine.YSpecificationID; import java.io.IOException; import java.util.Map; /** * @author Michael Adams * @date 18/02/2016 */ public class TaskIDChangeMap { private Map<String, String> _changedIdentifiers; public TaskIDChangeMap(Map<String, String> changeMap) { _changedIdentifiers = changeMap; } public String getID(String oldID) { String newID = _changedIdentifiers.get(oldID); return newID != null ? newID : oldID; } public String getOldID(String newID) { for (String oldID : _changedIdentifiers.keySet()) { if (_changedIdentifiers.get(oldID).equals(newID)) { return oldID; } } return newID; } // called when a user changes a taskID public void add(String oldID, String newID) { // need to handle the case where this id has been updated // more than once between saves _changedIdentifiers.put(getOldID(oldID), newID); } public void saveChanges() { if (! _changedIdentifiers.isEmpty()) { YSpecificationID specID = SpecificationModel.getHandler(). getSpecification().getSpecificationID(); try { if (WorkletClient.getInstance().updateRdrSetTaskIDs(specID, _changedIdentifiers)) { _changedIdentifiers.clear(); } } catch (IOException ignore) { // } } } }
yawlfoundation/editor
source/org/yawlfoundation/yawl/worklet/client/TaskIDChangeMap.java
Java
lgpl-3.0
1,648
package idare.imagenode.internal.GUI.DataSetController; import idare.imagenode.ColorManagement.ColorScalePane; import idare.imagenode.Interfaces.DataSets.DataSet; import idare.imagenode.Interfaces.Layout.DataSetLayoutProperties; import idare.imagenode.internal.GUI.DataSetController.DataSetSelectionModel.ColorPaneBox; import idare.imagenode.internal.GUI.DataSetController.DataSetSelectionModel.ComboBoxRenderer; import javax.swing.JTable; import javax.swing.table.TableCellEditor; import javax.swing.table.TableCellRenderer; /** * A DataSetSelectionTable, that is specific to the {@link DataSetSelectionModel}, using its unique renderers and editors. * @author Thomas Pfau * */ public class DataSetSelectionTable extends JTable { DataSetSelectionModel tablemodel; public DataSetSelectionTable(DataSetSelectionModel mod) { super(mod); tablemodel = mod; } /** * Move the selected entry (we assume single selection) down one row. * If the selected row is already the top row, nothing happens. */ public void moveEntryUp() { int row = getSelectedRow(); if(row > 0) { tablemodel.moveRowUp(row); } getSelectionModel().setSelectionInterval(row-1, row-1); } /** * Move the selected entry (we assume single selection) down one row. * If the selected row is already the last row, nothing happens. */ public void moveEntryDown() { int row = getSelectedRow(); if(row >= 0 & row < getRowCount()-1 ) { tablemodel.moveRowDown(row); } getSelectionModel().setSelectionInterval(row+1, row+1); } @Override public TableCellEditor getCellEditor(int row, int column) { Object value = super.getValueAt(row, column); if(value != null) { // we need very specific Editors for ColorScales and Dataset Properties. if(value instanceof DataSetLayoutProperties) { return tablemodel.getPropertiesEditor(row); } if(value instanceof ColorScalePane) { return tablemodel.getColorScaleEditor(row); } if(value instanceof DataSet) { return tablemodel.getDataSetEditor(row); } return getDefaultEditor(value.getClass()); } return super.getCellEditor(row, column); } @Override public TableCellRenderer getCellRenderer(int row, int column) { Object value = super.getValueAt(row, column); if(value != null) { // we need very specific renderers for ColorScales and Dataset Properties. if(value instanceof ComboBoxRenderer || value instanceof DataSetLayoutProperties) { TableCellRenderer current = tablemodel.getPropertiesRenderer(row); if(current != null) return current; else return super.getCellRenderer(row, column); } if(value instanceof ColorPaneBox|| value instanceof ColorScalePane) { TableCellRenderer current = tablemodel.getColorScaleRenderer(row); if(current != null) return current; else return super.getCellRenderer(row, column); } return getDefaultRenderer(value.getClass()); } return super.getCellRenderer(row, column); } }
sysbiolux/IDARE
METANODE-CREATOR/src/main/java/idare/imagenode/internal/GUI/DataSetController/DataSetSelectionTable.java
Java
lgpl-3.0
3,145
/* Mesquite source code. Copyright 1997-2009 W. Maddison and D. Maddison. Version 2.7, August 2009. Disclaimer: The Mesquite source code is lengthy and we are few. There are no doubt inefficiencies and goofs in this code. The commenting leaves much to be desired. Please approach this source code with the spirit of helping out. Perhaps with your help we can be more than a few, and make Mesquite better. Mesquite is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY. Mesquite's web site is http://mesquiteproject.org This source code and its compiled class files are free and modifiable under the terms of GNU Lesser General Public License. (http://www.gnu.org/copyleft/lesser.html) */ package mesquite.lib; import java.util.*; import java.io.*; import org.dom4j.*; import org.dom4j.io.*; public class XMLUtil { /*.................................................................................................................*/ public static Element addFilledElement(Element containingElement, String name, String content) { if (content == null || name == null) return null; Element element = DocumentHelper.createElement(name); element.addText(content); containingElement.add(element); return element; } /*.................................................................................................................*/ public static Element addFilledElement(Element containingElement, String name, CDATA cdata) { if (cdata == null || name == null) return null; Element element = DocumentHelper.createElement(name); element.add(cdata); containingElement.add(element); return element; } public static String getTextFromElement(Element containingElement, String name){ Element e = containingElement.element(name); if (e == null) return null; else return e.getText(); } /*.................................................................................................................*/ public static String getDocumentAsXMLString(Document doc, boolean escapeText) { try { String encoding = doc.getXMLEncoding(); if (encoding == null) encoding = "UTF-8"; Writer osw = new StringWriter(); OutputFormat opf = new OutputFormat(" ", true, encoding); XMLWriter writer = new XMLWriter(osw, opf); writer.setEscapeText(escapeText); writer.write(doc); writer.close(); return osw.toString(); } catch (IOException e) { MesquiteMessage.warnProgrammer("XML Document could not be returned as string."); } return null; } /*.................................................................................................................*/ public static String getElementAsXMLString(Element doc, String encoding, boolean escapeText) { try { Writer osw = new StringWriter(); OutputFormat opf = new OutputFormat(" ", true, encoding); XMLWriter writer = new XMLWriter(osw, opf); writer.setEscapeText(escapeText); writer.write(doc); writer.close(); return osw.toString(); } catch (IOException e) { MesquiteMessage.warnProgrammer("XML Document could not be returned as string."); } return null; } /*.................................................................................................................*/ public static String getDocumentAsXMLString(Document doc) { return getDocumentAsXMLString(doc,true); } /*.................................................................................................................*/ public static String getDocumentAsXMLString2(Document doc) { try { String encoding = doc.getXMLEncoding(); //if (encoding == null) // encoding = "UTF-8"; Writer osw = new StringWriter(); OutputFormat opf = new OutputFormat(" ", true); XMLWriter writer = new XMLWriter(osw, opf); writer.write(doc); writer.close(); return osw.toString(); } catch (IOException e) { MesquiteMessage.warnProgrammer("XML Document could not be returned as string."); } return null; } /*.................................................................................................................*/ public static Document getDocumentFromString(String rootElementName, String contents) { Document doc = null; try { doc = DocumentHelper.parseText(contents); } catch (Exception e) { return null; } if (doc == null || doc.getRootElement() == null) { return null; } else if (!StringUtil.blank(rootElementName) && !doc.getRootElement().getName().equals(rootElementName)) { return null; } return doc; } /*.................................................................................................................*/ public static Document getDocumentFromString(String contents) { return getDocumentFromString("",contents); } /*.................................................................................................................*/ public static Element getRootXMLElementFromString(String rootElementName, String contents) { Document doc = getDocumentFromString(rootElementName, contents); if (doc==null) return null; return doc.getRootElement(); } /*.................................................................................................................*/ public static Element getRootXMLElementFromString(String contents) { return getRootXMLElementFromString("",contents); } /*.................................................................................................................*/ public static Element getRootXMLElementFromURL(String rootElementName, String url) { SAXReader saxReader = new SAXReader(); Document doc = null; try { doc = saxReader.read(url); } catch (Exception e) { return null; } if (doc == null || doc.getRootElement() == null) { return null; } else if (!StringUtil.blank(rootElementName) && !doc.getRootElement().getName().equals(rootElementName)) { return null; } Element root = doc.getRootElement(); return root; } /*.................................................................................................................*/ public static Element getRootXMLElementFromURL(String url) { return getRootXMLElementFromURL("",url); } /*.................................................................................................................*/ public static void readXMLPreferences(MesquiteModule module, XMLPreferencesProcessor xmlPrefProcessor, String contents) { Element root = getRootXMLElementFromString("mesquite",contents); if (root==null) return; Element element = root.element(module.getXMLModuleName()); if (element != null) { Element versionElement = element.element("version"); if (versionElement == null) return ; else { int version = MesquiteInteger.fromString(element.elementText("version")); boolean acceptableVersion = (module.getXMLPrefsVersion()==version || !module.xmlPrefsVersionMustMatch()); if (acceptableVersion) processPreferencesFromXML(xmlPrefProcessor, element); else return; } } } /*.................................................................................................................*/ public static void processPreferencesFromXML ( XMLPreferencesProcessor xmlPrefProcessor, Element element) { List prefElement = element.elements(); for (Iterator iter = prefElement.iterator(); iter.hasNext();) { // this is going through all of the notices Element messageElement = (Element) iter.next(); xmlPrefProcessor.processSingleXMLPreference(messageElement.getName(), messageElement.getText()); } } }
MesquiteProject/MesquiteArchive
releases/Mesquite2.7/Mesquite Project/Source/mesquite/lib/XMLUtil.java
Java
lgpl-3.0
7,607
/* * XAdES4j - A Java library for generation and verification of XAdES signatures. * Copyright (C) 2010 Luis Goncalves. * * XAdES4j is free software; you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the Free * Software Foundation; either version 3 of the License, or any later version. * * XAdES4j is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License along * with XAdES4j. If not, see <http://www.gnu.org/licenses/>. */ package xades4j.xml.marshalling; import java.util.EnumMap; import java.util.List; import xades4j.properties.IdentifierType; import xades4j.properties.ObjectIdentifier; import xades4j.properties.data.BaseCertRefsData; import xades4j.properties.data.CertRef; import xades4j.xml.bind.xades.XmlCertIDListType; import xades4j.xml.bind.xades.XmlCertIDType; import xades4j.xml.bind.xades.XmlDigestAlgAndValueType; import xades4j.xml.bind.xades.XmlIdentifierType; import xades4j.xml.bind.xades.XmlObjectIdentifierType; import xades4j.xml.bind.xades.XmlQualifierType; import xades4j.xml.bind.xmldsig.XmlDigestMethodType; import xades4j.xml.bind.xmldsig.XmlX509IssuerSerialType; /** * @author Luís */ class ToXmlUtils { ToXmlUtils() { } private static final EnumMap<IdentifierType, XmlQualifierType> identifierTypeConv; static { identifierTypeConv = new EnumMap(IdentifierType.class); identifierTypeConv.put(IdentifierType.OIDAsURI, XmlQualifierType.OID_AS_URI); identifierTypeConv.put(IdentifierType.OIDAsURN, XmlQualifierType.OID_AS_URN); } static XmlObjectIdentifierType getXmlObjectId(ObjectIdentifier objId) { XmlObjectIdentifierType xmlObjId = new XmlObjectIdentifierType(); // Object identifier XmlIdentifierType xmlId = new XmlIdentifierType(); xmlId.setValue(objId.getIdentifier()); // If it is IdentifierType.URI the converter returns null, which is the // same as not specifying a qualifier. xmlId.setQualifier(identifierTypeConv.get(objId.getIdentifierType())); xmlObjId.setIdentifier(xmlId); return xmlObjId; } /**/ static XmlCertIDListType getXmlCertRefList(BaseCertRefsData certRefsData) { XmlCertIDListType xmlCertRefListProp = new XmlCertIDListType(); List<XmlCertIDType> xmlCertRefList = xmlCertRefListProp.getCert(); XmlDigestAlgAndValueType certDigest; XmlDigestMethodType certDigestMethod; XmlX509IssuerSerialType issuerSerial; XmlCertIDType certID; for (CertRef certRef : certRefsData.getCertRefs()) { certDigestMethod = new XmlDigestMethodType(); certDigestMethod.setAlgorithm(certRef.digestAlgUri); certDigest = new XmlDigestAlgAndValueType(); certDigest.setDigestMethod(certDigestMethod); certDigest.setDigestValue(certRef.digestValue); issuerSerial = new XmlX509IssuerSerialType(); issuerSerial.setX509IssuerName(certRef.issuerDN); issuerSerial.setX509SerialNumber(certRef.serialNumber); certID = new XmlCertIDType(); certID.setCertDigest(certDigest); certID.setIssuerSerial(issuerSerial); xmlCertRefList.add(certID); } return xmlCertRefListProp; } }
entaksi/xades4j
src/main/java/xades4j/xml/marshalling/ToXmlUtils.java
Java
lgpl-3.0
3,617
/* * This file is part of RskJ * Copyright (C) 2017 RSK Labs Ltd. * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package co.rsk.core; import com.google.common.primitives.UnsignedBytes; import org.ethereum.rpc.TypeConverter; import org.ethereum.util.ByteUtil; import org.ethereum.vm.DataWord; import java.util.Arrays; import java.util.Comparator; /** * Immutable representation of an RSK address. * It is a simple wrapper on the raw byte[]. * * @author Ariel Mendelzon */ public class RskAddress { /** * This is the size of an RSK address in bytes. */ public static final int LENGTH_IN_BYTES = 20; private static final RskAddress NULL_ADDRESS = new RskAddress(); /** * This compares using the lexicographical order of the sender unsigned bytes. */ public static final Comparator<RskAddress> LEXICOGRAPHICAL_COMPARATOR = Comparator.comparing( RskAddress::getBytes, UnsignedBytes.lexicographicalComparator()); private final byte[] bytes; /** * @param address a data word containing an address in the last 20 bytes. */ public RskAddress(DataWord address) { this(address.getLast20Bytes()); } /** * @param address the hex-encoded 20 bytes long address, with or without 0x prefix. */ public RskAddress(String address) { this(TypeConverter.stringHexToByteArray(address)); } /** * @param bytes the 20 bytes long raw address bytes. */ public RskAddress(byte[] bytes) { if (bytes.length != LENGTH_IN_BYTES) { throw new RuntimeException(String.format("An RSK address must be %d bytes long", LENGTH_IN_BYTES)); } this.bytes = bytes; } /** * This instantiates the contract creation address. */ private RskAddress() { this.bytes = new byte[0]; } /** * @return the null address, which is the receiver of contract creation transactions. */ public static RskAddress nullAddress() { return NULL_ADDRESS; } public byte[] getBytes() { return bytes; } public String toHexString() { return ByteUtil.toHexString(bytes); } @Override public boolean equals(Object other) { if (this == other) { return true; } if (other == null || this.getClass() != other.getClass()) { return false; } RskAddress otherSender = (RskAddress) other; return Arrays.equals(bytes, otherSender.bytes); } @Override public int hashCode() { return Arrays.hashCode(bytes); } /** * @return a DEBUG representation of the address, mainly used for logging. */ @Override public String toString() { return toHexString(); } public String toJsonString() { if (NULL_ADDRESS.equals(this)) { return null; } return TypeConverter.toUnformattedJsonHex(this.getBytes()); } }
rsksmart/rskj
rskj-core/src/main/java/co/rsk/core/RskAddress.java
Java
lgpl-3.0
3,619
/* Galois, a framework to exploit amorphous data-parallelism in irregular programs. Copyright (C) 2010, The University of Texas at Austin. All rights reserved. UNIVERSITY EXPRESSLY DISCLAIMS ANY AND ALL WARRANTIES CONCERNING THIS SOFTWARE AND DOCUMENTATION, INCLUDING ANY WARRANTIES OF MERCHANTABILITY, FITNESS FOR ANY PARTICULAR PURPOSE, NON-INFRINGEMENT AND WARRANTIES OF PERFORMANCE, AND ANY WARRANTY THAT MIGHT OTHERWISE ARISE FROM COURSE OF DEALING OR USAGE OF TRADE. NO WARRANTY IS EITHER EXPRESS OR IMPLIED WITH RESPECT TO THE USE OF THE SOFTWARE OR DOCUMENTATION. Under no circumstances shall University be liable for incidental, special, indirect, direct or consequential damages or loss of profits, interruption of business, or related expenses which may arise from use of Software or Documentation, including but not limited to those resulting from defects in Software and/or Documentation, or loss or inaccuracy of data of any kind. File: GNode.java */ package galois.objects.graph; import galois.objects.GObject; import galois.objects.Lockable; import galois.objects.Mappable; import galois.runtime.Replayable; /** * A node in a graph. * * @param <N> the type of the data stored in each node */ public interface GNode<N> extends Replayable, Lockable, Mappable<GNode<N>>, GObject { /** * Retrieves the node data associated with the vertex * * All the Galois runtime actions (e.g., conflict detection) will be performed when * the method is executed. * * @return the data contained in the node */ public N getData(); /** * Retrieves the node data associated with the vertex. Equivalent to {@link #getData(byte, byte)} * passing <code>flags</code> to both parameters. * * @param flags Galois runtime actions (e.g., conflict detection) that need to be executed * upon invocation of this method. See {@link galois.objects.MethodFlag} * @return the data contained in the node */ public N getData(byte flags); /** * Retrieves the node data associated with the vertex. For convenience, this method * also calls {@link GObject#access(byte)} on the returned data. * * <p>Recall that the * {@link GNode} object maintains information about the vertex and its connectivity * in the graph. This is separate from the data itself. For example, * <code>getData(MethodFlag.NONE, MethodFlag.SAVE_UNDO)</code> * does not acquire an abstract lock on the {@link GNode} (perhaps because * it was returned by a call to {@link GNode#map(util.fn.LambdaVoid)}), but it * saves undo information on the returned data in case the iteration needs to * be rolled back. * </p> * * @param nodeFlags Galois runtime actions (e.g., conflict detection) that need to be executed * upon invocation of this method on the <i>node itself</i>. * See {@link galois.objects.MethodFlag} * @param dataFlags Galois runtime actions (e.g., conflict detection) that need to be executed * upon invocation of this method on the <i>data</i> contained in the node. * See {@link galois.objects.MethodFlag} * @return the data contained in the node */ public N getData(byte nodeFlags, byte dataFlags); /** * Sets the node data. * * All the Galois runtime actions (e.g., conflict detection) will be performed when * the method is executed. * * @param d the data to be stored * @return the old data associated with the node */ public N setData(N d); /** * Sets the node data. * * @param d the data to be stored * @param flags Galois runtime actions (e.g., conflict detection) that need to be executed * upon invocation of this method. See {@link galois.objects.MethodFlag} * @return the old data associated with the node */ public N setData(N d, byte flags); }
chmaruni/SCJ
Shared/libs_src/Galois-2.0/src/galois/objects/graph/GNode.java
Java
lgpl-3.0
3,896
/** * Premium Markets is an automated stock market analysis system. * It implements a graphical environment for monitoring stock markets technical analysis * major indicators, for portfolio management and historical data charting. * In its advanced packaging -not provided under this license- it also includes : * Screening of financial web sites to pick up the best market shares, * Price trend prediction based on stock markets technical analysis and indices rotation, * Back testing, Automated buy sell email notifications on trend signals calculated over * markets and user defined portfolios. * With in mind beating the buy and hold strategy. * Type 'Premium Markets FORECAST' in your favourite search engine for a free workable demo. * * Copyright (C) 2008-2014 Guillaume Thoreton * * This file is part of Premium Markets. * * Premium Markets is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS * FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more * details. * * You should have received a copy of the GNU Lesser General Public License along * with this program. If not, see <http://www.gnu.org/licenses/>. */ package com.finance.pms.events.pounderationrules; import java.util.HashMap; import com.finance.pms.admin.install.logging.MyLogger; import com.finance.pms.datasources.shares.Stock; import com.finance.pms.events.SymbolEvents; import com.finance.pms.events.Validity; public class LatestNoYoYoValidatedPonderationRule extends LatestEventsPonderationRule { private static final long serialVersionUID = 573802685420097964L; private static MyLogger LOGGER = MyLogger.getLogger(LatestNoYoYoValidatedPonderationRule.class); private HashMap<Stock, Validity> tuningValidityList; public LatestNoYoYoValidatedPonderationRule(Integer sellThreshold, Integer buyThreshold, HashMap<Stock, Validity> tuningValidityList) { super(sellThreshold, buyThreshold); this.tuningValidityList = tuningValidityList; } @Override public int compare(SymbolEvents o1, SymbolEvents o2) { SymbolEvents se1 = o1; SymbolEvents se2 = o2; PonderationRule p1 = new LatestNoYoYoValidatedPonderationRule(sellThreshold, buyThreshold, tuningValidityList); PonderationRule p2 = new LatestNoYoYoValidatedPonderationRule(sellThreshold, buyThreshold, tuningValidityList); return compareCal(se1, se2, p1, p2); } @Override public Float finalWeight(SymbolEvents symbolEvents) { Validity validity = tuningValidityList.get(symbolEvents.getStock()); boolean isValid = false; if (validity != null) { isValid = validity.equals(Validity.SUCCESS); } else { LOGGER.warn("No validity information found for " + symbolEvents.getStock() + " while parsing events " + symbolEvents + ". Neural trend was not calculated for that stock."); } if (isValid) { return super.finalWeight(symbolEvents); } else { return 0.0f; } } @Override public Signal initSignal(SymbolEvents symbolEvents) { return new LatestNoYoYoValidatedSignal(symbolEvents.getEventDefList()); } @Override protected void postCondition(Signal signal) { LatestNoYoYoValidatedSignal LVSignal = (LatestNoYoYoValidatedSignal) signal; //Updating cumulative event signal with Bull Bear neural events. switch (LVSignal.getNbTrendChange()) { case 0 : //No event detected break; case 1 : //One Type of Event, no yoyo : weight = sum(cumulative events) + bullish - bearish signal.setSignalWeight(signal.getSignalWeight() + LVSignal.getNbBullish() - LVSignal.getNbBearish()); break; default : //Yoyo, Bull/Bear, we ignore the signal LOGGER.warn("Yo yo trend detected."); break; } } }
premiummarkets/pm
premiumMarkets/pm-core/src/main/java/com/finance/pms/events/pounderationrules/LatestNoYoYoValidatedPonderationRule.java
Java
lgpl-3.0
4,010
/** * * This file is part of Disco. * * Disco is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Disco is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Disco. If not, see <http://www.gnu.org/licenses/>. */ package eu.diversify.disco.cloudml; import eu.diversify.disco.population.diversity.TrueDiversity; import java.util.ArrayList; import java.util.Collections; import java.util.List; public class Options { private static final String JSON_FILE_NAME = "[^\\.]*\\.json$"; private static final String DOUBLE_LITERAL = "((\\+|-)?([0-9]+)(\\.[0-9]+)?)|((\\+|-)?\\.?[0-9]+)"; public static final String ENABLE_GUI = "-gui"; public static Options fromCommandLineArguments(String... arguments) { Options extracted = new Options(); for (String argument : arguments) { if (isJsonFile(argument)) { extracted.addDeploymentModel(argument); } else if (isDouble(argument)) { extracted.setReference(Double.parseDouble(argument)); } else if (isEnableGui(argument)) { extracted.setGuiEnabled(true); } else { throw new IllegalArgumentException("Unknown argument: " + argument); } } return extracted; } private static boolean isJsonFile(String argument) { return argument.matches(JSON_FILE_NAME); } private static boolean isDouble(String argument) { return argument.matches(DOUBLE_LITERAL); } private static boolean isEnableGui(String argument) { return argument.matches(ENABLE_GUI); } private boolean guiEnabled; private final List<String> deploymentModels; private double reference; public Options() { this.guiEnabled = false; this.deploymentModels = new ArrayList<String>(); this.reference = 0.75; } public boolean isGuiEnabled() { return guiEnabled; } public void setGuiEnabled(boolean guiEnabled) { this.guiEnabled = guiEnabled; } public double getReference() { return reference; } public void setReference(double setPoint) { this.reference = setPoint; } public List<String> getDeploymentModels() { return Collections.unmodifiableList(deploymentModels); } public void addDeploymentModel(String pathToModel) { this.deploymentModels.add(pathToModel); } public void launchDiversityController() { final CloudMLController controller = new CloudMLController(new TrueDiversity().normalise()); if (guiEnabled) { startGui(controller); } else { startCommandLine(controller); } } private void startGui(final CloudMLController controller) { java.awt.EventQueue.invokeLater(new Runnable() { @Override public void run() { final Gui gui = new Gui(controller); gui.setReference(reference); gui.setFileToLoad(deploymentModels.get(0)); gui.setVisible(true); } }); } private void startCommandLine(final CloudMLController controller) { final CommandLine commandLine = new CommandLine(controller); for (String deployment : getDeploymentModels()) { commandLine.controlDiversity(deployment, reference); } } }
DIVERSIFY-project/disco
samples/cloudml/controller/src/main/java/eu/diversify/disco/cloudml/Options.java
Java
lgpl-3.0
3,917
/** * */ package com.sirma.itt.emf.authentication.sso.saml.authenticator; import java.nio.charset.StandardCharsets; import java.util.Map; import javax.crypto.SecretKey; import javax.enterprise.inject.Instance; import javax.inject.Inject; import org.apache.commons.codec.binary.Base64; import org.apache.commons.lang3.StringUtils; import org.joda.time.DateTime; import org.joda.time.DateTimeZone; import com.sirma.itt.emf.authentication.sso.saml.SAMLMessageProcessor; import com.sirma.itt.seip.configuration.SystemConfiguration; import com.sirma.itt.seip.idp.config.IDPConfiguration; import com.sirma.itt.seip.plugin.Extension; import com.sirma.itt.seip.security.User; import com.sirma.itt.seip.security.authentication.AuthenticationContext; import com.sirma.itt.seip.security.authentication.Authenticator; import com.sirma.itt.seip.security.configuration.SecurityConfiguration; import com.sirma.itt.seip.security.context.SecurityContext; import com.sirma.itt.seip.security.util.SecurityUtil; import com.sirma.itt.seip.util.EqualsHelper; /** * Th SystemUserAuthenticator is responsible to login system users only using a generated token. * * @author bbanchev */ @Extension(target = Authenticator.NAME, order = 20) public class SystemUserAuthenticator extends BaseSamlAuthenticator { @Inject private Instance<SecurityConfiguration> securityConfiguration; @Inject private IDPConfiguration idpConfiguration; @Inject private SAMLMessageProcessor samlMessageProcessor; @Inject private SystemConfiguration systemConfiguration; @Override public User authenticate(AuthenticationContext authenticationContext) { return null; } @Override public Object authenticate(User toAuthenticate) { return authenticateById(toAuthenticate, toAuthenticate.getIdentityId()); } private Object authenticateById(User toAuthenticate, final String username) { if (StringUtils.isBlank(username)) { return null; } String userSimpleName = SecurityUtil.getUserWithoutTenant(username); if (isSystemUser(userSimpleName) || isSystemAdmin(userSimpleName)) { return authenticateWithTokenAndGetTicket(toAuthenticate, createToken(username, securityConfiguration.get().getCryptoKey().get())); } return null; } @SuppressWarnings("static-method") protected boolean isSystemAdmin(String userSimpleName) { return EqualsHelper.nullSafeEquals(SecurityContext.getSystemAdminName(), userSimpleName, true); } protected boolean isSystemUser(String userSimpleName) { return EqualsHelper.nullSafeEquals(userSimpleName, SecurityUtil.getUserWithoutTenant(SecurityContext.SYSTEM_USER_NAME), true); } @Override protected void completeAuthentication(User authenticated, SAMLTokenInfo info, Map<String, String> processedToken) { authenticated.getProperties().putAll(processedToken); } /** * Creates a token for given user. * * @param user * the user to create for * @param secretKey * is the encrypt key for saml token * @return the saml token */ protected byte[] createToken(String user, SecretKey secretKey) { return Base64.encodeBase64(SecurityUtil.encrypt( createResponse(systemConfiguration.getSystemAccessUrl().getOrFail().toString(), samlMessageProcessor.getIssuerId().get(), idpConfiguration.getIdpServerURL().get(), user), secretKey)); } /** * Creates the response for authentication in DMS. The time should be synchronized * * @param assertionUrl * the alfresco url * @param audianceUrl * the audiance url * @param samlURL * the saml url * @param user * the user to authenticate * @return the resulted saml2 message */ @SuppressWarnings("static-method") protected byte[] createResponse(String assertionUrl, String audianceUrl, String samlURL, String user) { DateTime now = new DateTime(DateTimeZone.UTC); DateTime barrier = now.plusMinutes(10); StringBuilder saml = new StringBuilder(2048); saml.append("<?xml version=\"1.0\" encoding=\"UTF-8\"?>") .append("<saml2p:Response ID=\"inppcpljfhhckioclinjenlcneknojmngnmgklab\" IssueInstant=\"").append(now) .append("\" Version=\"2.0\" xmlns:saml2p=\"urn:oasis:names:tc:SAML:2.0:protocol\">") .append("<saml2p:Status>") .append("<saml2p:StatusCode Value=\"urn:oasis:names:tc:SAML:2.0:status:Success\"/>") .append("</saml2p:Status>") .append("<saml2:Assertion ID=\"ehmifefpmmlichdcpeiogbgcmcbafafckfgnjfnk\" IssueInstant=\"").append(now) .append("\" Version=\"2.0\" xmlns:saml2=\"urn:oasis:names:tc:SAML:2.0:assertion\">") .append("<saml2:Issuer Format=\"urn:oasis:names:tc:SAML:2.0:nameid-format:entity\">").append(samlURL) .append("</saml2:Issuer>").append("<saml2:Subject>").append("<saml2:NameID>").append(user) .append("</saml2:NameID>") .append("<saml2:SubjectConfirmation Method=\"urn:oasis:names:tc:SAML:2.0:cm:bearer\">") .append("<saml2:SubjectConfirmationData InResponseTo=\"0\" NotOnOrAfter=\"").append(barrier) .append("\" Recipient=\"").append(assertionUrl).append("\"/>").append("</saml2:SubjectConfirmation>") .append("</saml2:Subject>").append("<saml2:Conditions NotBefore=\"").append(now) .append("\" NotOnOrAfter=\"").append(barrier).append("\">").append("<saml2:AudienceRestriction>") .append("<saml2:Audience>").append(audianceUrl).append("</saml2:Audience>") .append("</saml2:AudienceRestriction>").append("</saml2:Conditions>") .append("<saml2:AuthnStatement AuthnInstant=\"").append(now).append("\">") .append("<saml2:AuthnContext>") .append("<saml2:AuthnContextClassRef>urn:oasis:names:tc:SAML:2.0:ac:classes:Password</saml2:AuthnContextClassRef>") .append("</saml2:AuthnContext>").append("</saml2:AuthnStatement>").append("</saml2:Assertion>") .append("</saml2p:Response>"); return saml.toString().getBytes(StandardCharsets.UTF_8); } }
SirmaITT/conservation-space-1.7.0
docker/sirma-platform/platform/seip-parent/extensions/emf-sso-saml/src/main/java/com/sirma/itt/emf/authentication/sso/saml/authenticator/SystemUserAuthenticator.java
Java
lgpl-3.0
5,864
/** * DynamicReports - Free Java reporting library for creating reports dynamically * * Copyright (C) 2010 - 2012 Ricardo Mariaca * http://dynamicreports.sourceforge.net * * This file is part of DynamicReports. * * DynamicReports is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * DynamicReports is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with DynamicReports. If not, see <http://www.gnu.org/licenses/>. */ package net.sf.dynamicreports.examples.complex.applicationform; /** * @author Ricardo Mariaca ([email protected]) */ public enum MaritalStatus { SINGLE, MARRIED, DIVORCED }
robcowell/dynamicreports
dynamicreports-examples/src/main/java/net/sf/dynamicreports/examples/complex/applicationform/MaritalStatus.java
Java
lgpl-3.0
1,083
package org.molgenis.lifelines.catalog; import nl.umcg.hl7.service.studydefinition.POQMMT000002UVObservation; import org.molgenis.omx.catalogmanager.OmxCatalogFolder; import org.molgenis.omx.observ.Protocol; public class PoqmObservationCatalogItem extends OmxCatalogFolder { private final POQMMT000002UVObservation observation; public PoqmObservationCatalogItem(POQMMT000002UVObservation observation, Protocol protocol) { super(protocol); if (observation == null) throw new IllegalArgumentException("observation is null"); this.observation = observation; } @Override public String getName() { return observation.getCode().getDisplayName(); } @Override public String getDescription() { return observation.getCode().getOriginalText().getContent().toString(); } @Override public String getCode() { return observation.getCode().getCode(); } @Override public String getCodeSystem() { return observation.getCode().getCodeSystem(); } }
dennishendriksen/molgenis-lifelines
src/main/java/org/molgenis/lifelines/catalog/PoqmObservationCatalogItem.java
Java
lgpl-3.0
972
/* * SonarQube Lua Plugin * Copyright (C) 2016 * mailto:fati.ahmadi AT gmail DOT com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.lua.checks; import org.junit.Test; import org.sonar.lua.LuaAstScanner; import org.sonar.squidbridge.api.SourceFile; import org.sonar.squidbridge.checks.CheckMessagesVerifier; import org.sonar.squidbridge.api.SourceFunction; import java.io.File; public class TableComplexityCheckTest { @Test public void test() { TableComplexityCheck check = new TableComplexityCheck(); check.setMaximumTableComplexityThreshold(0); SourceFile file = LuaAstScanner.scanSingleFile(new File("src/test/resources/checks/tableComplexity.lua"), check); CheckMessagesVerifier.verify(file.getCheckMessages()) .next().atLine(1).withMessage("Table has a complexity of 1 which is greater than 0 authorized.") .noMore(); } }
SonarQubeCommunity/sonar-lua
lua-checks/src/test/java/org/sonar/lua/checks/TableComplexityCheckTest.java
Java
lgpl-3.0
1,600
package com.faralot.core.ui.fragments; import android.app.Activity; import android.app.AlertDialog.Builder; import android.app.Fragment; import android.content.DialogInterface; import android.content.DialogInterface.OnClickListener; import android.content.Intent; import android.os.Bundle; import android.provider.MediaStore.Images.Media; import android.support.v7.app.ActionBar; import android.support.v7.app.AppCompatActivity; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import android.view.ViewGroup.LayoutParams; import android.widget.Button; import android.widget.EditText; import android.widget.ImageButton; import android.widget.ProgressBar; import android.widget.TextView; import com.faralot.core.App; import com.faralot.core.R; import com.faralot.core.R.drawable; import com.faralot.core.R.id; import com.faralot.core.R.layout; import com.faralot.core.R.string; import com.faralot.core.lib.LocalizationSystem; import com.faralot.core.lib.LocalizationSystem.Listener; import com.faralot.core.rest.model.Location; import com.faralot.core.rest.model.location.Coord; import com.faralot.core.ui.holder.LocalizationHolder; import com.faralot.core.utils.Dimension; import com.faralot.core.utils.Localization; import com.faralot.core.utils.Util; import com.orhanobut.dialogplus.DialogPlus; import com.orhanobut.dialogplus.OnItemClickListener; import com.squareup.okhttp.MediaType; import com.squareup.okhttp.RequestBody; import org.osmdroid.bonuspack.overlays.InfoWindow; import org.osmdroid.bonuspack.overlays.MapEventsOverlay; import org.osmdroid.bonuspack.overlays.MapEventsReceiver; import org.osmdroid.util.GeoPoint; import org.osmdroid.views.MapView; import org.osmdroid.views.overlay.ItemizedIconOverlay; import org.osmdroid.views.overlay.OverlayItem; import java.io.File; import java.util.ArrayList; import retrofit.Callback; import retrofit.Response; import retrofit.Retrofit; public class LocationAddSelectFragment extends Fragment { protected MapView mapView; protected TextView latitude; protected ProgressBar latitudeProgress; protected TextView longitude; protected ProgressBar longitudeProgress; protected ImageButton submit; private boolean forceZoom; public LocationAddSelectFragment() { } @Override public final View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(layout.fragment_location_add_select, container, false); initElements(view); ActionBar actionBar = ((AppCompatActivity) getActivity()).getSupportActionBar(); if (actionBar != null) { actionBar.setTitle(getString(string.find_coordinates)); } onChoose(); return view; } private void initElements(View view) { mapView = (MapView) view.findViewById(id.map); latitude = (TextView) view.findViewById(id.result_lat); latitudeProgress = (ProgressBar) view.findViewById(id.progress_latitude); longitude = (TextView) view.findViewById(id.result_lon); longitudeProgress = (ProgressBar) view.findViewById(id.progress_longitude); Button back = (Button) view.findViewById(id.back); back.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { clearResultLayout(); onChoose(); onChoose(); } }); submit = (ImageButton) view.findViewById(id.submit); submit.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { onSubmit(); } }); } private void generateContent(float lat, float lon) { GeoPoint actPosition = new GeoPoint((double) lat, (double) lon); Util.setMapViewSettings(mapView, actPosition, forceZoom); ArrayList<OverlayItem> locations = new ArrayList<>(1); OverlayItem actPositionItem = new OverlayItem(getString(string.here), getString(string.my_position), actPosition); actPositionItem.setMarker(Util.resizeDrawable(getResources() .getDrawable(drawable.ic_marker_dark), getResources(), new Dimension(45, 45))); locations.add(actPositionItem); // Bonuspack MapEventsOverlay mapEventsOverlay = new MapEventsOverlay(getActivity(), new MapEventsReceiver() { @Override public boolean singleTapConfirmedHelper(GeoPoint geoPoint) { InfoWindow.closeAllInfoWindowsOn(mapView); return true; } @Override public boolean longPressHelper(GeoPoint geoPoint) { InfoWindow.closeAllInfoWindowsOn(mapView); setResultLayout((float) geoPoint.getLatitude(), (float) geoPoint .getLongitude()); return true; } }); mapView.getOverlays().add(0, mapEventsOverlay); mapView.getOverlays().add(new ItemizedIconOverlay<>(getActivity(), locations, null)); } protected final void onChoose() { clearResultLayout(); forceZoom = true; ArrayList<Localization> localizations = new ArrayList<>(4); localizations.add(new Localization(drawable.ic_gps_dark, getString(string.gps_coordinates), Localization.GPS)); localizations.add(new Localization(drawable.ic_camera_dark, getString(string.coord_photo_exif), Localization.PIC_COORD)); localizations.add(new Localization(drawable.ic_manual_dark, getString(string.add_manual), Localization.MANUAL)); if (App.palsActive) { localizations.add(new Localization(drawable.ic_pals_dark, getString(string.pals_provider), Localization.PALS)); } DialogPlus dialog = DialogPlus.newDialog(getActivity()) .setAdapter(new LocalizationHolder(getActivity(), localizations)) .setOnItemClickListener(new OnItemClickListener() { @Override public void onItemClick(DialogPlus dialog, Object item, View view, int position) { Listener listener = new Listener() { @Override public void onComplete(Coord coord, boolean valid) { if (valid) { setResultLayout(coord.getLatitude(), coord.getLongitude()); } } }; dialog.dismiss(); if (position == 0) { App.localization.getCoords(LocalizationSystem.GPS, listener); } else if (position == 1) { searchExif(); } else if (position == 2) { searchManual(); } else if (position == 3) { App.localization.getCoords(LocalizationSystem.PALS, listener); } } }) .setContentWidth(LayoutParams.WRAP_CONTENT) .setContentHeight(LayoutParams.WRAP_CONTENT) .create(); dialog.show(); } void searchManual() { Builder alertDialog = new Builder(getActivity()); final View layout = getActivity().getLayoutInflater() .inflate(R.layout.dialog_location_add_manual, null); alertDialog.setView(layout); alertDialog.setPositiveButton(getString(string.confirm), new OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { EditText latitude = (EditText) layout.findViewById(id.latitude); EditText longitude = (EditText) layout.findViewById(id.longitude); setResultLayout(Float.parseFloat(latitude.getText() .toString()), Float.parseFloat(longitude.getText().toString())); } }); alertDialog.show(); } void searchExif() { Intent intent = new Intent(Intent.ACTION_PICK, Media.EXTERNAL_CONTENT_URI); startActivityForResult(intent, 0); } void setResultLayout(float lat, float lon) { if (lat != 0 && lon != 0) { submit.setVisibility(View.VISIBLE); } latitudeProgress.setVisibility(View.GONE); latitude.setText(String.valueOf(lat)); longitudeProgress.setVisibility(View.GONE); longitude.setText(String.valueOf(lon)); generateContent(lat, lon); forceZoom = false; } private void clearResultLayout() { submit.setVisibility(View.GONE); latitudeProgress.setVisibility(View.VISIBLE); latitudeProgress.setIndeterminate(true); latitude.setText(null); longitudeProgress.setVisibility(View.VISIBLE); longitudeProgress.setIndeterminate(true); longitude.setText(null); } protected final void onSubmit() { float lat = Float.parseFloat(latitude.getText().toString()); float lon = Float.parseFloat(longitude.getText().toString()); if (lat != 0 && lon != 0) { Fragment fragment = new LocationAddFragment(); Bundle bundle = new Bundle(); bundle.putFloat(Location.GEOLOCATION_COORD_LATITUDE, lat); bundle.putFloat(Location.GEOLOCATION_COORD_LONGITUDE, lon); fragment.setArguments(bundle); Util.changeFragment(null, fragment, id.frame_container, getActivity(), null); } else { Util.getMessageDialog(getString(string.no_valid_coords), getActivity()); } } /** * Bild wird ausgesucht und uebergeben */ @Override public final void onActivityResult(int requestCode, int resultCode, Intent data) { if (requestCode == 0 && resultCode == Activity.RESULT_OK) { String path = Util.getPathFromCamera(data, getActivity()); if (path != null) { RequestBody typedFile = RequestBody.create(MediaType.parse("image/*"), new File(path)); App.rest.location.getLocationByExif(typedFile).enqueue(new Callback<Coord>() { @Override public void onResponse(Response<Coord> response, Retrofit retrofit) { if (response.isSuccess()) { setResultLayout(response.body().getLatitude(), response .body() .getLongitude()); } else { setResultLayout(0, 0); } } @Override public void onFailure(Throwable t) { Util.getMessageDialog(t.getMessage(), getActivity()); } }); } } } }
bestog/faralot-core
app/src/main/java/com/faralot/core/ui/fragments/LocationAddSelectFragment.java
Java
lgpl-3.0
9,954
package de.riedquat.java.io; import de.riedquat.java.util.Arrays; import org.junit.Test; import java.io.ByteArrayInputStream; import java.io.ByteArrayOutputStream; import java.io.IOException; import static de.riedquat.java.io.Util.copy; import static de.riedquat.java.util.Arrays.EMPTY_BYTE_ARRAY; import static org.junit.Assert.assertArrayEquals; public class UtilTest { @Test public void emptyStream_copiesNothing() throws IOException { assertCopies(EMPTY_BYTE_ARRAY); } @Test public void copiesData() throws IOException { assertCopies(Arrays.createRandomByteArray(10001)); } private void assertCopies(final byte[] testData) throws IOException { final ByteArrayInputStream in = new ByteArrayInputStream(testData); final ByteArrayOutputStream out = new ByteArrayOutputStream(); copy(out, in); assertArrayEquals(testData, out.toByteArray()); } }
christianhujer/japi
WebServer/test/de/riedquat/java/io/UtilTest.java
Java
lgpl-3.0
934
package com.darkona.adventurebackpack.inventory; import com.darkona.adventurebackpack.common.IInventoryAdventureBackpack; import com.darkona.adventurebackpack.init.ModBlocks; import com.darkona.adventurebackpack.item.ItemAdventureBackpack; import com.darkona.adventurebackpack.util.Utils; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; /** * Created by Darkona on 12/10/2014. */ public class SlotBackpack extends SlotAdventureBackpack { public SlotBackpack(IInventoryAdventureBackpack inventory, int id, int x, int y) { super(inventory, id, x, y); } @Override public boolean isItemValid(ItemStack stack) { return (!(stack.getItem() instanceof ItemAdventureBackpack) && !(stack.getItem() == Item.getItemFromBlock(ModBlocks.blockBackpack))); } @Override public void onPickupFromSlot(EntityPlayer p_82870_1_, ItemStack p_82870_2_) { super.onPickupFromSlot(p_82870_1_, p_82870_2_); } }
Mazdallier/AdventureBackpack2
src/main/java/com/darkona/adventurebackpack/inventory/SlotBackpack.java
Java
lgpl-3.0
1,030
package org.alfresco.repo.cmis.ws; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlElementRef; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; /** * <p>Java class for anonymous complex type. * * <p>The following schema fragment specifies the expected content contained within this class. * * <pre> * &lt;complexType> * &lt;complexContent> * &lt;restriction base="{http://www.w3.org/2001/XMLSchema}anyType"> * &lt;sequence> * &lt;element name="repositoryId" type="{http://www.w3.org/2001/XMLSchema}string"/> * &lt;element name="extension" type="{http://docs.oasis-open.org/ns/cmis/messaging/200908/}cmisExtensionType" minOccurs="0"/> * &lt;/sequence> * &lt;/restriction> * &lt;/complexContent> * &lt;/complexType> * </pre> * * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "repositoryId", "extension" }) @XmlRootElement(name = "getRepositoryInfo") public class GetRepositoryInfo { @XmlElement(required = true) protected String repositoryId; @XmlElementRef(name = "extension", namespace = "http://docs.oasis-open.org/ns/cmis/messaging/200908/", type = JAXBElement.class) protected JAXBElement<CmisExtensionType> extension; /** * Gets the value of the repositoryId property. * * @return * possible object is * {@link String } * */ public String getRepositoryId() { return repositoryId; } /** * Sets the value of the repositoryId property. * * @param value * allowed object is * {@link String } * */ public void setRepositoryId(String value) { this.repositoryId = value; } /** * Gets the value of the extension property. * * @return * possible object is * {@link JAXBElement }{@code <}{@link CmisExtensionType }{@code >} * */ public JAXBElement<CmisExtensionType> getExtension() { return extension; } /** * Sets the value of the extension property. * * @param value * allowed object is * {@link JAXBElement }{@code <}{@link CmisExtensionType }{@code >} * */ public void setExtension(JAXBElement<CmisExtensionType> value) { this.extension = ((JAXBElement<CmisExtensionType> ) value); } }
loftuxab/community-edition-old
projects/remote-api/source/generated/org/alfresco/repo/cmis/ws/GetRepositoryInfo.java
Java
lgpl-3.0
2,688
/******************************************************************************* * Copyright (c) 2014 Open Door Logistics (www.opendoorlogistics.com) * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at http://www.gnu.org/licenses/lgpl.txt ******************************************************************************/ package com.opendoorlogistics.core.scripts.execution.dependencyinjection; import java.awt.Dimension; import javax.swing.JPanel; import com.opendoorlogistics.api.HasApi; import com.opendoorlogistics.api.components.ComponentControlLauncherApi.ControlLauncherCallback; import com.opendoorlogistics.api.components.ComponentExecutionApi.ClosedStatusObservable; import com.opendoorlogistics.api.components.ComponentExecutionApi.ModalDialogResult; import com.opendoorlogistics.api.components.ODLComponent; import com.opendoorlogistics.api.components.ProcessingApi; import com.opendoorlogistics.api.distances.DistancesConfiguration; import com.opendoorlogistics.api.distances.ODLCostMatrix; import com.opendoorlogistics.api.geometry.LatLong; import com.opendoorlogistics.api.geometry.ODLGeom; import com.opendoorlogistics.api.tables.ODLDatastore; import com.opendoorlogistics.api.tables.ODLTable; import com.opendoorlogistics.api.tables.ODLTableReadOnly; import com.opendoorlogistics.core.tables.decorators.datastores.dependencies.DataDependencies; public interface DependencyInjector extends ProcessingApi, HasApi { String getBatchKey(); ModalDialogResult showModalPanel(JPanel panel,String title, ModalDialogResult ...buttons); ModalDialogResult showModalPanel(JPanel panel,String title,Dimension minSize, ModalDialogResult ...buttons); <T extends JPanel & ClosedStatusObservable> void showModalPanel(T panel, String title); ODLCostMatrix calculateDistances(DistancesConfiguration request, ODLTableReadOnly... tables); ODLGeom calculateRouteGeom(DistancesConfiguration request, LatLong from, LatLong to); void addInstructionDependencies(String instructionId, DataDependencies dependencies); void submitControlLauncher(String instructionId,ODLComponent component,ODLDatastore<? extends ODLTable> parametersTableCopy, String reportTopLabel,ControlLauncherCallback cb); }
PGWelch/com.opendoorlogistics
com.opendoorlogistics.core/src/com/opendoorlogistics/core/scripts/execution/dependencyinjection/DependencyInjector.java
Java
lgpl-3.0
2,349
package org.energy_home.dal.functions.data; import java.util.Map; import org.osgi.service.dal.FunctionData; public class DoorLockData extends FunctionData { public final static String STATUS_OPEN = "OPEN"; public final static String STATUS_CLOSED = "CLOSED"; private String status; public DoorLockData(long timestamp, Map metadata) { super(timestamp, metadata); } public DoorLockData(long timestamp, Map metadata, String status) { super(timestamp, metadata); this.status = status; } public String getStatus() { return this.status; } public int compareTo(Object o) { return 0; } }
ismb/jemma.osgi.dal.functions.eh
src/main/java/org/energy_home/dal/functions/data/DoorLockData.java
Java
lgpl-3.0
611
/* * Mentawai Web Framework http://mentawai.lohis.com.br/ * Copyright (C) 2005 Sergio Oliveira Jr. ([email protected]) * * This library is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 2.1 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library; if not, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA */ package org.mentawai.filter; import org.mentawai.core.Filter; import org.mentawai.core.InvocationChain; public class GlobalFilterFreeMarkerFilter implements Filter { private final String[] innerActions; public GlobalFilterFreeMarkerFilter() { this.innerActions = null; } public GlobalFilterFreeMarkerFilter(String ... innerActions) { this.innerActions = innerActions; } public boolean isGlobalFilterFree(String innerAction) { if (innerActions == null) return true; if (innerAction == null) return false; // inner actions are specified... for(String s : innerActions) { if (s.equals(innerAction)) return true; } return false; } public String filter(InvocationChain chain) throws Exception { return chain.invoke(); } public void destroy() { } }
tempbottle/mentawai
src/main/java/org/mentawai/filter/GlobalFilterFreeMarkerFilter.java
Java
lgpl-3.0
1,882
package org.osmdroid.bonuspack.utils; import java.io.IOException; import java.io.InputStream; import java.util.List; import org.apache.http.HttpEntity; import org.apache.http.HttpResponse; import org.apache.http.NameValuePair; import org.apache.http.StatusLine; import org.apache.http.client.entity.UrlEncodedFormEntity; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpPost; import org.apache.http.impl.client.DefaultHttpClient; import org.apache.http.params.BasicHttpParams; import org.apache.http.params.HttpConnectionParams; import org.apache.http.params.HttpParams; import org.apache.http.util.EntityUtils; import android.util.Log; /** * A "very very simple to use" class for performing http get and post requests. * So many ways to do that, and potential subtle issues. * If complexity should be added to handle even more issues, complexity should be put here and only here. * * Typical usage: * <pre>HttpConnection connection = new HttpConnection(); * connection.doGet("http://www.google.com"); * InputStream stream = connection.getStream(); * if (stream != null) { * //use this stream, for buffer reading, or XML SAX parsing, or whatever... * } * connection.close();</pre> */ public class HttpConnection { private DefaultHttpClient client; private InputStream stream; private HttpEntity entity; private String mUserAgent; private final static int TIMEOUT_CONNECTION=3000; //ms private final static int TIMEOUT_SOCKET=8000; //ms public HttpConnection(){ stream = null; entity = null; HttpParams httpParameters = new BasicHttpParams(); /* useful? HttpProtocolParams.setContentCharset(httpParameters, "UTF-8"); HttpProtocolParams.setHttpElementCharset(httpParameters, "UTF-8"); */ // Set the timeout in milliseconds until a connection is established. HttpConnectionParams.setConnectionTimeout(httpParameters, TIMEOUT_CONNECTION); // Set the default socket timeout (SO_TIMEOUT) // in milliseconds which is the timeout for waiting for data. HttpConnectionParams.setSoTimeout(httpParameters, TIMEOUT_SOCKET); client = new DefaultHttpClient(httpParameters); //TODO: created here. Reuse to do for better perfs???... } public void setUserAgent(String userAgent){ mUserAgent = userAgent; } /** * @param sUrl url to get */ public void doGet(String sUrl){ try { HttpGet request = new HttpGet(sUrl); if (mUserAgent != null) request.setHeader("User-Agent", mUserAgent); HttpResponse response = client.execute(request); StatusLine status = response.getStatusLine(); if (status.getStatusCode() != 200) { Log.e(BonusPackHelper.LOG_TAG, "Invalid response from server: " + status.toString()); } else { entity = response.getEntity(); } } catch (Exception e){ e.printStackTrace(); } } public void doPost(String sUrl, List<NameValuePair> nameValuePairs) { try { HttpPost request = new HttpPost(sUrl); if (mUserAgent != null) request.setHeader("User-Agent", mUserAgent); request.setEntity(new UrlEncodedFormEntity(nameValuePairs)); HttpResponse response = client.execute(request); StatusLine status = response.getStatusLine(); if (status.getStatusCode() != 200) { Log.e(BonusPackHelper.LOG_TAG, "Invalid response from server: " + status.toString()); } else { entity = response.getEntity(); } } catch (Exception e) { e.printStackTrace(); } } /** * @return the opened InputStream, or null if creation failed for any reason. */ public InputStream getStream() { try { if (entity != null) stream = entity.getContent(); } catch (IOException e) { e.printStackTrace(); } return stream; } /** * @return the whole content as a String, or null if creation failed for any reason. */ public String getContentAsString(){ try { if (entity != null) { return EntityUtils.toString(entity, "UTF-8"); //setting the charset is important if none found in the entity. } else return null; } catch (IOException e) { e.printStackTrace(); return null; } } /** * Calling close once is mandatory. */ public void close(){ if (stream != null){ try { stream.close(); stream = null; } catch (IOException e) { e.printStackTrace(); } } if (entity != null){ try { entity.consumeContent(); //"finish". Important if we want to reuse the client object one day... entity = null; } catch (IOException e) { e.printStackTrace(); } } if (client != null){ client.getConnectionManager().shutdown(); client = null; } } }
pese-git/osmbonuspack
src/main/java/org/osmdroid/bonuspack/utils/HttpConnection.java
Java
lgpl-3.0
4,625
/** * Copyright (C) 2010-2015 Gordon Fraser, Andrea Arcuri and EvoSuite * contributors * * This file is part of EvoSuite. * * EvoSuite is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser Public License as published by the * Free Software Foundation, either version 3.0 of the License, or (at your * option) any later version. * * EvoSuite is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser Public License for more details. * * You should have received a copy of the GNU Lesser Public License along * with EvoSuite. If not, see <http://www.gnu.org/licenses/>. */ package org.evosuite.runtime.mock.java.io; import java.io.File; import java.io.FileFilter; import java.io.FilenameFilter; import java.io.IOException; import java.net.MalformedURLException; import java.net.URI; import java.net.URL; import java.util.ArrayList; import org.evosuite.runtime.RuntimeSettings; import org.evosuite.runtime.mock.MockFramework; import org.evosuite.runtime.mock.OverrideMock; import org.evosuite.runtime.mock.java.lang.MockIllegalArgumentException; import org.evosuite.runtime.mock.java.net.MockURL; import org.evosuite.runtime.vfs.FSObject; import org.evosuite.runtime.vfs.VFile; import org.evosuite.runtime.vfs.VFolder; import org.evosuite.runtime.vfs.VirtualFileSystem; /** * This class is used in the mocking framework to replace File instances. * * <p> * All files are created in memory, and no access to disk is ever done * * @author arcuri * */ public class MockFile extends File implements OverrideMock { private static final long serialVersionUID = -8217763202925800733L; /* * Constructors, with same inputs as in File. Note: it is not possible to inherit JavaDocs for constructors. */ public MockFile(String pathname) { super(pathname); } public MockFile(String parent, String child) { super(parent,child); } public MockFile(File parent, String child) { this(parent.getPath(),child); } public MockFile(URI uri) { super(uri); } /* * TODO: Java 7 * * there is only one method in File that depends on Java 7: * * public Path toPath() * * * but if we include it here, we will break compatibility with Java 6. * Once we drop such backward compatibility, we will need to override * such method */ /* * --------- static methods ------------------ * * recall: it is not possible to override static methods. * In the SUT, all calls to those static methods of File, eg File.foo(), * will need to be replaced with EvoFile.foo() */ public static File[] listRoots() { if(! MockFramework.isEnabled()){ return File.listRoots(); } File[] roots = File.listRoots(); MockFile[] mocks = new MockFile[roots.length]; for(int i=0; i<roots.length; i++){ mocks[i] = new MockFile(roots[i].getAbsolutePath()); } return mocks; } public static File createTempFile(String prefix, String suffix, File directory) throws IOException{ if(! MockFramework.isEnabled()){ return File.createTempFile(prefix, suffix, directory); } VirtualFileSystem.getInstance().throwSimuledIOExceptionIfNeeded(""); String path = VirtualFileSystem.getInstance().createTempFile(prefix, suffix, directory); if(path==null){ throw new MockIOException(); } return new MockFile(path); } public static File createTempFile(String prefix, String suffix) throws IOException { return createTempFile(prefix, suffix, null); } // -------- modified methods ---------------- @Override public int compareTo(File pathname) { if(! MockFramework.isEnabled()){ return super.compareTo(pathname); } return new File(getAbsolutePath()).compareTo(pathname); } @Override public File getParentFile() { if(! MockFramework.isEnabled()){ return super.getParentFile(); } String p = this.getParent(); if (p == null) return null; return new MockFile(p); } @Override public File getAbsoluteFile() { if(! MockFramework.isEnabled()){ return super.getAbsoluteFile(); } String absPath = getAbsolutePath(); return new MockFile(absPath); } @Override public File getCanonicalFile() throws IOException { if(! MockFramework.isEnabled()){ return super.getCanonicalFile(); } String canonPath = getCanonicalPath(); VirtualFileSystem.getInstance().throwSimuledIOExceptionIfNeeded(getAbsolutePath()); return new MockFile(canonPath); } @Override public boolean canRead() { if(! MockFramework.isEnabled()){ return super.canRead(); } FSObject file = VirtualFileSystem.getInstance().findFSObject(getAbsolutePath()); if(file==null){ return false; } return file.isReadPermission(); } @Override public boolean setReadOnly() { if(! MockFramework.isEnabled()){ return super.setReadOnly(); } FSObject file = VirtualFileSystem.getInstance().findFSObject(getAbsolutePath()); if(file==null){ return false; } file.setReadPermission(true); file.setExecutePermission(false); file.setWritePermission(false); return true; } @Override public boolean setReadable(boolean readable, boolean ownerOnly) { if(! MockFramework.isEnabled()){ return super.setReadable(readable, ownerOnly); } FSObject file = VirtualFileSystem.getInstance().findFSObject(getAbsolutePath()); if(file==null){ return false; } file.setReadPermission(readable); return true; } @Override public boolean canWrite() { if(! MockFramework.isEnabled()){ return super.canWrite(); } FSObject file = VirtualFileSystem.getInstance().findFSObject(getAbsolutePath()); if(file==null){ return false; } return file.isWritePermission(); } @Override public boolean setWritable(boolean writable, boolean ownerOnly) { if(! MockFramework.isEnabled()){ return super.setWritable(writable, ownerOnly); } FSObject file = VirtualFileSystem.getInstance().findFSObject(getAbsolutePath()); if(file==null){ return false; } file.setWritePermission(writable); return true; } @Override public boolean setExecutable(boolean executable, boolean ownerOnly) { if(! MockFramework.isEnabled()){ return super.setExecutable(executable, ownerOnly); } FSObject file = VirtualFileSystem.getInstance().findFSObject(getAbsolutePath()); if(file==null){ return false; } file.setExecutePermission(executable); return true; } @Override public boolean canExecute() { if(! MockFramework.isEnabled()){ return super.canExecute(); } FSObject file = VirtualFileSystem.getInstance().findFSObject(getAbsolutePath()); if(file==null){ return false; } return file.isExecutePermission(); } @Override public boolean exists() { if(! MockFramework.isEnabled()){ return super.exists(); } return VirtualFileSystem.getInstance().exists(getAbsolutePath()); } @Override public boolean isDirectory() { if(! MockFramework.isEnabled()){ return super.isDirectory(); } FSObject file = VirtualFileSystem.getInstance().findFSObject(getAbsolutePath()); if(file==null){ return false; } return file.isFolder(); } @Override public boolean isFile() { if(! MockFramework.isEnabled()){ return super.isFile(); } return !isDirectory(); } @Override public boolean isHidden() { if(! MockFramework.isEnabled()){ return super.isHidden(); } if(getName().startsWith(".")){ //this is not necessarily true in Windows return true; } else { return false; } } @Override public boolean setLastModified(long time) { if(! MockFramework.isEnabled()){ return super.setLastModified(time); } if (time < 0){ throw new MockIllegalArgumentException("Negative time"); } FSObject target = VirtualFileSystem.getInstance().findFSObject(getAbsolutePath()); if(target==null){ return false; } return target.setLastModified(time); } @Override public long lastModified() { if(! MockFramework.isEnabled()){ return super.lastModified(); } FSObject target = VirtualFileSystem.getInstance().findFSObject(getAbsolutePath()); if(target==null){ return 0; } return target.getLastModified(); } @Override public long length() { if(! MockFramework.isEnabled()){ return super.length(); } FSObject target = VirtualFileSystem.getInstance().findFSObject(getAbsolutePath()); if(target==null){ return 0; } if(target.isFolder() || target.isDeleted()){ return 0; } VFile file = (VFile) target; return file.getDataSize(); } //following 3 methods are never used in SF110 @Override public long getTotalSpace() { if(! MockFramework.isEnabled()){ return super.getTotalSpace(); } return 0; //TODO } @Override public long getFreeSpace() { if(! MockFramework.isEnabled()){ return super.getFreeSpace(); } return 0; //TODO } @Override public long getUsableSpace() { if(! MockFramework.isEnabled()){ return super.getUsableSpace(); } return 0; //TODO } @Override public boolean createNewFile() throws IOException { if(! MockFramework.isEnabled()){ return super.createNewFile(); } VirtualFileSystem.getInstance().throwSimuledIOExceptionIfNeeded(getAbsolutePath()); return VirtualFileSystem.getInstance().createFile(getAbsolutePath()); } @Override public boolean delete() { if(! MockFramework.isEnabled()){ return super.delete(); } return VirtualFileSystem.getInstance().deleteFSObject(getAbsolutePath()); } @Override public boolean renameTo(File dest) { if(! MockFramework.isEnabled()){ return super.renameTo(dest); } boolean renamed = VirtualFileSystem.getInstance().rename( this.getAbsolutePath(), dest.getAbsolutePath()); return renamed; } @Override public boolean mkdir() { if(! MockFramework.isEnabled()){ return super.mkdir(); } String parent = this.getParent(); if(parent==null || !VirtualFileSystem.getInstance().exists(parent)){ return false; } return VirtualFileSystem.getInstance().createFolder(getAbsolutePath()); } @Override public void deleteOnExit() { if(! MockFramework.isEnabled()){ super.deleteOnExit(); } /* * do nothing, as anyway no actual file is created */ } @Override public String[] list() { if(! MockFramework.isEnabled()){ return super.list(); } if(!isDirectory() || !exists()){ return null; } else { VFolder dir = (VFolder) VirtualFileSystem.getInstance().findFSObject(getAbsolutePath()); return dir.getChildrenNames(); } } @Override public File[] listFiles() { if(! MockFramework.isEnabled()){ return super.listFiles(); } String[] ss = list(); if (ss == null) return null; int n = ss.length; MockFile[] fs = new MockFile[n]; for (int i = 0; i < n; i++) { fs[i] = new MockFile(this,ss[i]); } return fs; } @Override public File[] listFiles(FileFilter filter) { if(! MockFramework.isEnabled()){ return super.listFiles(filter); } String ss[] = list(); if (ss == null) return null; ArrayList<File> files = new ArrayList<File>(); for (String s : ss) { File f = new MockFile(this,s); if ((filter == null) || filter.accept(f)) files.add(f); } return files.toArray(new File[files.size()]); } @Override public String getCanonicalPath() throws IOException { if(! MockFramework.isEnabled()){ return super.getCanonicalPath(); } VirtualFileSystem.getInstance().throwSimuledIOExceptionIfNeeded(getAbsolutePath()); return super.getCanonicalPath(); } @Override public URL toURL() throws MalformedURLException { if(! MockFramework.isEnabled() || !RuntimeSettings.useVNET){ return super.toURL(); } URL url = super.toURL(); return MockURL.URL(url.toString()); } // -------- unmodified methods -------------- @Override public String getName(){ return super.getName(); } @Override public String getParent() { return super.getParent(); } @Override public String getPath() { return super.getPath(); } @Override public boolean isAbsolute() { return super.isAbsolute(); } @Override public String getAbsolutePath() { return super.getAbsolutePath(); } @Override public URI toURI() { return super.toURI(); //no need of VNET here } @Override public String[] list(FilenameFilter filter) { //no need to mock it, as it uses the mocked list() return super.list(filter); } @Override public boolean mkdirs() { //no need to mock it, as all methods it calls are mocked return super.mkdirs(); } @Override public boolean setWritable(boolean writable) { return super.setWritable(writable); // it calls mocked method } @Override public boolean setReadable(boolean readable) { return super.setReadable(readable); //it calls mocked method } @Override public boolean setExecutable(boolean executable) { return super.setExecutable(executable); // it calls mocked method } // ------- Object methods ----------- @Override public boolean equals(Object obj) { return super.equals(obj); } @Override public int hashCode() { return super.hashCode(); } @Override public String toString() { return super.toString(); } }
SoftwareEngineeringToolDemos/FSE-2011-EvoSuite
runtime/src/main/java/org/evosuite/runtime/mock/java/io/MockFile.java
Java
lgpl-3.0
13,402
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package optas.gui.wizard; /** * * @author chris */ public class ComponentWrapper { public String componentName; public String componentContext; public boolean contextComponent; public ComponentWrapper(String componentName, String componentContext, boolean contextComponent) { this.componentContext = componentContext; this.componentName = componentName; this.contextComponent = contextComponent; } @Override public String toString() { if (contextComponent) { return componentName; } return /*componentContext + "." + */ componentName; } }
kralisch/jams
JAMSOptas/src/optas/gui/wizard/ComponentWrapper.java
Java
lgpl-3.0
738
package org.jta.testspringhateoas.hello; import org.springframework.http.HttpEntity; import org.springframework.http.HttpStatus; import org.springframework.http.ResponseEntity; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import static org.springframework.hateoas.mvc.ControllerLinkBuilder.*; @RestController public class GreetingController { private static final String TEMPLATE = "Hello, %s!"; @RequestMapping("/greeting") public HttpEntity<Greeting> greeting( @RequestParam(value = "name", required = false, defaultValue = "World") String name) { Greeting greeting = new Greeting(String.format(TEMPLATE, name)); greeting.add(linkTo(methodOn(GreetingController.class).greeting(name)).withSelfRel()); return new ResponseEntity<Greeting>(greeting, HttpStatus.OK); } }
javiertoja/SpringBoot
testSpringHateoas/src/main/java/org/jta/testspringhateoas/hello/GreetingController.java
Java
lgpl-3.0
970
/** * Copyright (C) 2013-2014 Kametic <[email protected]> * * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE, Version 3, 29 June 2007; * or any later version * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.gnu.org/licenses/lgpl-3.0.txt * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.nuun.kernel.core.internal; import static io.nuun.kernel.core.NuunCore.createKernel; import static io.nuun.kernel.core.NuunCore.newKernelConfiguration; import static org.fest.assertions.Assertions.assertThat; import io.nuun.kernel.api.Kernel; import io.nuun.kernel.core.pluginsit.dummy1.DummyPlugin; import io.nuun.kernel.core.pluginsit.dummy23.DummyPlugin2; import io.nuun.kernel.core.pluginsit.dummy23.DummyPlugin3; import io.nuun.kernel.core.pluginsit.dummy4.DummyPlugin4; import io.nuun.kernel.core.pluginsit.dummy5.DummyPlugin5; import java.util.concurrent.CountDownLatch; import org.junit.Test; public class KernelMulticoreTest { @Test public void dependee_plugins_that_misses_should_be_source_of_error() throws InterruptedException { CountDownLatch startLatch = new CountDownLatch(1); for (int threadNo = 0; threadNo < 2; threadNo++) { Thread t = new KernelHolder(startLatch); t.start(); } // give the threads chance to start up; we could perform // initialisation code here as well. Thread.sleep(200); startLatch.countDown(); } static class KernelHolder extends Thread { public KernelHolder(CountDownLatch startLatch) { } @SuppressWarnings("unchecked") @Override public void run() { // try { System.out.println("Before"); // startLatch.await(); KernelCore underTest; DummyPlugin4 plugin4 = new DummyPlugin4(); underTest = (KernelCore) createKernel( // newKernelConfiguration() // .params ( DummyPlugin.ALIAS_DUMMY_PLUGIN1 , "WAZAAAA", DummyPlugin.NUUNROOTALIAS , "internal,"+KernelCoreTest.class.getPackage().getName() ) ); assertThat(underTest.name()).startsWith(Kernel.KERNEL_PREFIX_NAME); System.out.println(">" + underTest.name()); underTest.addPlugins( DummyPlugin2.class); underTest.addPlugins( DummyPlugin3.class); underTest.addPlugins( plugin4); underTest.addPlugins( DummyPlugin5.class); underTest.init(); assertThat(underTest.isInitialized()).isTrue(); System.out.println(">" + underTest.name() + " initialized = " + underTest.isInitialized()); underTest.start(); assertThat(underTest.isStarted()).isTrue(); System.out.println(">" + underTest.name() + " started = " + underTest.isStarted()); underTest.stop(); } // catch (InterruptedException e) // { // e.printStackTrace(); // } } } }
adrienlauer/kernel
core/src/test/java/io/nuun/kernel/core/internal/KernelMulticoreTest.java
Java
lgpl-3.0
3,859
/* * This file is part of RskJ * Copyright (C) 2019 RSK Labs Ltd. * (derived from ethereumJ library, Copyright (c) 2016 <ether.camp>) * * This program is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package co.rsk.pcc.blockheader; import co.rsk.pcc.ExecutionEnvironment; import org.ethereum.core.Block; import org.ethereum.core.CallTransaction; /** * This implements the "getCoinbaseAddress" method * that belongs to the BlockHeaderContract native contract. * * @author Diego Masini */ public class GetCoinbaseAddress extends BlockHeaderContractMethod { private final CallTransaction.Function function = CallTransaction.Function.fromSignature( "getCoinbaseAddress", new String[]{"int256"}, new String[]{"bytes"} ); public GetCoinbaseAddress(ExecutionEnvironment executionEnvironment, BlockAccessor blockAccessor) { super(executionEnvironment, blockAccessor); } @Override public CallTransaction.Function getFunction() { return function; } @Override protected Object internalExecute(Block block, Object[] arguments) { return block.getCoinbase().getBytes(); } }
rsksmart/rskj
rskj-core/src/main/java/co/rsk/pcc/blockheader/GetCoinbaseAddress.java
Java
lgpl-3.0
1,780
/** * Copyright (C) 2010-2017 Gordon Fraser, Andrea Arcuri and EvoSuite * contributors * * This file is part of EvoSuite. * * EvoSuite is free software: you can redistribute it and/or modify it * under the terms of the GNU Lesser General Public License as published * by the Free Software Foundation, either version 3.0 of the License, or * (at your option) any later version. * * EvoSuite is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with EvoSuite. If not, see <http://www.gnu.org/licenses/>. */ package org.evosuite.symbolic.vm; import org.evosuite.symbolic.expr.fp.RealValue; /** * * @author galeotti * */ public final class Fp64Operand implements DoubleWordOperand, RealOperand { private final RealValue realExpr; public Fp64Operand(RealValue realExpr) { this.realExpr = realExpr; } public RealValue getRealExpression() { return realExpr; } @Override public String toString() { return realExpr.toString(); } }
sefaakca/EvoSuite-Sefa
client/src/main/java/org/evosuite/symbolic/vm/Fp64Operand.java
Java
lgpl-3.0
1,222
/* * #%L * Alfresco Repository * %% * Copyright (C) 2005 - 2016 Alfresco Software Limited * %% * This file is part of the Alfresco software. * If the software was purchased under a paid Alfresco license, the terms of * the paid license agreement will prevail. Otherwise, the software is * provided under the following open source license terms: * * Alfresco is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * Alfresco is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with Alfresco. If not, see <http://www.gnu.org/licenses/>. * #L% */ package org.alfresco.util.schemacomp.model; import static org.junit.Assert.*; import static org.mockito.Mockito.verify; import org.alfresco.test_category.BaseSpringTestsCategory; import org.alfresco.test_category.OwnJVMTestsCategory; import org.alfresco.util.schemacomp.DbProperty; import org.junit.Before; import org.junit.Test; import org.junit.experimental.categories.Category; import org.junit.runner.RunWith; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; /** * Tests for the Schema class. * * @author Matt Ward */ @RunWith(MockitoJUnitRunner.class) @Category(BaseSpringTestsCategory.class) public class SchemaTest extends DbObjectTestBase<Schema> { private Schema left; private Schema right; @Before public void setUp() { left = new Schema("left_schema"); right = new Schema("right_schema"); } @Override protected Schema getThisObject() { return left; } @Override protected Schema getThatObject() { return right; } @Override protected void doDiffTests() { // We need to be warned if comparing, for example a version 500 schema with a // version 501 schema. inOrder.verify(comparisonUtils).compareSimple( new DbProperty(left, "version"), new DbProperty(right, "version"), ctx); // In addition to the base class functionality, Schema.diff() compares // the DbObjects held in the other schema with its own DbObjects. inOrder.verify(comparisonUtils).compareCollections(left.objects, right.objects, ctx); } @Test public void acceptVisitor() { DbObject dbo1 = Mockito.mock(DbObject.class); left.add(dbo1); DbObject dbo2 = Mockito.mock(DbObject.class); left.add(dbo2); DbObject dbo3 = Mockito.mock(DbObject.class); left.add(dbo3); left.accept(visitor); verify(dbo1).accept(visitor); verify(dbo2).accept(visitor); verify(dbo3).accept(visitor); verify(visitor).visit(left); } @Test public void sameAs() { // We have to assume that two schemas are always the same, regardless of name, // otherwise unless the reference schema has the same name as the target database // all the comparisons will fail - and users can choose to install databases with any schema // name they choose. assertTrue("Schemas should be considered the same", left.sameAs(right)); // Things are always the same as themselves. assertTrue("Schemas are the same physical object", left.sameAs(left)); assertFalse("A table is not the same as a schema", left.sameAs(new Table("left_schema"))); assertFalse("null is not the same as a schema", left.sameAs(null)); } }
Alfresco/alfresco-repository
src/test/java/org/alfresco/util/schemacomp/model/SchemaTest.java
Java
lgpl-3.0
4,062
package org.toughradius.handler; public interface RadiusConstant { public final static String VENDOR_TOUGHSOCKS = "18168"; public final static String VENDOR_MIKROTIK = "14988"; public final static String VENDOR_IKUAI = "10055"; public final static String VENDOR_HUAWEI = "2011"; public final static String VENDOR_ZTE = "3902"; public final static String VENDOR_H3C = "25506"; public final static String VENDOR_RADBACK = "2352"; public final static String VENDOR_CISCO = "9"; }
talkincode/ToughRADIUS
src/main/java/org/toughradius/handler/RadiusConstant.java
Java
lgpl-3.0
512
/* * Copyright 2017 Crown Copyright * * This file is part of Stroom-Stats. * * Stroom-Stats 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. * * Stroom-Stats 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 Stroom-Stats. If not, see <http://www.gnu.org/licenses/>. */ package stroom.stats.configuration; import org.ehcache.spi.loaderwriter.CacheLoaderWriter; import org.hibernate.Session; import org.hibernate.SessionFactory; import org.hibernate.context.internal.ManagedSessionContext; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.inject.Inject; import java.util.Map; public class StatisticConfigurationCacheByUuidLoaderWriter implements CacheLoaderWriter<String,StatisticConfiguration>{ private static final Logger LOGGER = LoggerFactory.getLogger(StatisticConfigurationCacheByUuidLoaderWriter.class); private final StroomStatsStoreEntityDAO stroomStatsStoreEntityDAO; private final SessionFactory sessionFactory; @Inject public StatisticConfigurationCacheByUuidLoaderWriter(final StroomStatsStoreEntityDAO stroomStatsStoreEntityDAO, final SessionFactory sessionFactory) { this.stroomStatsStoreEntityDAO = stroomStatsStoreEntityDAO; this.sessionFactory = sessionFactory; } @Override public StatisticConfiguration load(final String key) throws Exception { LOGGER.trace("load called for key {}", key); //EHCache doesn't cache null values so if we can't find a stat config for this uuid, //just return null try (Session session = sessionFactory.openSession()) { ManagedSessionContext.bind(session); session.beginTransaction(); StatisticConfiguration statisticConfiguration = stroomStatsStoreEntityDAO.loadByUuid(key).orElse(null); LOGGER.trace("Returning statisticConfiguration {}", statisticConfiguration); return statisticConfiguration; } catch (Exception e) { throw new RuntimeException(String.format("Error loading stat store entity by uuid %s", key), e); } } @Override public Map<String, StatisticConfiguration> loadAll(final Iterable<? extends String> keys) throws Exception { throw new UnsupportedOperationException("loadAll (getAll) is not currently supported on this cache"); } @Override public void write(final String key, final StatisticConfiguration value) throws Exception { throw new UnsupportedOperationException("CRUD operations are not currently supported on this cache"); } @Override public void writeAll(final Iterable<? extends Map.Entry<? extends String, ? extends StatisticConfiguration>> entries) throws Exception { throw new UnsupportedOperationException("CRUD operations are not currently supported on this cache"); } @Override public void delete(final String key) throws Exception { throw new UnsupportedOperationException("CRUD operations are not currently supported on this cache"); } @Override public void deleteAll(final Iterable<? extends String> keys) throws Exception { throw new UnsupportedOperationException("CRUD operations are not currently supported on this cache"); } }
gchq/stroom-stats
stroom-stats-service/src/main/java/stroom/stats/configuration/StatisticConfigurationCacheByUuidLoaderWriter.java
Java
lgpl-3.0
3,752
/* * Copyright (C) 2015-2016 Didier Villevalois. * * This file is part of JLaTo. * * JLaTo is free software: you can redistribute it and/or modify it under * the terms of the GNU Lesser General Public License as published by the * Free Software Foundation, either version 3 of the License, or (at your * option) any later version. * * JLaTo is distributed in the hope that it will be useful, but WITHOUT * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or * FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public * License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with JLaTo. If not, see <http://www.gnu.org/licenses/>. */ package org.jlato.internal.td.decl; import org.jlato.internal.bu.coll.SNodeList; import org.jlato.internal.bu.decl.SAnnotationDecl; import org.jlato.internal.bu.name.SName; import org.jlato.internal.td.TDLocation; import org.jlato.internal.td.TDTree; import org.jlato.tree.Kind; import org.jlato.tree.NodeList; import org.jlato.tree.Trees; import org.jlato.tree.decl.AnnotationDecl; import org.jlato.tree.decl.ExtendedModifier; import org.jlato.tree.decl.MemberDecl; import org.jlato.tree.decl.TypeDecl; import org.jlato.tree.name.Name; import org.jlato.util.Mutation; /** * An annotation type declaration. */ public class TDAnnotationDecl extends TDTree<SAnnotationDecl, TypeDecl, AnnotationDecl> implements AnnotationDecl { /** * Returns the kind of this annotation type declaration. * * @return the kind of this annotation type declaration. */ public Kind kind() { return Kind.AnnotationDecl; } /** * Creates an annotation type declaration for the specified tree location. * * @param location the tree location. */ public TDAnnotationDecl(TDLocation<SAnnotationDecl> location) { super(location); } /** * Creates an annotation type declaration with the specified child trees. * * @param modifiers the modifiers child tree. * @param name the name child tree. * @param members the members child tree. */ public TDAnnotationDecl(NodeList<ExtendedModifier> modifiers, Name name, NodeList<MemberDecl> members) { super(new TDLocation<SAnnotationDecl>(SAnnotationDecl.make(TDTree.<SNodeList>treeOf(modifiers), TDTree.<SName>treeOf(name), TDTree.<SNodeList>treeOf(members)))); } /** * Returns the modifiers of this annotation type declaration. * * @return the modifiers of this annotation type declaration. */ public NodeList<ExtendedModifier> modifiers() { return location.safeTraversal(SAnnotationDecl.MODIFIERS); } /** * Replaces the modifiers of this annotation type declaration. * * @param modifiers the replacement for the modifiers of this annotation type declaration. * @return the resulting mutated annotation type declaration. */ public AnnotationDecl withModifiers(NodeList<ExtendedModifier> modifiers) { return location.safeTraversalReplace(SAnnotationDecl.MODIFIERS, modifiers); } /** * Mutates the modifiers of this annotation type declaration. * * @param mutation the mutation to apply to the modifiers of this annotation type declaration. * @return the resulting mutated annotation type declaration. */ public AnnotationDecl withModifiers(Mutation<NodeList<ExtendedModifier>> mutation) { return location.safeTraversalMutate(SAnnotationDecl.MODIFIERS, mutation); } /** * Returns the name of this annotation type declaration. * * @return the name of this annotation type declaration. */ public Name name() { return location.safeTraversal(SAnnotationDecl.NAME); } /** * Replaces the name of this annotation type declaration. * * @param name the replacement for the name of this annotation type declaration. * @return the resulting mutated annotation type declaration. */ public AnnotationDecl withName(Name name) { return location.safeTraversalReplace(SAnnotationDecl.NAME, name); } /** * Mutates the name of this annotation type declaration. * * @param mutation the mutation to apply to the name of this annotation type declaration. * @return the resulting mutated annotation type declaration. */ public AnnotationDecl withName(Mutation<Name> mutation) { return location.safeTraversalMutate(SAnnotationDecl.NAME, mutation); } /** * Replaces the name of this annotation type declaration. * * @param name the replacement for the name of this annotation type declaration. * @return the resulting mutated annotation type declaration. */ public AnnotationDecl withName(String name) { return location.safeTraversalReplace(SAnnotationDecl.NAME, Trees.name(name)); } /** * Returns the members of this annotation type declaration. * * @return the members of this annotation type declaration. */ public NodeList<MemberDecl> members() { return location.safeTraversal(SAnnotationDecl.MEMBERS); } /** * Replaces the members of this annotation type declaration. * * @param members the replacement for the members of this annotation type declaration. * @return the resulting mutated annotation type declaration. */ public AnnotationDecl withMembers(NodeList<MemberDecl> members) { return location.safeTraversalReplace(SAnnotationDecl.MEMBERS, members); } /** * Mutates the members of this annotation type declaration. * * @param mutation the mutation to apply to the members of this annotation type declaration. * @return the resulting mutated annotation type declaration. */ public AnnotationDecl withMembers(Mutation<NodeList<MemberDecl>> mutation) { return location.safeTraversalMutate(SAnnotationDecl.MEMBERS, mutation); } }
ptitjes/jlato
src/main/java/org/jlato/internal/td/decl/TDAnnotationDecl.java
Java
lgpl-3.0
5,671
package org.orchestra.sm; import java.io.BufferedReader; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.util.ArrayList; import java.util.List; import java.util.Map; import java.util.Map.Entry; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Runner { private final Logger logger = LoggerFactory.getLogger(Runner.class); private List<String> command = new ArrayList<String>(); private Map<String, String> env; private String workDir; private Process process; public Map<String, String> getEnv() { return env; } public void setEnv(Map<String, String> env) { this.env = env; } public Runner(String command, List<String> args) { this.command.add(command); if(args != null) this.command.addAll(args); } public Runner(String command, List<String> args, Map<String, String> env) { this.command.add(command); if(args != null) this.command.addAll(args); this.env = env; } public Runner(String command, List<String> args, Map<String, String> env, String workDir) { this.command.add(command); if(args != null) this.command.addAll(args); this.env = env; this.workDir = workDir; } public int run(String arg) throws IOException, InterruptedException { List<String> cmd = new ArrayList<String>(command); if(arg != null) cmd.add(arg); new StringBuffer(); ProcessBuilder pb = new ProcessBuilder(cmd); if(env != null) pb.environment().putAll(env); if(workDir != null) pb.directory(new File(workDir)); logger.debug("Environment variables:"); for(Entry<String, String> e : pb.environment().entrySet()) { logger.debug(e.getKey() + "=" + e.getValue()); } process = pb.start(); return process.waitFor(); } public InputStream getInputStream() { return process.getInputStream(); } public BufferedReader getSystemOut() { BufferedReader input = new BufferedReader(new InputStreamReader(process.getInputStream())); return input; } public BufferedReader getSystemError() { BufferedReader error = new BufferedReader(new InputStreamReader(process.getErrorStream())); return error; } public void setStandardInput(String filename) { } }
bigorc/orchestra
src/main/java/org/orchestra/sm/Runner.java
Java
lgpl-3.0
2,212
package org.datacleaner.kettle.ui; import java.util.ArrayList; import java.util.List; import org.eclipse.swt.SWT; import org.eclipse.swt.events.DisposeEvent; import org.eclipse.swt.events.DisposeListener; import org.eclipse.swt.graphics.Image; import org.eclipse.swt.graphics.Point; import org.eclipse.swt.graphics.Rectangle; import org.eclipse.swt.layout.FormAttachment; import org.eclipse.swt.layout.FormData; import org.eclipse.swt.layout.FormLayout; import org.eclipse.swt.layout.GridLayout; import org.eclipse.swt.widgets.Button; import org.eclipse.swt.widgets.Display; import org.eclipse.swt.widgets.Event; import org.eclipse.swt.widgets.Group; import org.eclipse.swt.widgets.Label; import org.eclipse.swt.widgets.Listener; import org.eclipse.swt.widgets.MessageBox; import org.eclipse.swt.widgets.Shell; import org.eclipse.swt.widgets.Text; import org.pentaho.di.core.Const; import org.pentaho.di.core.plugins.JobEntryPluginType; import org.pentaho.di.core.plugins.PluginRegistry; import org.pentaho.di.job.JobMeta; import org.pentaho.di.job.entry.JobEntryDialogInterface; import org.pentaho.di.job.entry.JobEntryInterface; import org.pentaho.di.repository.Repository; import org.pentaho.di.ui.core.gui.GUIResource; import org.pentaho.di.ui.job.entry.JobEntryDialog; import org.pentaho.di.ui.trans.step.BaseStepDialog; import plugin.DataCleanerJobEntry; public abstract class AbstractJobEntryDialog extends JobEntryDialog implements JobEntryDialogInterface, DisposeListener { private final String initialJobName; private Text jobNameField; private Button okButton; private Button cancelButton; private List<Object> resources = new ArrayList<Object>(); public AbstractJobEntryDialog(Shell parent, JobEntryInterface jobEntry, Repository rep, JobMeta jobMeta) { super(parent, jobEntry, rep, jobMeta); initialJobName = (jobEntry.getName() == null ? DataCleanerJobEntry.NAME : jobEntry.getName()); } protected void initializeShell(Shell shell) { String id = PluginRegistry.getInstance().getPluginId(JobEntryPluginType.class, jobMeta); if (id != null) { shell.setImage(GUIResource.getInstance().getImagesStepsSmall().get(id)); } } /** * @wbp.parser.entryPoint */ @Override public final JobEntryInterface open() { final Shell parent = getParent(); final Display display = parent.getDisplay(); // initialize shell { shell = new Shell(parent, SWT.DIALOG_TRIM | SWT.RESIZE | SWT.MIN | SWT.MAX); initializeShell(shell); FormLayout shellLayout = new FormLayout(); shellLayout.marginTop = 0; shellLayout.marginLeft = 0; shellLayout.marginRight = 0; shellLayout.marginBottom = 0; shellLayout.marginWidth = 0; shellLayout.marginHeight = 0; shell.setLayout(shellLayout); shell.setText(DataCleanerJobEntry.NAME + ": " + initialJobName); } final int middle = Const.MIDDLE_PCT; final int margin = Const.MARGIN; // DC banner final DataCleanerBanner banner = new DataCleanerBanner(shell); { final FormData bannerLayoutData = new FormData(); bannerLayoutData.left = new FormAttachment(0, 0); bannerLayoutData.right = new FormAttachment(100, 0); bannerLayoutData.top = new FormAttachment(0, 0); banner.setLayoutData(bannerLayoutData); } // Step name { final Label stepNameLabel = new Label(shell, SWT.RIGHT); stepNameLabel.setText("Step name:"); final FormData stepNameLabelLayoutData = new FormData(); stepNameLabelLayoutData.left = new FormAttachment(0, margin); stepNameLabelLayoutData.right = new FormAttachment(middle, -margin); stepNameLabelLayoutData.top = new FormAttachment(banner, margin * 2); stepNameLabel.setLayoutData(stepNameLabelLayoutData); jobNameField = new Text(shell, SWT.SINGLE | SWT.LEFT | SWT.BORDER); jobNameField.setText(initialJobName); final FormData stepNameFieldLayoutData = new FormData(); stepNameFieldLayoutData.left = new FormAttachment(middle, 0); stepNameFieldLayoutData.right = new FormAttachment(100, -margin); stepNameFieldLayoutData.top = new FormAttachment(banner, margin * 2); jobNameField.setLayoutData(stepNameFieldLayoutData); } // Properties Group final Group propertiesGroup = new Group(shell, SWT.SHADOW_ETCHED_IN); propertiesGroup.setText("Step configuration"); final FormData propertiesGroupLayoutData = new FormData(); propertiesGroupLayoutData.left = new FormAttachment(0, margin); propertiesGroupLayoutData.right = new FormAttachment(100, -margin); propertiesGroupLayoutData.top = new FormAttachment(jobNameField, margin); propertiesGroup.setLayoutData(propertiesGroupLayoutData); final GridLayout propertiesGroupLayout = new GridLayout(2, false); propertiesGroup.setLayout(propertiesGroupLayout); addConfigurationFields(propertiesGroup, margin, middle); okButton = new Button(shell, SWT.PUSH); Image saveImage = new Image(shell.getDisplay(), AbstractJobEntryDialog.class.getResourceAsStream("save.png")); resources.add(saveImage); okButton.setImage(saveImage); okButton.setText("OK"); okButton.addListener(SWT.Selection, new Listener() { @Override public void handleEvent(Event event) { ok(); final String jobEntryName = jobNameField.getText(); if (jobEntryName != null && jobEntryName.length() > 0 && !initialJobName.equals(jobEntryName)) { jobEntryInt.setName(jobEntryName); } jobEntryInt.setChanged(); shell.close(); } }); cancelButton = new Button(shell, SWT.PUSH); Image cancelImage = new Image(shell.getDisplay(), AbstractJobEntryDialog.class.getResourceAsStream("cancel.png")); resources.add(cancelImage); cancelButton.setImage(cancelImage); cancelButton.setText("Cancel"); cancelButton.addListener(SWT.Selection, new Listener() { @Override public void handleEvent(Event arg0) { cancel(); jobNameField.setText(""); shell.close(); } }); BaseStepDialog.positionBottomButtons(shell, new Button[] { okButton, cancelButton }, margin, propertiesGroup); // HI banner final DataCleanerFooter footer = new DataCleanerFooter(shell); { final FormData footerLayoutData = new FormData(); footerLayoutData.left = new FormAttachment(0, 0); footerLayoutData.right = new FormAttachment(100, 0); footerLayoutData.top = new FormAttachment(okButton, margin * 2); footer.setLayoutData(footerLayoutData); } shell.addDisposeListener(this); shell.setSize(getDialogSize()); // center the dialog in the middle of the screen final Rectangle screenSize = shell.getDisplay().getPrimaryMonitor().getBounds(); shell.setLocation((screenSize.width - shell.getBounds().width) / 2, (screenSize.height - shell.getBounds().height) / 2); shell.pack(); shell.open(); while (!shell.isDisposed()) { if (!display.readAndDispatch()) { display.sleep(); } } return jobEntryInt; } @Override public void widgetDisposed(DisposeEvent event) { for (Object resource : resources) { if (resource instanceof Image) { ((Image) resource).dispose(); } } } protected Point getDialogSize() { Point clientAreaSize = shell.computeSize(SWT.DEFAULT, SWT.DEFAULT); int frameX = shell.getSize().x - shell.getClientArea().width; int frameY = shell.getSize().y - shell.getClientArea().height; return new Point(frameX + clientAreaSize.x, frameY + clientAreaSize.y); } protected abstract void addConfigurationFields(Group propertiesGroup, int margin, int middle); public void cancel() { // do nothing } public abstract void ok(); protected void showWarning(String message) { MessageBox messageBox = new MessageBox(new Shell(), SWT.ICON_WARNING | SWT.OK); messageBox.setText("EasyDataQuality - Warning"); messageBox.setMessage(message); messageBox.open(); } protected String getStepDescription() { return null; } }
datacleaner/pdi-datacleaner
src/main/java/org/datacleaner/kettle/ui/AbstractJobEntryDialog.java
Java
lgpl-3.0
8,903
import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; /** * Randomly generates Secret Santa assignments for a given group. * <p> * All valid possible assignments are equally likely to be generated (uniform distribution). * * @author Michael Zaccardo ([email protected]) */ public class SecretSanta { private static final Random random = new Random(); private static final String[] DEFAULT_NAMES = { "Rob", "Ally", "Angus", "Mike", "Shannon", "Greg", "Lewis", "Isabel" }; public static void main(final String[] args) { final String[] names = getNamesToUse(args); final List<Integer> assignments = generateAssignments(names.length); printAssignmentsWithNames(assignments, names); } private static String[] getNamesToUse(final String[] args) { if (args.length >= 2) { return args; } else { System.out.println("Two or more names were not provided -- using default names.\n"); return DEFAULT_NAMES; } } private static List<Integer> generateAssignments(final int size) { final List<Integer> assignments = generateShuffledList(size); while (!areValidAssignments(assignments)) { Collections.shuffle(assignments, random); } return assignments; } private static List<Integer> generateShuffledList(final int size) { final List<Integer> list = new ArrayList<>(size); for (int i = 0; i < size; i++) { list.add(i); } Collections.shuffle(list, random); return list; } private static boolean areValidAssignments(final List<Integer> assignments) { for (int i = 0; i < assignments.size(); i++) { if (i == assignments.get(i)) { return false; } } return true; } private static void printAssignmentsWithNames(final List<Integer> assignments, final String[] names) { for (int i = 0; i < assignments.size(); i++) { System.out.println(names[i] + " --> " + names[assignments.get(i)]); } } }
AetherWorks/SecretSanta
java/SecretSanta.java
Java
unlicense
2,008
package com.google.gson; import com.google.gson.stream.JsonReader; import com.google.gson.stream.JsonWriter; class Gson$FutureTypeAdapter<T> extends TypeAdapter<T> { private TypeAdapter<T> delegate; public T read(JsonReader paramJsonReader) { if (this.delegate == null) throw new IllegalStateException(); return this.delegate.read(paramJsonReader); } public void setDelegate(TypeAdapter<T> paramTypeAdapter) { if (this.delegate != null) throw new AssertionError(); this.delegate = paramTypeAdapter; } public void write(JsonWriter paramJsonWriter, T paramT) { if (this.delegate == null) throw new IllegalStateException(); this.delegate.write(paramJsonWriter, paramT); } } /* Location: E:\Progs\Dev\Android\Decompile\apktool\zssq\zssq-dex2jar.jar * Qualified Name: com.google.gson.Gson.FutureTypeAdapter * JD-Core Version: 0.6.0 */
clilystudio/NetBook
allsrc/com/google/gson/Gson$FutureTypeAdapter.java
Java
unlicense
917
package com.smartgwt.mobile.client.widgets; import com.google.gwt.resources.client.ImageResource; public abstract class Action { private ImageResource icon; private int iconSize; private String title; private String tooltip; public Action(String title) { this.title = title; } public Action(ImageResource icon) { this.icon = icon; } public Action(String title, ImageResource icon) { this(title); this.icon = icon; } public Action(String title, ImageResource icon, int iconSize) { this(title, icon); this.iconSize = iconSize; } public Action(String title, ImageResource icon, int iconSize, String tooltip) { this(title, icon, iconSize); this.tooltip = tooltip; } public final ImageResource getIcon() { return icon; } public final int getIconSize() { return iconSize; } public final String getTitle() { return title; } public final String getTooltip() { return tooltip; } public abstract void execute(ActionContext context); }
will-gilbert/SmartGWT-Mobile
mobile/src/main/java/com/smartgwt/mobile/client/widgets/Action.java
Java
unlicense
1,126
/* ********************************************************************** /* * NOTE: This copyright does *not* cover user programs that use Hyperic * program services by normal system calls through the application * program interfaces provided as part of the Hyperic Plug-in Development * Kit or the Hyperic Client Development Kit - this is merely considered * normal use of the program, and does *not* fall under the heading of * "derived work". * * Copyright (C) [2004-2012], VMware, Inc. * This file is part of Hyperic. * * Hyperic is free software; you can redistribute it and/or modify * it under the terms version 2 of the GNU General Public License as * published by the Free Software Foundation. This program is distributed * in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA. */ package org.hyperic.tools.ant; import java.io.ByteArrayInputStream; import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.IOException; import java.io.InputStream; import java.lang.reflect.Method; import java.util.HashMap; import java.util.Map; import java.util.Properties; import java.util.regex.Matcher; import java.util.regex.Pattern; public class PropertiesFileMergerTask extends Properties{ private static Method saveConvertMethod ; private String fileContent ; private Map<String,String[]> delta ; private boolean isLoaded ; static { try{ saveConvertMethod = Properties.class.getDeclaredMethod("saveConvert", String.class, boolean.class, boolean.class) ; saveConvertMethod.setAccessible(true) ; }catch(Throwable t) { throw (t instanceof RuntimeException ? (RuntimeException) t: new RuntimeException(t)) ; }//EO catch block }//EO static block public PropertiesFileMergerTask() { this.delta = new HashMap<String, String[]>() ; }//EOM @Override public synchronized Object put(Object key, Object value) { Object oPrevious = null ; try{ oPrevious = super.put(key, value); if(this.isLoaded && !value.equals(oPrevious)) this.delta.put(key.toString(), new String[] { value.toString(), (String) oPrevious}) ; return oPrevious ; }catch(Throwable t) { t.printStackTrace() ; throw new RuntimeException(t) ; }//EO catch block }//EOM @Override public final synchronized Object remove(Object key) { final Object oExisting = super.remove(key); this.delta.remove(key) ; return oExisting ; }//EOM public static final PropertiesFileMergerTask load(final File file) throws IOException { InputStream fis = null, fis1 = null ; try{ if(!file.exists()) throw new IOException(file + " does not exist or is not readable") ; //else final PropertiesFileMergerTask properties = new PropertiesFileMergerTask() ; fis = new FileInputStream(file) ; //first read the content into a string final byte[] arrFileContent = new byte[(int)fis.available()] ; fis.read(arrFileContent) ; properties.fileContent = new String(arrFileContent) ; fis1 = new ByteArrayInputStream(arrFileContent) ; properties.load(fis1); // System.out.println(properties.fileContent); return properties ; }catch(Throwable t) { throw (t instanceof IOException ? (IOException)t : new IOException(t)) ; }finally{ if(fis != null) fis.close() ; if(fis1 != null) fis1.close() ; }//EO catch block }//EOM @Override public synchronized void load(InputStream inStream) throws IOException { try{ super.load(inStream); }finally{ this.isLoaded = true ; }//EO catch block }//EOm public final void store(final File outputFile, final String comments) throws IOException { if(this.delta.isEmpty()) return ; FileOutputStream fos = null ; String key = null, value = null ; Pattern pattern = null ; Matcher matcher = null ; String[] arrValues = null; try{ for(Map.Entry<String,String[]> entry : this.delta.entrySet()) { key = (String) saveConvertMethod.invoke(this, entry.getKey(), true/*escapeSpace*/, true /*escUnicode*/); arrValues = entry.getValue() ; value = (String) saveConvertMethod.invoke(this, arrValues[0], false/*escapeSpace*/, true /*escUnicode*/); //if the arrValues[1] == null then this is a new property if(arrValues[1] == null) { this.fileContent = this.fileContent + "\n" + key + "=" + value ; }else { //pattern = Pattern.compile(key+"\\s*=(\\s*.*\\s*)"+ arrValues[1].replaceAll("\\s+", "(\\\\s*.*\\\\s*)") , Pattern.MULTILINE) ; pattern = Pattern.compile(key+"\\s*=.*\n", Pattern.MULTILINE) ; matcher = pattern.matcher(this.fileContent) ; this.fileContent = matcher.replaceAll(key + "=" + value) ; }//EO else if existing property System.out.println("Adding/Replacing " + key + "-->" + arrValues[1] + " with: " + value) ; }//EO while there are more entries ; fos = new FileOutputStream(outputFile) ; fos.write(this.fileContent.getBytes()) ; }catch(Throwable t) { throw (t instanceof IOException ? (IOException)t : new IOException(t)) ; }finally{ if(fos != null) { fos.flush() ; fos.close() ; }//EO if bw was initialized }//EO catch block }//EOM public static void main(String[] args) throws Throwable { ///FOR DEBUG String s = " 1 2 4 sdf \\\\\nsdfsd" ; final Pattern pattern = Pattern.compile("test.prop2\\s*=.*(?:\\\\?\\s*)(\n)" , Pattern.MULTILINE) ; final Matcher matcher = pattern.matcher("test.prop2="+s) ; System.out.println(matcher.replaceAll("test.prop2=" + "newvalue$1")) ; ///FOR DEBUG if(true) return ; final String path = "/tmp/confs/hq-server-46.conf" ; final File file = new File(path) ; final PropertiesFileMergerTask properties = PropertiesFileMergerTask.load(file) ; /* final Pattern pattern = Pattern.compile("test.prop1\\s*=this(\\s*.*\\s*)is(\\s*.*\\s*)the(\\s*.*\\s*)value" , Pattern.MULTILINE) ; final Matcher matcher = pattern.matcher(properties.fileContent) ; System.out.println( matcher.replaceAll("test.prop1=new value") ) ; System.out.println("\n\n--> " + properties.get("test.prop1")) ;*/ final String overridingConfPath = "/tmp/confs/hq-server-5.conf" ; //final Properties overrdingProperties = new Properties() ; final FileInputStream fis = new FileInputStream(overridingConfPath) ; properties.load(fis) ; fis.close() ; ///properties.putAll(overrdingProperties) ; final String outputPath = "/tmp/confs/output-hq-server.conf" ; final File outputFile = new File(outputPath) ; final String comments = "" ; properties.store(outputFile, comments) ; }//EOM }//EOC
cc14514/hq6
hq-installer/src/main/java/org/hyperic/tools/ant/PropertiesFileMergerTask.java
Java
unlicense
8,153
package com.sochat.client; import java.math.BigInteger; import java.security.GeneralSecurityException; import java.security.KeyFactory; import java.security.PublicKey; import java.security.spec.RSAPublicKeySpec; public class ServerPublicKey { public static PublicKey getServerPublicKey(String publicKeyModulus, String publicKeyExponent) throws GeneralSecurityException { BigInteger modulus = new BigInteger(publicKeyModulus, 16); BigInteger exponent = new BigInteger(publicKeyExponent, 16); RSAPublicKeySpec pubKeySpec = new RSAPublicKeySpec(modulus, exponent); KeyFactory keyFactory = KeyFactory.getInstance("RSA"); return keyFactory.generatePublic(pubKeySpec); } }
ovaskevich/sochat
src/com/sochat/client/ServerPublicKey.java
Java
unlicense
732
package com.elionhaxhi.ribbit.ui; import java.util.ArrayList; import java.util.List; import android.app.Activity; import android.app.AlertDialog; import android.net.Uri; import android.os.Bundle; import android.support.v4.app.NavUtils; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.view.Window; import android.widget.AdapterView; import android.widget.AdapterView.OnItemClickListener; import android.widget.GridView; import android.widget.ImageView; import android.widget.ListView; import android.widget.TextView; import android.widget.Toast; import com.elionhaxhi.ribbit.R; import com.elionhaxhi.ribbit.adapters.UserAdapter; import com.elionhaxhi.ribbit.utils.FileHelper; import com.elionhaxhi.ribbit.utils.ParseConstants; import com.parse.FindCallback; import com.parse.ParseException; import com.parse.ParseFile; import com.parse.ParseInstallation; import com.parse.ParseObject; import com.parse.ParsePush; import com.parse.ParseQuery; import com.parse.ParseRelation; import com.parse.ParseUser; import com.parse.SaveCallback; public class RecipientsActivity extends Activity { public static final String TAG=RecipientsActivity.class.getSimpleName(); protected List<ParseUser> mFriends; protected ParseRelation<ParseUser> mFriendsRelation; protected ParseUser mCurrentUser; protected MenuItem mSendMenuItem; protected Uri mMediaUri; protected String mFileType; protected GridView mGridView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS); setContentView(R.layout.user_grid); //setupActionBar(); mGridView =(GridView)findViewById(R.id.friendsGrid); mGridView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE); mGridView.setOnItemClickListener(mOnItemClickListener); TextView emptyTextView = (TextView)findViewById(android.R.id.empty); mGridView.setEmptyView(emptyTextView); mMediaUri = getIntent().getData(); mFileType = getIntent().getExtras().getString(ParseConstants.KEY_FILE_TYPE); } @Override public void onResume(){ super.onResume(); mCurrentUser = ParseUser.getCurrentUser(); mFriendsRelation = mCurrentUser.getRelation(ParseConstants.KEY_FRIENDS_RELATION); setProgressBarIndeterminateVisibility(true); ParseQuery<ParseUser> query = mFriendsRelation.getQuery(); query.addAscendingOrder(ParseConstants.KEY_USERNAME); query.findInBackground(new FindCallback<ParseUser>(){ @Override public void done(List<ParseUser> friends, ParseException e){ setProgressBarIndeterminateVisibility(false); if(e == null){ mFriends = friends; String [] usernames = new String[mFriends.size()]; int i =0; for(ParseUser user : mFriends){ usernames[i]=user.getUsername(); i++; } if(mGridView.getAdapter() == null){ UserAdapter adapter = new UserAdapter(RecipientsActivity.this, mFriends); mGridView.setAdapter(adapter); } else{ ((UserAdapter)mGridView.getAdapter()).refill(mFriends); } } else{ Log.e(TAG, e.getMessage()); AlertDialog.Builder builder= new AlertDialog.Builder(RecipientsActivity.this); builder.setMessage(e.getMessage()) .setTitle(R.string.error_title) .setPositiveButton(android.R.string.ok, null); AlertDialog dialog = builder.create(); dialog.show(); } } }); } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.reciptient, menu); mSendMenuItem = menu.getItem(0); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { // Handle action bar item clicks here. The action bar will // as you specify a parent activity in AndroidManifest.xml. int id = item.getItemId(); switch(item.getItemId()){ case android.R.id.home: NavUtils.navigateUpFromSameTask(this); return true; case R.id.action_send: ParseObject message = createMessage(); if(message == null){ AlertDialog.Builder builder = new AlertDialog.Builder(this); builder.setMessage(R.string.error_selecting_file) .setTitle(R.string.error_selection_file_title) .setPositiveButton(android.R.string.ok, null); AlertDialog dialog = builder.create(); dialog.show(); } else { send(message); finish(); } return true; } return super.onOptionsItemSelected(item); } protected ParseObject createMessage(){ ParseObject message = new ParseObject(ParseConstants.CLASS_MESSAGE); message.put(ParseConstants.KEY_SENDER_ID, ParseUser.getCurrentUser().getObjectId()); message.put(ParseConstants.KEY_SENDER_NAME, ParseUser.getCurrentUser().getUsername()); message.put(ParseConstants.KEY_RECIPIENT_IDS, getRecipientIds()); message.put(ParseConstants.KEY_FILE_TYPE, mFileType); byte[] fileBytes = FileHelper.getByteArrayFromFile(this, mMediaUri); if(fileBytes == null){ return null; } else{ if(mFileType.equalsIgnoreCase(ParseConstants.TYPE_IMAGE)){ fileBytes = FileHelper.reduceImageForUpload(fileBytes); } String fileName = FileHelper.getFileName(this, mMediaUri, mFileType); ParseFile file = new ParseFile(fileName, fileBytes); message.put(ParseConstants.KEY_FILE, file); return message; } } protected ArrayList<String> getRecipientIds(){ ArrayList<String> recipientIds = new ArrayList<String>(); for(int i=0; i< mGridView.getCount(); i++){ if(mGridView.isItemChecked(i)){ recipientIds.add(mFriends.get(i).getObjectId()); } } return recipientIds; } protected void send(ParseObject message){ message.saveInBackground(new SaveCallback(){ @Override public void done(ParseException e){ if(e == null){ //success Toast.makeText(RecipientsActivity.this, R.string.success_message, Toast.LENGTH_LONG).show(); sendPushNotifications(); } else{ AlertDialog.Builder builder = new AlertDialog.Builder(RecipientsActivity.this); builder.setMessage(R.string.error_sending_message) .setTitle(R.string.error_selection_file_title) .setPositiveButton(android.R.string.ok, null); AlertDialog dialog = builder.create(); dialog.show(); } } }); } protected OnItemClickListener mOnItemClickListener = new OnItemClickListener() { @Override public void onItemClick(AdapterView<?> parent, View view, int position, long id) { if(mGridView.getCheckedItemCount() > 0) { mSendMenuItem.setVisible(true); } else{ mSendMenuItem.setVisible(false); } ImageView checkImageView =(ImageView)findViewById(R.id.checkImageView); if(mGridView.isItemChecked(position)){ //add recipient checkImageView.setVisibility(View.VISIBLE); } else{ //remove the recipient checkImageView.setVisibility(View.INVISIBLE); } } }; protected void sendPushNotifications(){ ParseQuery<ParseInstallation> query = ParseInstallation.getQuery(); query.whereContainedIn(ParseConstants.KEY_USER_ID, getRecipientIds()); //send a push notificaton ParsePush push = new ParsePush(); push.setQuery(query); push.setMessage(getString(R.string.push_message, ParseUser.getCurrentUser().getUsername())); push.sendInBackground(); } }
ElionHaxhi/Ribbit
src/com/elionhaxhi/ribbit/ui/RecipientsActivity.java
Java
unlicense
7,505
package com.intershop.adapter.payment.partnerpay.internal.service.capture; import javax.inject.Inject; import com.google.inject.Injector; import com.intershop.adapter.payment.partnerpay.capi.service.capture.CaptureFactory; import com.intershop.api.service.payment.v1.capability.Capture; public class CaptureFactoryImpl implements CaptureFactory { @Inject private Injector injector; @Override public Capture createCapture() { Capture ret = new CaptureImpl(); injector.injectMembers(ret); return ret; } }
IntershopCommunicationsAG/partnerpay-example
s_payment_partnerpay/ac_payment_partnerpay/javasource/com/intershop/adapter/payment/partnerpay/internal/service/capture/CaptureFactoryImpl.java
Java
unlicense
578
// This Source Code is in the Public Domain per: http://unlicense.org package org.litesoft.commonfoundation.charstreams; /** * A CharSource is like a powerful version of a "char" based Iterator. */ public interface CharSource { /** * Report if there are any more characters available to get(). * <p/> * Similar to Iterator's hasNext(). */ public boolean anyRemaining(); /** * Get the next character (consume it from the stream) or -1 if there are no more characters available. */ public int get(); /** * Get the next character (consume it from the stream) or throw an exception if there are no more characters available. */ public char getRequired(); /** * Return the next character (without consuming it) or -1 if there are no more characters available. */ public int peek(); /** * Return the Next Offset (from the stream) that the peek/get/getRequired would read from (it may be beyond the stream end). */ public int getNextOffset(); /** * Return the Last Offset (from the stream), which the previous get/getRequired read from (it may be -1 if stream has not been successfully read from). */ public int getLastOffset(); /** * Return a string (and consume the characters) from the current position up to (but not including) the position of the 'c' character. OR "" if 'c' is not found (nothing consumed). */ public String getUpTo( char c ); /** * Consume all the spaces (NOT white space) until either there are no more characters or a non space is encountered (NOT consumed). * * @return true if there are more characters. */ public boolean consumeSpaces(); /** * Return a string (and consume the characters) from the current position thru the end of the characters OR up to (but not including) a character that is not a visible 7-bit ascii character (' ' < c <= 126). */ public String getUpToNonVisible7BitAscii(); /** * Consume all the non-visible 7-bit ascii characters (visible c == ' ' < c <= 126) until either there are no more characters or a visible 7-bit ascii character is encountered (NOT consumed). * * @return true if there are more characters. */ public boolean consumeNonVisible7BitAscii(); }
litesoft/LiteSoftCommonFoundation
src/org/litesoft/commonfoundation/charstreams/CharSource.java
Java
unlicense
2,332
package net.simpvp.Jail; import java.text.SimpleDateFormat; import java.util.Date; import java.util.UUID; import org.bukkit.Location; /** * Class representing the stored information about a jailed player */ public class JailedPlayer { public UUID uuid; public String playername; public String reason; public String jailer; public Location location; public int jailed_time; public boolean to_be_released; public boolean online; public JailedPlayer(UUID uuid, String playername, String reason, String jailer, Location location, int jailed_time, boolean to_be_released, boolean online) { this.uuid = uuid; this.playername = playername; this.reason = reason; this.jailer = jailer; this.location = location; this.jailed_time = jailed_time; this.to_be_released = to_be_released; this.online = online; } public void add() { Jail.jailed_players.add(this.uuid); } public void insert() { SQLite.insert_player_info(this); } public int get_to_be_released() { int ret = 0; if (this.to_be_released) ret ^= 1; if (!this.online) ret ^= 2; return ret; } /** * Returns a text description of this jailed player. */ public String get_info() { SimpleDateFormat sdf = new SimpleDateFormat("d MMMM yyyy, H:m:s"); String msg = this.playername + " (" + this.uuid + ")" + " was jailed on " + sdf.format(new Date(this.jailed_time * 1000L)) + " by " + this.jailer + " for" + this.reason + "."; if (this.to_be_released) { msg += "\nThis player is set to be released"; } return msg; } }
C4K3/Jail
src/main/java/net/simpvp/Jail/JailedPlayer.java
Java
unlicense
1,551
/* * NOTE: This copyright does *not* cover user programs that use HQ * program services by normal system calls through the application * program interfaces provided as part of the Hyperic Plug-in Development * Kit or the Hyperic Client Development Kit - this is merely considered * normal use of the program, and does *not* fall under the heading of * "derived work". * * Copyright (C) [2004, 2005, 2006], Hyperic, Inc. * This file is part of HQ. * * HQ is free software; you can redistribute it and/or modify * it under the terms version 2 of the GNU General Public License as * published by the Free Software Foundation. This program is distributed * in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA. */ package org.hyperic.hq.ui.action.portlet.autoDisc; import org.hyperic.hq.appdef.shared.AIPlatformValue; import org.hyperic.hq.autoinventory.ScanStateCore; import org.hyperic.hq.autoinventory.ScanMethodState; public class AIPlatformWithStatus extends AIPlatformValue { private ScanStateCore state = null; public AIPlatformWithStatus(AIPlatformValue aip, ScanStateCore state) { super(aip); this.state = state; } public boolean getIsAgentReachable() { return state != null; } public boolean getIsScanning() { return state != null && !state.getIsDone(); } public String getStatus() { if (state == null) return "Agent is not responding"; if (state.getGlobalException() != null) { return state.getGlobalException().getMessage(); } ScanMethodState[] methstates = state.getScanMethodStates(); String rval = ""; String status; for (int i = 0; i < methstates.length; i++) { status = methstates[i].getStatus(); if (status != null) rval += status.trim(); } rval = rval.trim(); if (rval.length() == 0) { rval = "Scan starting..."; } return rval; } }
cc14514/hq6
hq-web/src/main/java/org/hyperic/hq/ui/action/portlet/autoDisc/AIPlatformWithStatus.java
Java
unlicense
2,391
package generics.p19; import java.util.Random; import utils.Generator; public class Good { private final int id; private String description; public Good(int id, String description) { this.id = id; this.description = description; } public static Generator<Good> generator = new Generator<Good>() { Random random = new Random(); @Override public Good next() { return new Good(random.nextInt(1000), ""); } }; @Override public String toString() { return "Good: " + id + " " + description; } }
bodydomelight/tij-problems
src/generics/p19/Good.java
Java
unlicense
619
package net.yottabyte.game; import java.awt.*; /** * @author Jason Fagan */ public class BouncyBall { private int x; private int y; private int vx; private int vy; private int radius; private int drag; private int mass; public BouncyBall(int x, int y, int vx, int vy, int radius, int mass, int drag) { this.x = x; this.y = y; this.vx = vx; this.vy = vy; this.radius = radius; this.mass = mass; this.drag = drag; } public void move(Rectangle rect) { x += vx; y += vy; hitWall(rect); } public void paint(Graphics2D g2d) { g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); g2d.setColor(Color.WHITE); g2d.fillOval(x, y, radius, radius); } public void hitWall(Rectangle rect) { if (x <= 0) { x = 0; vx = -(vx * drag); } else if (x + radius >= rect.width) { x = rect.width - radius; vx = -(vx * drag); } if (y < 0) { y = 0; vy = -(vy * drag); } else if (y + (radius * 2) >= rect.height) { y = rect.height - (radius * 2); vy = -(vy * drag); } } // see http://en.wikipedia.org/wiki/Elastic_collision public boolean hasCollidedWith(BouncyBall ball) { int dx = Math.abs(getCenterX() - ball.getCenterX()); int dy = Math.abs(getCenterY() - ball.getCenterY()); double distance = Math.sqrt(dx * dx + dy * dy); return distance <= radius; } public void handleCollision(BouncyBall ball) { int dx = getCenterX() - ball.getCenterX(); int dy = getCenterY() - ball.getCenterY(); // Calculate collision angle double ca = Math.atan2(dy, dx); // Calculate force magnitudes double mgt1 = Math.sqrt(vx * vx + vy * vy); double mgt2 = Math.sqrt(ball.getVx() * ball.getVx() + ball.getVy() * ball.getVy()); // Calculate direction double dir1 = Math.atan2(vy, vx); double dir2 = Math.atan2(ball.getVy(), ball.getVx()); // Calculate new velocities double vx1 = mgt1 * Math.cos(dir1 - ca); double vy1 = mgt1 * Math.sin(dir1 - ca); double vx2 = mgt2 * Math.cos(dir2 - ca); double vy2 = mgt2 * Math.sin(dir2 - ca); double vfx1 = ((mass - ball.getMass()) * vx1 + (ball.getMass() + ball.getMass()) * vx2) / (mass + ball.getMass()); double fvx2 = ((mass + mass) * vx1 + (ball.getMass() - mass) * vx2) / (mass + ball.getMass()); double fvy1 = vy1; double fvy2 = vy2; vx = (int) (Math.cos(ca) * vfx1 + Math.cos(ca + Math.PI / 2) * fvy1); vx = (int) (Math.sin(ca) * vfx1 + Math.sin(ca + Math.PI / 2) * fvy1); ball.setVx((int) (Math.cos(ca) * fvx2 + Math.cos(ca + Math.PI / 2) * fvy2)); ball.setVy((int) (Math.sin(ca) * fvx2 + Math.sin(ca + Math.PI / 2) * fvy2)); } public int getCenterX() { return x - radius / 2; } public int getCenterY() { return y - radius / 2; } public int getX() { return x; } public void setX(int x) { this.x = x; } public int getY() { return y; } public void setY(int y) { this.y = y; } public int getVx() { return vx; } public void setVx(int vx) { this.vx = vx; } public int getVy() { return vy; } public void setVy(int vy) { this.vy = vy; } public int getRadius() { return radius; } public void setRadius(int radius) { this.radius = radius; } public int getDrag() { return drag; } public void setDrag(int drag) { this.drag = drag; } public int getMass() { return mass; } public void setMass(int mass) { this.mass = mass; } }
jasonfagan/game-experiments
physics/src/main/java/net/yottabyte/game/BouncyBall.java
Java
unlicense
3,996
public class RandomColoringDiv2 { public int getCount(int maxR, int maxG, int maxB, int startR, int startG, int startB, int d1, int d2) { int colors = 0; int minR = Math.max(0, startR - d2); int minG = Math.max(0, startG - d2); int minB = Math.max(0, startB - d2); for (int r = minR; r<maxR; r++) { int difR = Math.abs(r - startR); if (difR > d2) break; for (int g = minG; g<maxG; g++) { int difG = Math.abs(g - startG); if (difG > d2) break; for (int b = minB; b<maxB; b++) { int difB = Math.abs(b - startB); if (difB > d2) break; if (difR >= d1 || difG >= d1 || difB >=d1) colors++; } } } return colors; } public static void main(String[] args) { long time; int answer; boolean errors = false; int desiredAnswer; time = System.currentTimeMillis(); answer = new RandomColoringDiv2().getCount(5, 1, 1, 2, 0, 0, 0, 1); System.out.println("Time: " + (System.currentTimeMillis() - time) / 1000.0 + " seconds"); desiredAnswer = 3; System.out.println("Your answer:"); System.out.println("\t" + answer); System.out.println("Desired answer:"); System.out.println("\t" + desiredAnswer); if (answer != desiredAnswer) { errors = true; System.out.println("DOESN'T MATCH!!!!"); } else System.out.println("Match :-)"); System.out.println(); time = System.currentTimeMillis(); answer = new RandomColoringDiv2().getCount(4, 2, 2, 0, 0, 0, 3, 3); System.out.println("Time: " + (System.currentTimeMillis() - time) / 1000.0 + " seconds"); desiredAnswer = 4; System.out.println("Your answer:"); System.out.println("\t" + answer); System.out.println("Desired answer:"); System.out.println("\t" + desiredAnswer); if (answer != desiredAnswer) { errors = true; System.out.println("DOESN'T MATCH!!!!"); } else System.out.println("Match :-)"); System.out.println(); time = System.currentTimeMillis(); answer = new RandomColoringDiv2().getCount(4, 2, 2, 0, 0, 0, 5, 5); System.out.println("Time: " + (System.currentTimeMillis() - time) / 1000.0 + " seconds"); desiredAnswer = 0; System.out.println("Your answer:"); System.out.println("\t" + answer); System.out.println("Desired answer:"); System.out.println("\t" + desiredAnswer); if (answer != desiredAnswer) { errors = true; System.out.println("DOESN'T MATCH!!!!"); } else System.out.println("Match :-)"); System.out.println(); time = System.currentTimeMillis(); answer = new RandomColoringDiv2().getCount(6, 9, 10, 1, 2, 3, 0, 10); System.out.println("Time: " + (System.currentTimeMillis() - time) / 1000.0 + " seconds"); desiredAnswer = 540; System.out.println("Your answer:"); System.out.println("\t" + answer); System.out.println("Desired answer:"); System.out.println("\t" + desiredAnswer); if (answer != desiredAnswer) { errors = true; System.out.println("DOESN'T MATCH!!!!"); } else System.out.println("Match :-)"); System.out.println(); time = System.currentTimeMillis(); answer = new RandomColoringDiv2().getCount(6, 9, 10, 1, 2, 3, 4, 10); System.out.println("Time: " + (System.currentTimeMillis() - time) / 1000.0 + " seconds"); desiredAnswer = 330; System.out.println("Your answer:"); System.out.println("\t" + answer); System.out.println("Desired answer:"); System.out.println("\t" + desiredAnswer); if (answer != desiredAnswer) { errors = true; System.out.println("DOESN'T MATCH!!!!"); } else System.out.println("Match :-)"); System.out.println(); time = System.currentTimeMillis(); answer = new RandomColoringDiv2().getCount(49, 59, 53, 12, 23, 13, 11, 22); System.out.println("Time: " + (System.currentTimeMillis() - time) / 1000.0 + " seconds"); desiredAnswer = 47439; System.out.println("Your answer:"); System.out.println("\t" + answer); System.out.println("Desired answer:"); System.out.println("\t" + desiredAnswer); if (answer != desiredAnswer) { errors = true; System.out.println("DOESN'T MATCH!!!!"); } else System.out.println("Match :-)"); System.out.println(); if (errors) System.out.println("Some of the test cases had errors :-("); else System.out.println("You're a stud (at least on the test data)! :-D "); } } // Powered by [KawigiEdit] 2.0!
mariusj/contests
srm540/src/RandomColoringDiv2.java
Java
unlicense
5,179
package br.com.tosin.ssd.utils; /** * Created by roger on 11/03/17. */ public class CONSTANTS_DIRECTIONS { public static final String NORTH = "N"; public static final String SOUTH = "S"; public static final String WEST = "W"; public static final String EAST = "E"; public static final String NORTHWEST = "NW"; public static final String NORTHEAST = "NE"; public static final String SOUTH_WEST = "SW"; public static final String SOUTHEAST = "SE"; }
TosinRoger/SmartSystemsDesign
src/br/com/tosin/ssd/utils/CONSTANTS_DIRECTIONS.java
Java
unlicense
526
/* * NOTE: This copyright does *not* cover user programs that use HQ * program services by normal system calls through the application * program interfaces provided as part of the Hyperic Plug-in Development * Kit or the Hyperic Client Development Kit - this is merely considered * normal use of the program, and does *not* fall under the heading of * "derived work". * * Copyright (C) [2004-2009], Hyperic, Inc. * This file is part of HQ. * * HQ is free software; you can redistribute it and/or modify * it under the terms version 2 of the GNU General Public License as * published by the Free Software Foundation. This program is distributed * in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A * PARTICULAR PURPOSE. See the GNU General Public License for more * details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 * USA. */ package org.hyperic.hq.ui.server.session; import java.rmi.RemoteException; import java.util.ArrayList; import java.util.Collection; import java.util.List; import javax.security.auth.login.LoginException; import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.hyperic.hq.appdef.shared.AppdefEntityID; import org.hyperic.hq.auth.shared.SessionManager; import org.hyperic.hq.auth.shared.SessionNotFoundException; import org.hyperic.hq.auth.shared.SessionTimeoutException; import org.hyperic.hq.authz.server.session.AuthzApplicationEvent; import org.hyperic.hq.authz.server.session.AuthzSubject; import org.hyperic.hq.authz.server.session.Role; import org.hyperic.hq.authz.server.session.RoleCreatedEvent; import org.hyperic.hq.authz.server.session.RoleDeleteRequestedEvent; import org.hyperic.hq.authz.server.session.RoleRemoveFromSubjectRequestedEvent; import org.hyperic.hq.authz.server.session.SubjectDeleteRequestedEvent; import org.hyperic.hq.authz.shared.AuthzConstants; import org.hyperic.hq.authz.shared.AuthzSubjectManager; import org.hyperic.hq.authz.shared.PermissionException; import org.hyperic.hq.authz.shared.PermissionManager; import org.hyperic.hq.authz.shared.PermissionManagerFactory; import org.hyperic.hq.bizapp.shared.AuthzBoss; import org.hyperic.hq.common.server.session.Crispo; import org.hyperic.hq.common.server.session.CrispoOption; import org.hyperic.hq.common.shared.CrispoManager; import org.hyperic.hq.ui.Constants; import org.hyperic.hq.ui.Dashboard; import org.hyperic.hq.ui.WebUser; import org.hyperic.hq.ui.shared.DashboardManager; import org.hyperic.util.StringUtil; import org.hyperic.util.config.ConfigResponse; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.ApplicationListener; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; /** */ @Service @Transactional public class DashboardManagerImpl implements DashboardManager, ApplicationListener<AuthzApplicationEvent> { private Log log = LogFactory.getLog(DashboardManagerImpl.class); protected SessionManager sessionManager = SessionManager.getInstance(); private DashboardConfigDAO dashDao; private CrispoManager crispoManager; private AuthzSubjectManager authzSubjectManager; @Autowired public DashboardManagerImpl(DashboardConfigDAO dashDao, CrispoManager crispoManager, AuthzSubjectManager authzSubjectManager) { this.dashDao = dashDao; this.crispoManager = crispoManager; this.authzSubjectManager = authzSubjectManager; } /** */ @Transactional(readOnly = true) public UserDashboardConfig getUserDashboard(AuthzSubject me, AuthzSubject user) throws PermissionException { PermissionManager permMan = PermissionManagerFactory.getInstance(); if (!me.equals(user) && !permMan.hasAdminPermission(me.getId())) { throw new PermissionException("You are unauthorized to see this " + "dashboard"); } return dashDao.findDashboard(user); } /** */ @Transactional(readOnly = true) public RoleDashboardConfig getRoleDashboard(AuthzSubject me, Role r) throws PermissionException { PermissionManager permMan = PermissionManagerFactory.getInstance(); permMan.check(me.getId(), r.getResource().getResourceType(), r.getId(), AuthzConstants.roleOpModifyRole); return dashDao.findDashboard(r); } private ConfigResponse getDefaultConfig() { return new ConfigResponse(); } /** */ public UserDashboardConfig createUserDashboard(AuthzSubject me, AuthzSubject user, String name) throws PermissionException { PermissionManager permMan = PermissionManagerFactory.getInstance(); if (!me.equals(user) && !permMan.hasAdminPermission(me.getId())) { throw new PermissionException("You are unauthorized to create " + "this dashboard"); } Crispo cfg = crispoManager.create(getDefaultConfig()); UserDashboardConfig dash = new UserDashboardConfig(user, name, cfg); dashDao.save(dash); return dash; } /** */ public RoleDashboardConfig createRoleDashboard(AuthzSubject me, Role r, String name) throws PermissionException { PermissionManager permMan = PermissionManagerFactory.getInstance(); permMan.check(me.getId(), r.getResource().getResourceType(), r.getId(), AuthzConstants.roleOpModifyRole); Crispo cfg = crispoManager.create(getDefaultConfig()); RoleDashboardConfig dash = new RoleDashboardConfig(r, name, cfg); dashDao.save(dash); return dash; } /** * Reconfigure a user's dashboard */ public void configureDashboard(AuthzSubject me, DashboardConfig cfg, ConfigResponse newCfg) throws PermissionException { if (!isEditable(me, cfg)) { throw new PermissionException("You are unauthorized to modify " + "this dashboard"); } crispoManager.update(cfg.getCrispo(), newCfg); } /** */ public void renameDashboard(AuthzSubject me, DashboardConfig cfg, String name) throws PermissionException { if (!isEditable(me, cfg)) { throw new PermissionException("You are unauthorized to modify " + "this dashboard"); } cfg.setName(name); } /** * Determine if a dashboard is editable by the passed user */ @Transactional(readOnly = true) public boolean isEditable(AuthzSubject me, DashboardConfig dash) { PermissionManager permMan = PermissionManagerFactory.getInstance(); if (permMan.hasAdminPermission(me.getId())) return true; return dash.isEditable(me); } /** */ @Transactional(readOnly = true) public Collection<DashboardConfig> getDashboards(AuthzSubject me) throws PermissionException { Collection<DashboardConfig> res = new ArrayList<DashboardConfig>(); PermissionManager permMan = PermissionManagerFactory.getInstance(); if (permMan.hasGuestRole() && permMan.hasAdminPermission(me.getId())) { res.addAll(dashDao.findAllRoleDashboards()); res.add(getUserDashboard(me, me)); return res; } UserDashboardConfig cfg = getUserDashboard(me, me); if (cfg != null) res.add(cfg); if (permMan.hasGuestRole()) res.addAll(dashDao.findRolesFor(me)); return res; } /** * Update dashboard and user configs to account for resource deletion * * @param ids An array of ID's of removed resources */ public void handleResourceDelete(AppdefEntityID[] ids) { for (int i = 0; i < ids.length; i++) { String appdefKey = ids[i].getAppdefKey(); List<CrispoOption> copts = crispoManager.findOptionByValue(appdefKey); for (CrispoOption o : copts) { String val = o.getValue(); String newVal = removeResource(val, appdefKey); if (!val.equals(newVal)) { crispoManager.updateOption(o, newVal); log.debug("Update option key=" + o.getKey() + " old =" + val + " new =" + newVal); } } } } /** */ @Transactional(readOnly = true) public ConfigResponse getRssUserPreferences(String user, String token) throws LoginException { ConfigResponse preferences; try { AuthzSubject me = authzSubjectManager.findSubjectByName(user); preferences = getUserDashboard(me, me).getConfig(); } catch (Exception e) { throw new LoginException("Username has no preferences"); } // Let's make sure that the rss auth token matches String prefToken = preferences.getValue(Constants.RSS_TOKEN); if (token == null || !token.equals(prefToken)) throw new LoginException("Username and Auth token do not match"); return preferences; } private String removeResource(String val, String resource) { val = StringUtil.remove(val, resource); val = StringUtil.replace(val, Constants.EMPTY_DELIMITER, Constants.DASHBOARD_DELIMITER); return val; } public void onApplicationEvent(AuthzApplicationEvent event) { if(event instanceof SubjectDeleteRequestedEvent) { dashDao.handleSubjectRemoval(((SubjectDeleteRequestedEvent)event).getSubject()); }else if(event instanceof RoleDeleteRequestedEvent) { roleRemoved(((RoleDeleteRequestedEvent)event).getRole()); }else if(event instanceof RoleCreatedEvent) { roleCreated(((RoleCreatedEvent)event).getRole()); }else if(event instanceof RoleRemoveFromSubjectRequestedEvent) { roleRemovedFromSubject(((RoleRemoveFromSubjectRequestedEvent)event).getRole(), ((RoleRemoveFromSubjectRequestedEvent)event).getSubject()); } } private void roleRemoved(Role role) { RoleDashboardConfig cfg = dashDao.findDashboard(role); if (cfg == null) { return; } List<CrispoOption> opts = crispoManager.findOptionByKey(Constants.DEFAULT_DASHBOARD_ID); for (CrispoOption opt : opts) { if (Integer.valueOf(opt.getValue()).equals(cfg.getId())) { crispoManager.updateOption(opt, null); } } dashDao.handleRoleRemoval(role); } private void roleCreated(Role role) { Crispo cfg = crispoManager.create(getDefaultConfig()); RoleDashboardConfig dash = new RoleDashboardConfig(role, role.getName() + " Role Dashboard", cfg); dashDao.save(dash); } private void roleRemovedFromSubject(Role r, AuthzSubject from) { RoleDashboardConfig cfg = dashDao.findDashboard(r); Crispo c = from.getPrefs(); if (c != null) { for (CrispoOption opt : c.getOptions()) { if (opt.getKey().equals(Constants.DEFAULT_DASHBOARD_ID) && Integer.valueOf(opt.getValue()).equals(cfg.getId())) { crispoManager.updateOption(opt, null); break; } } } } @Transactional(readOnly = true) public List<DashboardConfig> findEditableDashboardConfigs(WebUser user, AuthzBoss boss) throws SessionNotFoundException, SessionTimeoutException, PermissionException, RemoteException { AuthzSubject me = boss.findSubjectById(user.getSessionId(), user.getSubject().getId()); Collection<DashboardConfig> dashboardCollection = getDashboards(me); List<DashboardConfig> editableDashboardConfigs = new ArrayList<DashboardConfig>(); for (DashboardConfig config : dashboardCollection) { if (isEditable(me, config)) { editableDashboardConfigs.add(config); } } return editableDashboardConfigs; } @Transactional(readOnly = true) public List<Dashboard> findEditableDashboards(WebUser user, AuthzBoss boss) throws SessionNotFoundException, SessionTimeoutException, PermissionException, RemoteException { List<DashboardConfig> dashboardConfigs = findEditableDashboardConfigs(user, boss); List<Dashboard> editableDashboards = new ArrayList<Dashboard>(); for (DashboardConfig config : dashboardConfigs) { Dashboard dashboard = new Dashboard(); dashboard.set_name(config.getName()); dashboard.setId(config.getId()); editableDashboards.add(dashboard); } return editableDashboards; } /** * Find a given dashboard by its id * @param id the id of the dashboard * @param user current user * @param boss the authzboss * @return the DashboardConfig of the corresponding DashboardId or null if * none */ @Transactional(readOnly = true) public DashboardConfig findDashboard(Integer id, WebUser user, AuthzBoss boss) { Collection<DashboardConfig> dashboardCollection; try { AuthzSubject me = boss.findSubjectById(user.getSessionId(), user.getSubject().getId()); dashboardCollection = getDashboards(me); } catch (Exception e) { return null; } for (DashboardConfig config : dashboardCollection) { if (config.getId().equals(id)) { return config; } } return null; } }
cc14514/hq6
hq-web/src/main/java/org/hyperic/hq/ui/server/session/DashboardManagerImpl.java
Java
unlicense
13,750
package es.com.blogspot.elblogdepicodev.activiti; import java.text.MessageFormat; import java.util.HashMap; import java.util.Map; import org.activiti.engine.ProcessEngine; import org.activiti.engine.ProcessEngineConfiguration; import org.activiti.engine.ProcessEngines; import org.activiti.engine.RepositoryService; import org.activiti.engine.RuntimeService; import org.activiti.engine.runtime.ProcessInstance; import org.h2.tools.Server; import es.com.blogspot.elblogdepicodev.activiti.misc.Producto; public class Errores { public static void main(String[] args) throws Exception { Server server = null; try { server = Server.createTcpServer().start(); ProcessEngines.init(); ProcessEngine processEngine = ProcessEngineConfiguration.createProcessEngineConfigurationFromResource("activiti-mysql.cfg.xml").buildProcessEngine(); RuntimeService runtimeService = processEngine.getRuntimeService(); RepositoryService repositoryService = processEngine.getRepositoryService(); repositoryService.createDeployment().addClasspathResource("bpmn/Errores.bpmn20.xml").deploy(); Producto producto = new Producto("Arch Linux T-Shirt", 10l); Map variables = new HashMap(); variables.put("producto", producto); ProcessInstance pi = runtimeService.startProcessInstanceByKey("errores", variables); System.out.println(MessageFormat.format("Las nuevas existencias de {0} son {1}", producto.getNombre(), producto.getExistencias())); } finally { ProcessEngines.destroy(); if (server != null) server.stop(); } } }
picodotdev/elblogdepicodev
HelloWorldActiviti/src/main/java/es/com/blogspot/elblogdepicodev/activiti/Errores.java
Java
unlicense
1,554
package ua.clinic.tests.integration; import com.fasterxml.jackson.databind.ObjectMapper; import org.junit.Test; import org.junit.runner.RunWith; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.autoconfigure.web.servlet.AutoConfigureMockMvc; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.http.MediaType; import org.springframework.test.context.junit4.SpringRunner; import org.springframework.test.web.servlet.MockMvc; import org.springframework.test.web.servlet.MvcResult; import ua.ibt.clinic.api.DetailsAPI; import ua.ibt.clinic.api.DoctorAPI; import java.text.SimpleDateFormat; import static org.junit.Assert.assertEquals; import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.post; import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.status; /** * Created by Iryna Tkachova on 11.03.2017. */ @RunWith(SpringRunner.class) @SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT) @AutoConfigureMockMvc public class UserdetailsControllerTest { private static final Logger logger = LoggerFactory.getLogger(UserdetailsControllerTest.class); @Autowired private MockMvc mockMvc; @Test public void test_addDetails() throws Exception { logger.debug(">>>>>>>>>> test_addDetails >>>>>>>>>>"); DetailsAPI detailsAPI = new DetailsAPI(); detailsAPI.iduser = Long.valueOf(984844); detailsAPI.numcard = "aa-111"; detailsAPI.name = "Ivan"; detailsAPI.surname = "Ivanenko"; detailsAPI.middlename = "Ivanovich"; detailsAPI.birthday = new SimpleDateFormat("yyyy-MM-dd").parse("2001-10-10"); detailsAPI.sex = "M"; detailsAPI.notes = "test"; ObjectMapper om = new ObjectMapper(); String content = om.writeValueAsString(detailsAPI); MvcResult result = mockMvc.perform(post("/details/set") .accept(MediaType.APPLICATION_JSON_UTF8) .contentType(MediaType.APPLICATION_JSON_UTF8) .content(content) ) .andExpect(status().isOk()) .andReturn(); String reply = result.getResponse().getContentAsString(); DetailsAPI resultData = om.readValue(reply, DetailsAPI.class); assertEquals("Reurn code in not 0",resultData.retcode.longValue(), 0L); } @Test public void test_setDoctor() throws Exception { logger.debug(">>>>>>>>>> test_setDoctor >>>>>>>>>>"); DoctorAPI doctorAPI = new DoctorAPI(); doctorAPI.iduser = Long.valueOf(984844); doctorAPI.tabnumber = Long.valueOf(22222); ObjectMapper om = new ObjectMapper(); String content = om.writeValueAsString(doctorAPI); MvcResult result = mockMvc.perform(post("/doctor/set") .accept(MediaType.APPLICATION_JSON_UTF8) .contentType(MediaType.APPLICATION_JSON_UTF8) .content(content) ) .andExpect(status().isOk()) .andReturn(); String reply = result.getResponse().getContentAsString(); DetailsAPI resultData = om.readValue(reply, DetailsAPI.class); assertEquals("Reurn code in not 0",resultData.retcode.longValue(), 0L); } }
beamka/Polyclinic
Clinic/src/test/java/ua/clinic/tests/integration/UserdetailsControllerTest.java
Java
unlicense
3,482
/* * Copyright 2002-2008 the original author or authors. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.springframework.util; import java.util.Arrays; import java.util.Collection; import java.util.Enumeration; import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Properties; /** * Miscellaneous collection utility methods. * Mainly for internal use within the framework. * * @author Juergen Hoeller * @author Rob Harrop * @since 1.1.3 */ public abstract class CollectionUtils { /** * Return <code>true</code> if the supplied Collection is <code>null</code> * or empty. Otherwise, return <code>false</code>. * @param collection the Collection to check * @return whether the given Collection is empty */ public static boolean isEmpty(Collection collection) { return (collection == null || collection.isEmpty()); } /** * Return <code>true</code> if the supplied Map is <code>null</code> * or empty. Otherwise, return <code>false</code>. * @param map the Map to check * @return whether the given Map is empty */ public static boolean isEmpty(Map map) { return (map == null || map.isEmpty()); } /** * Convert the supplied array into a List. A primitive array gets * converted into a List of the appropriate wrapper type. * <p>A <code>null</code> source value will be converted to an * empty List. * @param source the (potentially primitive) array * @return the converted List result * @see ObjectUtils#toObjectArray(Object) */ public static List arrayToList(Object source) { return Arrays.asList(ObjectUtils.toObjectArray(source)); } /** * Merge the given array into the given Collection. * @param array the array to merge (may be <code>null</code>) * @param collection the target Collection to merge the array into */ public static void mergeArrayIntoCollection(Object array, Collection collection) { if (collection == null) { throw new IllegalArgumentException("Collection must not be null"); } Object[] arr = ObjectUtils.toObjectArray(array); for (int i = 0; i < arr.length; i++) { collection.add(arr[i]); } } /** * Merge the given Properties instance into the given Map, * copying all properties (key-value pairs) over. * <p>Uses <code>Properties.propertyNames()</code> to even catch * default properties linked into the original Properties instance. * @param props the Properties instance to merge (may be <code>null</code>) * @param map the target Map to merge the properties into */ public static void mergePropertiesIntoMap(Properties props, Map map) { if (map == null) { throw new IllegalArgumentException("Map must not be null"); } if (props != null) { for (Enumeration en = props.propertyNames(); en.hasMoreElements();) { String key = (String) en.nextElement(); map.put(key, props.getProperty(key)); } } } /** * Check whether the given Iterator contains the given element. * @param iterator the Iterator to check * @param element the element to look for * @return <code>true</code> if found, <code>false</code> else */ public static boolean contains(Iterator iterator, Object element) { if (iterator != null) { while (iterator.hasNext()) { Object candidate = iterator.next(); if (ObjectUtils.nullSafeEquals(candidate, element)) { return true; } } } return false; } /** * Check whether the given Enumeration contains the given element. * @param enumeration the Enumeration to check * @param element the element to look for * @return <code>true</code> if found, <code>false</code> else */ public static boolean contains(Enumeration enumeration, Object element) { if (enumeration != null) { while (enumeration.hasMoreElements()) { Object candidate = enumeration.nextElement(); if (ObjectUtils.nullSafeEquals(candidate, element)) { return true; } } } return false; } /** * Check whether the given Collection contains the given element instance. * <p>Enforces the given instance to be present, rather than returning * <code>true</code> for an equal element as well. * @param collection the Collection to check * @param element the element to look for * @return <code>true</code> if found, <code>false</code> else */ public static boolean containsInstance(Collection collection, Object element) { if (collection != null) { for (Iterator it = collection.iterator(); it.hasNext();) { Object candidate = it.next(); if (candidate == element) { return true; } } } return false; } /** * Return <code>true</code> if any element in '<code>candidates</code>' is * contained in '<code>source</code>'; otherwise returns <code>false</code>. * @param source the source Collection * @param candidates the candidates to search for * @return whether any of the candidates has been found */ public static boolean containsAny(Collection source, Collection candidates) { if (isEmpty(source) || isEmpty(candidates)) { return false; } for (Iterator it = candidates.iterator(); it.hasNext();) { if (source.contains(it.next())) { return true; } } return false; } /** * Return the first element in '<code>candidates</code>' that is contained in * '<code>source</code>'. If no element in '<code>candidates</code>' is present in * '<code>source</code>' returns <code>null</code>. Iteration order is * {@link Collection} implementation specific. * @param source the source Collection * @param candidates the candidates to search for * @return the first present object, or <code>null</code> if not found */ public static Object findFirstMatch(Collection source, Collection candidates) { if (isEmpty(source) || isEmpty(candidates)) { return null; } for (Iterator it = candidates.iterator(); it.hasNext();) { Object candidate = it.next(); if (source.contains(candidate)) { return candidate; } } return null; } /** * Find a single value of the given type in the given Collection. * @param collection the Collection to search * @param type the type to look for * @return a value of the given type found if there is a clear match, * or <code>null</code> if none or more than one such value found */ public static Object findValueOfType(Collection collection, Class type) { if (isEmpty(collection)) { return null; } Object value = null; for (Iterator it = collection.iterator(); it.hasNext();) { Object obj = it.next(); if (type == null || type.isInstance(obj)) { if (value != null) { // More than one value found... no clear single value. return null; } value = obj; } } return value; } /** * Find a single value of one of the given types in the given Collection: * searching the Collection for a value of the first type, then * searching for a value of the second type, etc. * @param collection the collection to search * @param types the types to look for, in prioritized order * @return a value of one of the given types found if there is a clear match, * or <code>null</code> if none or more than one such value found */ public static Object findValueOfType(Collection collection, Class[] types) { if (isEmpty(collection) || ObjectUtils.isEmpty(types)) { return null; } for (int i = 0; i < types.length; i++) { Object value = findValueOfType(collection, types[i]); if (value != null) { return value; } } return null; } /** * Determine whether the given Collection only contains a single unique object. * @param collection the Collection to check * @return <code>true</code> if the collection contains a single reference or * multiple references to the same instance, <code>false</code> else */ public static boolean hasUniqueObject(Collection collection) { if (isEmpty(collection)) { return false; } boolean hasCandidate = false; Object candidate = null; for (Iterator it = collection.iterator(); it.hasNext();) { Object elem = it.next(); if (!hasCandidate) { hasCandidate = true; candidate = elem; } else if (candidate != elem) { return false; } } return true; } }
codeApeFromChina/resource
frame_packages/java_libs/spring-2.5.6-src/src/org/springframework/util/CollectionUtils.java
Java
unlicense
8,998
/** * This is a demo class * * @author Ravi */ public class Demo { /** * This is the main method * * @param args */ public static void main(String[] args) { System.out.println("This is a demo."); } }
PatchRowcester/LearningJava
Demo/src/Demo.java
Java
unlicense
239
package com.github.alkedr.matchers.reporting.reporters; import org.junit.Test; import static com.github.alkedr.matchers.reporting.reporters.Reporters.noOpSafeTreeReporter; import static com.github.alkedr.matchers.reporting.reporters.Reporters.noOpSimpleTreeReporter; public class NoOpReportersTest { @Test public void noOpSafeTreeReporter_methodsShouldNotUseArgumentsOrThrow() { SafeTreeReporter reporter = noOpSafeTreeReporter(); reporter.presentNode(null, null, null); reporter.absentNode(null, null); reporter.brokenNode(null, null, null); callAllFlatReporterMethods(reporter); } @Test public void noOpSimpleTreeReporter_methodsShouldNotUseArgumentsOrThrow() { SimpleTreeReporter reporter = noOpSimpleTreeReporter(); reporter.beginPresentNode(null, null); reporter.beginAbsentNode(null); reporter.beginBrokenNode(null, null); reporter.endNode(); callAllFlatReporterMethods(reporter); } private static void callAllFlatReporterMethods(FlatReporter reporter) { reporter.correctlyPresent(); reporter.correctlyAbsent(); reporter.incorrectlyPresent(); reporter.incorrectlyAbsent(); reporter.passedCheck(null); reporter.failedCheck(null, null); reporter.checkForAbsentItem(null); reporter.brokenCheck(null, null); } }
alkedr/reporting-matchers
src/test/java/com/github/alkedr/matchers/reporting/reporters/NoOpReportersTest.java
Java
unlicense
1,403
package crashreporter.api; import java.util.ArrayList; import java.util.Collection; import java.util.Collections; import java.util.HashMap; import java.util.List; import java.util.Map; /** * Registry for API provider objects. * * @author Richard */ public class Registry { private static final Map<String, PastebinProvider> pastebinProviders = new HashMap<String, PastebinProvider>(); private static final Map<String, Class<? extends NotificationProvider>> notificationProviders = new HashMap<String, Class<? extends NotificationProvider>>(); /** * Register a {@link PastebinProvider}. * * @param id ID name for the provider, used in the config file * @param provider The provider */ public static void registerPastebinProvider(String id, PastebinProvider provider) { if (pastebinProviders.containsKey(id)) throw new IllegalArgumentException("Pastebin provider " + id + " already registered by " + pastebinProviders.get(id) + " when registering " + provider); pastebinProviders.put(id, provider); } /** * Get a {@link PastebinProvider} by its ID. * * @param id ID name for the provider * @return The provider, or null if there is no such provider */ public static PastebinProvider getPastebinProvider(String id) { return pastebinProviders.get(id); } /** * Get a list of {@link PastebinProvider}s, the first one being the user's preferred pastebin. * * @return List of providers */ public static List<PastebinProvider> getPastebinProviders() { List<PastebinProvider> providers = new ArrayList<PastebinProvider>(pastebinProviders.size()); // first the preferred one PastebinProvider preferred = CallHandler.instance.getPastebin(); if (preferred != null) providers.add(preferred); // then the rest providers.addAll(pastebinProviders.values()); return providers; } /** * Get a map of all {@link PastebinProvider}s, in no particular order. * * @return Map of providers */ public static Map<String, PastebinProvider> getAllPastebinProviders() { return Collections.unmodifiableMap(pastebinProviders); } /** * Register a {@link NotificationProvider} class. * * @param id ID name for the provider, used in the config file * @param provider The provider class */ public static void registerNotificationProvider(String id, Class<? extends NotificationProvider> provider) { if (notificationProviders.containsKey(id)) throw new IllegalArgumentException("Notification provider " + id + " already registered by " + notificationProviders.get(id) + " when registering " + provider); notificationProviders.put(id, provider); } /** * Get a {@link NotificationProvider} class by its ID. * * @param id ID name for the provider class * @return The provider class, or null if there is no such provider */ public static Class<? extends NotificationProvider> getNotificationProvider(String id) { return notificationProviders.get(id); } /** * Get a list of {@link NotificationProvider} classes. * * @return List of provider classes * @see CallHandler#getActiveNotificationProviders() */ public static List<Class<? extends NotificationProvider>> getNotificationProviders() { List<Class<? extends NotificationProvider>> providers = new ArrayList<Class<? extends NotificationProvider>>(notificationProviders.size()); providers.addAll(notificationProviders.values()); return providers; } /** * Get a map of all {@link NotificationProvider} classes. * * @return Map of provider classes * @see CallHandler#getActiveNotificationProviders() */ public static Map<String, Class<? extends NotificationProvider>> getAllNotificationProviders() { return Collections.unmodifiableMap(notificationProviders); } }
richardg867/CrashReporter
src/crashreporter/api/Registry.java
Java
unlicense
3,754
package gui.dragndrop; import javafx.application.Application; import javafx.scene.Scene; import javafx.scene.control.*; import javafx.scene.input.*; import javafx.scene.layout.*; import javafx.scene.paint.Color; import javafx.stage.Stage; public class DragAndDrop extends Application { public void start(Stage stage) { AnchorPane root = new AnchorPane(); Label source = new Label("DRAG ME"); source.setLayoutX(50); source.setLayoutY(100); source.setScaleX(2.0); source.setScaleY(2.0); root.getChildren().add(source); Label target = new Label("DROP HERE"); target.setLayoutX(250); target.setLayoutY(100); target.setScaleX(2.0); target.setScaleY(2.0); root.getChildren().add(target); source.setOnDragDetected(e->onDragDetected(e)); target.setOnDragOver(e->onDragOver(e)); target.setOnDragEntered(e->onDragEntered(e)); target.setOnDragExited(e->onDragExited(e)); target.setOnDragDropped(e->onDragDropped(e)); source.setOnDragDone(e->onDragDone(e)); Scene scene = new Scene(root, 400, 200); stage.setScene(scene); stage.setTitle("Drag and Drop"); stage.show(); } private void onDragDetected(MouseEvent e) { System.out.println("onDragDetected"); Label source = (Label)e.getSource(); Dragboard db = source.startDragAndDrop(TransferMode.ANY); ClipboardContent content = new ClipboardContent(); content.putString(source.getText()); db.setContent(content); } private void onDragOver(DragEvent e) { System.out.println("onDragOver"); Label target = (Label)e.getSource(); if(e.getGestureSource() != target && e.getDragboard().hasString()) { e.acceptTransferModes(TransferMode.COPY_OR_MOVE); } } private void onDragEntered(DragEvent e) { System.out.println("onDragEntered"); Label target = (Label)e.getSource(); if(e.getGestureSource() != target && e.getDragboard().hasString()) { target.setTextFill(Color.RED); } } private void onDragExited(DragEvent e) { System.out.println("onDragExited"); Label target = (Label)e.getSource(); target.setTextFill(Color.BLACK); } private void onDragDropped(DragEvent e) { System.out.println("onDragDropped"); Label target = (Label)e.getSource(); Dragboard db = e.getDragboard(); boolean success = false; if(db.hasString()) { target.setText(db.getString()); success = true; } e.setDropCompleted(success); } private void onDragDone(DragEvent e) { System.out.println("onDragDone"); Label source = (Label)e.getSource(); if (e.getTransferMode() == TransferMode.MOVE) { source.setText(""); } } public static void main(String[] args) { launch(args); } }
KonstantinTwardzik/Graphical-User-Interfaces
CodeExamples/src/gui/dragndrop/DragAndDrop.java
Java
unlicense
3,091
public class Student { private String namn; private int födelseår, status, id; public Student(){} public String getNamn() { return namn; } public void setNamn(String nyNamn) { namn=nyNamn; } public int getId() { return id; } public void setId(int nyId) { id=nyId; } public int getStatus() { return status; } public void setStatus(int nyStatus) { status=nyStatus; } public int getFödelseår() { return födelseår; } public void setFödelseår(int nyFödelseår) { födelseår=nyFödelseår; } public String print() { return namn+"\t"+id+"\t"+födelseår; } }
andreasaronsson/introduktion_till_informatik
tebrakod/Student.java
Java
apache-2.0
589
package com.jerry.controller; import com.jerry.model.TBanquet; import com.jerry.service.BanquetService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RestController; import java.util.List; @RestController @RequestMapping("/banquet") public class BanquetController { @Autowired BanquetService banquetService; @GetMapping("/listBanquetByRestaurantId") public List<TBanquet> listBanquetByRestaurantId(String restaurantId) { return banquetService.listBanquetByRestaurantId(restaurantId); } @GetMapping("/findOne") public TBanquet findOne(String banquetId) { return banquetService.findOne(banquetId); } }
luoyefeiwu/learn_java
jpa/src/main/java/com/jerry/controller/BanquetController.java
Java
apache-2.0
840
/* * Licensed to the Apache Software Foundation (ASF) under one or more contributor license * agreements. See the NOTICE file distributed with this work for additional information regarding * copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance with the License. You may obtain a * copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software distributed under the License * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express * or implied. See the License for the specific language governing permissions and limitations under * the License. */ package net.gcolin.jmx.console.embedded; import net.gcolin.jmx.console.JmxHtml; import net.gcolin.jmx.console.JmxProcessException; import net.gcolin.jmx.console.JmxResult; import net.gcolin.jmx.console.JmxTool; import java.io.IOException; import java.io.Writer; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * A Jmx servlet with bootstrap style. * * @author Gael COLIN * */ public class BootStrapJmxServlet extends HttpServlet { private static final long serialVersionUID = 7998004606230901933L; protected transient JmxTool tool; protected transient JmxHtml html; @Override public void init() throws ServletException { tool = new JmxTool(); html = new JmxHtml() { protected String getButtonCss() { return "btn btn-primary"; } protected String getInputTextClass() { return "form-control"; } protected String getFormClass() { return "form-inline"; } protected String getSelectClass() { return "form-control"; } protected String getMenuUlClass() { return "menu"; } @Override protected String getTableClass() { return "table table-bordered"; } protected void writeCss(Writer writer) throws IOException { writer.write("<link href=\"/css/bootstrap.min.css\" rel=\"stylesheet\" />"); writer.write("<link href=\"/css/bootstrap-theme.min.css\" rel=\"stylesheet\" />"); writer.write("<style type='text/css'>.menu li.active>a{font-weight:bold}" + ".col{display:table-cell}.space{padding-left:16px;}</style>"); } }; } @SuppressWarnings("unchecked") @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Map<String, String> parameters = new HashMap<String, String>(); for (Object elt : req.getParameterMap().entrySet()) { Entry<String, String[]> entry = (Entry<String, String[]>) elt; parameters.put(entry.getKey(), entry.getValue()[0]); } JmxResult result; try { result = tool.build(parameters); } catch (JmxProcessException ex) { throw new ServletException(ex); } result.setRequestUri(req.getRequestURI()); result.setQueryParams(req.getQueryString()); resp.setContentType("text/html"); html.write(result, parameters, resp.getWriter()); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
gcolin/jmx-web-console
jmx-embedded/src/main/java/net/gcolin/jmx/console/embedded/BootStrapJmxServlet.java
Java
apache-2.0
3,657
/** * Copyright 2014 TangoMe Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package com.tango.logstash.flume.redis.sink.serializer; import org.apache.flume.Event; import org.apache.flume.conf.Configurable; import org.apache.flume.conf.ConfigurableComponent; public interface Serializer extends Configurable, ConfigurableComponent { /** * Serialize an event for storage in Redis * * @param event * Event to serialize * @return Serialized data */ byte[] serialize(Event event) throws RedisSerializerException; }
DevOps-TangoMe/flume-redis
flume-redis-sink/src/main/java/com/tango/logstash/flume/redis/sink/serializer/Serializer.java
Java
apache-2.0
1,070
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.commons.io.output; import java.io.IOException; import java.io.OutputStream; /** * Classic splitter of OutputStream. Named after the unix 'tee' * command. It allows a stream to be branched off so there * are now two streams. * */ public class TeeOutputStream extends ProxyOutputStream { /** the second OutputStream to write to */ protected OutputStream branch; //TODO consider making this private /** * Constructs a TeeOutputStream. * @param out the main OutputStream * @param branch the second OutputStream */ public TeeOutputStream(final OutputStream out, final OutputStream branch) { super(out); this.branch = branch; } /** * Write the bytes to both streams. * @param b the bytes to write * @throws IOException if an I/O error occurs */ @Override public synchronized void write(final byte[] b) throws IOException { super.write(b); this.branch.write(b); } /** * Write the specified bytes to both streams. * @param b the bytes to write * @param off The start offset * @param len The number of bytes to write * @throws IOException if an I/O error occurs */ @Override public synchronized void write(final byte[] b, final int off, final int len) throws IOException { super.write(b, off, len); this.branch.write(b, off, len); } /** * Write a byte to both streams. * @param b the byte to write * @throws IOException if an I/O error occurs */ @Override public synchronized void write(final int b) throws IOException { super.write(b); this.branch.write(b); } /** * Flushes both streams. * @throws IOException if an I/O error occurs */ @Override public void flush() throws IOException { super.flush(); this.branch.flush(); } /** * Closes both output streams. * * If closing the main output stream throws an exception, attempt to close the branch output stream. * * If closing the main and branch output streams both throw exceptions, which exceptions is thrown by this method is * currently unspecified and subject to change. * * @throws IOException * if an I/O error occurs */ @Override public void close() throws IOException { try { super.close(); } finally { this.branch.close(); } } }
pimtegelaar/commons-io-test3
src/main/java/org/apache/commons/io/output/TeeOutputStream.java
Java
apache-2.0
3,320
package org.renjin.primitives; import org.renjin.eval.Context; import org.renjin.eval.EvalException; import org.renjin.primitives.annotations.processor.ArgumentException; import org.renjin.primitives.annotations.processor.ArgumentIterator; import org.renjin.primitives.annotations.processor.WrapperRuntime; import org.renjin.primitives.files.Files; import org.renjin.sexp.BuiltinFunction; import org.renjin.sexp.DoubleVector; import org.renjin.sexp.Environment; import org.renjin.sexp.FunctionCall; import org.renjin.sexp.IntVector; import org.renjin.sexp.LogicalVector; import org.renjin.sexp.PairList; import org.renjin.sexp.SEXP; import org.renjin.sexp.StringVector; public class R$primitive$file$access extends BuiltinFunction { public R$primitive$file$access() { super("file.access"); } public SEXP apply(Context context, Environment environment, FunctionCall call, PairList args) { try { ArgumentIterator argIt = new ArgumentIterator(context, environment, args); SEXP s0 = argIt.evalNext(); SEXP s1 = argIt.evalNext(); if (!argIt.hasNext()) { return this.doApply(context, environment, s0, s1); } throw new EvalException("file.access: too many arguments, expected at most 2."); } catch (ArgumentException e) { throw new EvalException(context, "Invalid argument: %s. Expected:\n\tfile.access(character, integer(1))", e.getMessage()); } catch (EvalException e) { e.initContext(context); throw e; } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new EvalException(e); } } public static SEXP doApply(Context context, Environment environment, FunctionCall call, String[] argNames, SEXP[] args) { try { if ((args.length) == 2) { return doApply(context, environment, args[ 0 ], args[ 1 ]); } } catch (EvalException e) { e.initContext(context); throw e; } catch (RuntimeException e) { throw e; } catch (Exception e) { throw new EvalException(e); } throw new EvalException("file.access: max arity is 2"); } public SEXP apply(Context context, Environment environment, FunctionCall call, String[] argNames, SEXP[] args) { return R$primitive$file$access.doApply(context, environment, call, argNames, args); } public static SEXP doApply(Context context, Environment environment, SEXP arg0, SEXP arg1) throws Exception { if ((arg0 instanceof StringVector)&&(((arg1 instanceof IntVector)||(arg1 instanceof DoubleVector))||(arg1 instanceof LogicalVector))) { return Files.fileAccess(context, ((StringVector) arg0), WrapperRuntime.convertToInt(arg1)); } else { throw new EvalException(String.format("Invalid argument:\n\tfile.access(%s, %s)\n\tExpected:\n\tfile.access(character, integer(1))", arg0 .getTypeName(), arg1 .getTypeName())); } } }
bedatadriven/renjin-statet
org.renjin.core/src-gen/org/renjin/primitives/R$primitive$file$access.java
Java
apache-2.0
3,115