repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
bobisjan/adaptive-restful-api
data/src/main/java/cz/cvut/fel/adaptiverestfulapi/data/GetHandler.java
961
package cz.cvut.fel.adaptiverestfulapi.data; import cz.cvut.fel.adaptiverestfulapi.core.HttpContext; import cz.cvut.fel.adaptiverestfulapi.meta.configuration.Configuration; import cz.cvut.fel.adaptiverestfulapi.meta.model.Entity; /** * Abstract handler for GET method. */ public abstract class GetHandler implements Handler { public static final String Key = GetHandler.class.getName(); /** * Handles GET method. * @param entity The entity. * @param context The HTTP context. * @param configuration The configuration. * @return Processed HTTP context. * @throws DataException */ protected abstract HttpContext get(Entity entity, HttpContext context, Configuration configuration) throws DataException; @Override public final HttpContext handle(Entity entity, HttpContext context, Configuration configuration) throws DataException { return this.get(entity, context, configuration); } }
lgpl-3.0
lburgazzoli/Chronicle-Map
src/main/java/net/openhft/chronicle/hash/ChecksumEntry.java
3180
/* * Copyright (C) 2015 higherfrequencytrading.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. * * 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.openhft.chronicle.hash; import net.openhft.chronicle.map.MapAbsentEntry; import net.openhft.chronicle.map.MapEntry; import net.openhft.chronicle.set.SetEntry; /** * Abstracts entries of hash containers, created by {@link ChronicleHashBuilder}s * with {@link ChronicleHashBuilder#checksumEntries(boolean)} configured to {@code true}. There is * no method that returns {@code ChecksumEntry}, {@link MapEntry} or {@link SetEntry} could be * <i>casted</i> to {@code ChecksumEntry} to access it's methods. * * <p>See <a href="https://github.com/OpenHFT/Chronicle-Map#entry-checksums">Entry checksums</a> * section in the Chronicle Map tutorial for usage examples of this interface. */ public interface ChecksumEntry { /** * Re-computes and stores checksum for the entry. This method <i>shouldn't</i> be called before * or after ordinary operations like {@link MapAbsentEntry#doInsert(Data)}, {@link * MapEntry#doReplaceValue(Data)}: it is performed automatically underneath. Call this method, * only when value bytes was updated directly, for example though flyweight implementation of * a <a href="https://github.com/OpenHFT/Chronicle-Values#value-interface-specification">value * interface</a>. * * @throws UnsupportedOperationException if checksums are not stored in the containing Chronicle * Hash * @throws RuntimeException if the context of this entry is locked improperly, e. g. on the * {@linkplain HashQueryContext#readLock() read} level, that is not upgradable to the * {@linkplain HashQueryContext#updateLock() update} level. Calling {@code updateChecksum()} * method is enabled when at least update lock is held. */ void updateChecksum(); /** * Computes checksum from the entry bytes and checks whether it is equal to the stored checksum. * * @return {@code true} if stored checksum equals to checksum computed from the entry bytes * @throws UnsupportedOperationException if checksums are not stored in the containing Chronicle * Hash * @throws RuntimeException if the context of this entry is locked improperly, e. g. on the * {@linkplain HashQueryContext#readLock() read} level, that is not upgradable to the * {@linkplain HashQueryContext#updateLock() update} level. Calling {@code checkSum()} method is * enabled when at least update lock is held. */ boolean checkSum(); }
lgpl-3.0
CarlosFMeneses/Project_3-Phase_2
Problem01/StringTooLongException.java
415
/* Carlos F. Meneses 03/30/2015 Bergen Community College Advanced Java Programming Homework Project 3, Phase 2, Problem 1 */ /** StringTooLongException: This exception gets thrown if the user enters a string which has 20 or more characters. (see also: StringApp.java) */ public class StringTooLongException extends Exception { public StringTooLongException() { super ("Check file error.log for errors"); } }
lgpl-3.0
joansmith/sonarqube
server/sonar-server/src/main/java/org/sonar/server/es/DefaultIndexSettings.java
4331
/* * 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.server.es; import org.elasticsearch.cluster.metadata.IndexMetaData; import org.elasticsearch.common.settings.ImmutableSettings; class DefaultIndexSettings { private DefaultIndexSettings() { // only static stuff } static ImmutableSettings.Builder defaults() { return ImmutableSettings.builder() .put(IndexMetaData.SETTING_NUMBER_OF_SHARDS, 1) .put(IndexMetaData.SETTING_NUMBER_OF_REPLICAS, 0) .put("index.refresh_interval", "30s") .put("index.mapper.dynamic", false) // Sortable text analyzer .put("index.analysis.analyzer.sortable.type", "custom") .put("index.analysis.analyzer.sortable.tokenizer", "keyword") .putArray("index.analysis.analyzer.sortable.filter", "trim", "lowercase") // Edge NGram index-analyzer .put("index.analysis.analyzer.index_grams.type", "custom") .put("index.analysis.analyzer.index_grams.tokenizer", "whitespace") .putArray("index.analysis.analyzer.index_grams.filter", "trim", "lowercase", "gram_filter") // Edge NGram search-analyzer .put("index.analysis.analyzer.search_grams.type", "custom") .put("index.analysis.analyzer.search_grams.tokenizer", "whitespace") .putArray("index.analysis.analyzer.search_grams.filter", "trim", "lowercase") // Word index-analyzer .put("index.analysis.analyzer.index_words.type", "custom") .put("index.analysis.analyzer.index_words.tokenizer", "standard") .putArray("index.analysis.analyzer.index_words.filter", "standard", "word_filter", "lowercase", "stop", "asciifolding", "porter_stem") // Word search-analyzer .put("index.analysis.analyzer.search_words.type", "custom") .put("index.analysis.analyzer.search_words.tokenizer", "standard") .putArray("index.analysis.analyzer.search_words.filter", "standard", "lowercase", "stop", "asciifolding", "porter_stem") // Edge NGram filter .put("index.analysis.filter.gram_filter.type", "edgeNGram") .put("index.analysis.filter.gram_filter.min_gram", 2) .put("index.analysis.filter.gram_filter.max_gram", 15) .putArray("index.analysis.filter.gram_filter.token_chars", "letter", "digit", "punctuation", "symbol") // Word filter .put("index.analysis.filter.word_filter.type", "word_delimiter") .put("index.analysis.filter.word_filter.generate_word_parts", true) .put("index.analysis.filter.word_filter.catenate_words", true) .put("index.analysis.filter.word_filter.catenate_numbers", true) .put("index.analysis.filter.word_filter.catenate_all", true) .put("index.analysis.filter.word_filter.split_on_case_change", true) .put("index.analysis.filter.word_filter.preserve_original", true) .put("index.analysis.filter.word_filter.split_on_numerics", true) .put("index.analysis.filter.word_filter.stem_english_possessive", true) // Path Analyzer .put("index.analysis.analyzer.path_analyzer.type", "custom") .put("index.analysis.analyzer.path_analyzer.tokenizer", "path_hierarchy") // UUID Module analyzer .put("index.analysis.tokenizer.dot_tokenizer.type", "pattern") .put("index.analysis.tokenizer.dot_tokenizer.pattern", "\\.") .put("index.analysis.analyzer.uuid_analyzer.type", "custom") .putArray("index.analysis.analyzer.uuid_analyzer.filter", "trim") .put("index.analysis.analyzer.uuid_analyzer.tokenizer", "dot_tokenizer"); } }
lgpl-3.0
koca2000/NoteBlockAPI
src/main/java/com/xxmicloxx/NoteBlockAPI/NoteBlockSongPlayer.java
4060
package com.xxmicloxx.NoteBlockAPI; import com.xxmicloxx.NoteBlockAPI.utils.InstrumentUtils; import org.bukkit.Bukkit; import org.bukkit.block.Block; import org.bukkit.entity.Player; /** * @deprecated {@link com.xxmicloxx.NoteBlockAPI.songplayer.NoteBlockSongPlayer} */ @Deprecated public class NoteBlockSongPlayer extends SongPlayer { private Block noteBlock; private int distance = 16; public NoteBlockSongPlayer(Song song) { super(song); makeNewClone(com.xxmicloxx.NoteBlockAPI.songplayer.NoteBlockSongPlayer.class); } public NoteBlockSongPlayer(Song song, SoundCategory soundCategory) { super(song, soundCategory); makeNewClone(com.xxmicloxx.NoteBlockAPI.songplayer.NoteBlockSongPlayer.class); } public NoteBlockSongPlayer(com.xxmicloxx.NoteBlockAPI.songplayer.SongPlayer songPlayer) { super(songPlayer); } @Override void update(String key, Object value) { super.update(key, value); switch (key){ case "distance": distance = (int) value; break; case "noteBlock": noteBlock = (Block) value; break; } } /** * Get the Block this SongPlayer is played at * @return Block representing a NoteBlock */ public Block getNoteBlock() { return noteBlock; } /** * Set the Block this SongPlayer is played at */ public void setNoteBlock(Block noteBlock) { this.noteBlock = noteBlock; CallUpdate("noteBlock", noteBlock); } @Override public void playTick(Player player, int tick) { if (noteBlock.getType() != com.xxmicloxx.NoteBlockAPI.utils.CompatibilityUtils.getNoteBlockMaterial()) { return; } if (!player.getWorld().getName().equals(noteBlock.getWorld().getName())) { // not in same world return; } byte playerVolume = NoteBlockAPI.getPlayerVolume(player); for (Layer layer : song.getLayerHashMap().values()) { Note note = layer.getNote(tick); if (note == null) { continue; } player.playNote(noteBlock.getLocation(), InstrumentUtils.getBukkitInstrument(note.getInstrument()), new org.bukkit.Note(note.getKey() - 33)); float volume = ((layer.getVolume() * (int) this.volume * (int) playerVolume) / 1000000F) * ((1F / 16F) * getDistance()); float pitch = NotePitch.getPitch(note.getKey() - 33); if (InstrumentUtils.isCustomInstrument(note.getInstrument())) { CustomInstrument instrument = song.getCustomInstruments() [note.getInstrument() - InstrumentUtils.getCustomInstrumentFirstIndex()]; if (instrument.getSound() != null) { CompatibilityUtils.playSound(player, noteBlock.getLocation(), instrument.getSound(), this.soundCategory, volume, pitch); } else { CompatibilityUtils.playSound(player, noteBlock.getLocation(), instrument.getSoundfile(), this.soundCategory, volume, pitch); } } else { CompatibilityUtils.playSound(player, noteBlock.getLocation(), InstrumentUtils.getInstrument(note.getInstrument()), this.soundCategory, volume, pitch); } if (isPlayerInRange(player)) { if (!this.playerList.get(player.getName())) { playerList.put(player.getName(), true); Bukkit.getPluginManager().callEvent(new PlayerRangeStateChangeEvent(this, player, true)); } } else { if (this.playerList.get(player.getName())) { playerList.put(player.getName(), false); Bukkit.getPluginManager().callEvent(new PlayerRangeStateChangeEvent(this, player, false)); } } } } /** * Sets distance in blocks where would be player able to hear sound. * @param distance (Default 16 blocks) */ public void setDistance(int distance) { this.distance = distance; CallUpdate("distance", distance); } public int getDistance() { return distance; } /** * Returns true if the Player is able to hear the current NoteBlockSongPlayer * @param player in range * @return ability to hear the current NoteBlockSongPlayer */ @Deprecated public boolean isPlayerInRange(Player player) { if (player.getLocation().distance(noteBlock.getLocation()) > getDistance()) { return false; } else { return true; } } }
lgpl-3.0
racodond/sonar-css-plugin
css-frontend/src/main/java/org/sonar/css/model/property/standard/OverflowX.java
1311
/* * SonarQube CSS / SCSS / Less Analyzer * Copyright (C) 2013-2017 David RACODON * mailto: david.racodon@gmail.com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.css.model.property.standard; import org.sonar.css.model.property.StandardProperty; import org.sonar.css.model.property.validator.valueelement.OverflowValidator; public class OverflowX extends StandardProperty { public OverflowX() { addLinks( "https://drafts.csswg.org/css-overflow-3/#propdef-overflow-x", "http://dev.w3.org/csswg/css-box-3/#overflow-x"); addValidators(new OverflowValidator()); } }
lgpl-3.0
Dev4Ninja/mvo4j
src/main/java/br/com/d4n/mvo/ioc/PostConstruct.java
1076
package br.com.d4n.mvo.ioc; /* * #%L * mvo4j * %% * Copyright (C) 2012 - 2015 DevFor Ninjas * %% * 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/>. * #L% */ import java.lang.annotation.ElementType; import java.lang.annotation.Inherited; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Inherited @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) public @interface PostConstruct { }
lgpl-3.0
benothman/jboss-web-nio2
java/org/apache/el/parser/ELParserTreeConstants.java
1838
/* Generated By:JavaCC: Do not edit this line. ELParserTreeConstants.java Version 5.0 */ package org.apache.el.parser; public interface ELParserTreeConstants { public int JJTCOMPOSITEEXPRESSION = 0; public int JJTLITERALEXPRESSION = 1; public int JJTDEFERREDEXPRESSION = 2; public int JJTDYNAMICEXPRESSION = 3; public int JJTVOID = 4; public int JJTCHOICE = 5; public int JJTOR = 6; public int JJTAND = 7; public int JJTEQUAL = 8; public int JJTNOTEQUAL = 9; public int JJTLESSTHAN = 10; public int JJTGREATERTHAN = 11; public int JJTLESSTHANEQUAL = 12; public int JJTGREATERTHANEQUAL = 13; public int JJTPLUS = 14; public int JJTMINUS = 15; public int JJTMULT = 16; public int JJTDIV = 17; public int JJTMOD = 18; public int JJTNEGATIVE = 19; public int JJTNOT = 20; public int JJTEMPTY = 21; public int JJTVALUE = 22; public int JJTDOTSUFFIX = 23; public int JJTBRACKETSUFFIX = 24; public int JJTIDENTIFIER = 25; public int JJTFUNCTION = 26; public int JJTTRUE = 27; public int JJTFALSE = 28; public int JJTFLOATINGPOINT = 29; public int JJTINTEGER = 30; public int JJTSTRING = 31; public int JJTNULL = 32; public String[] jjtNodeName = { "CompositeExpression", "LiteralExpression", "DeferredExpression", "DynamicExpression", "void", "Choice", "Or", "And", "Equal", "NotEqual", "LessThan", "GreaterThan", "LessThanEqual", "GreaterThanEqual", "Plus", "Minus", "Mult", "Div", "Mod", "Negative", "Not", "Empty", "Value", "DotSuffix", "BracketSuffix", "Identifier", "Function", "True", "False", "FloatingPoint", "Integer", "String", "Null", }; } /* JavaCC - OriginalChecksum=f9dfeaba39219034209bcc010ceeafc5 (do not edit this line) */
lgpl-3.0
almondtools/comtemplate
src/main/java/net/amygdalum/comtemplate/engine/TemplateExpressionVisitor.java
3564
package net.amygdalum.comtemplate.engine; import net.amygdalum.comtemplate.engine.expressions.BooleanLiteral; import net.amygdalum.comtemplate.engine.expressions.Cast; import net.amygdalum.comtemplate.engine.expressions.Concat; import net.amygdalum.comtemplate.engine.expressions.DecimalLiteral; import net.amygdalum.comtemplate.engine.expressions.Defaulted; import net.amygdalum.comtemplate.engine.expressions.ErrorExpression; import net.amygdalum.comtemplate.engine.expressions.EvalAnonymousTemplate; import net.amygdalum.comtemplate.engine.expressions.EvalAttribute; import net.amygdalum.comtemplate.engine.expressions.EvalContextVar; import net.amygdalum.comtemplate.engine.expressions.EvalFunction; import net.amygdalum.comtemplate.engine.expressions.EvalTemplate; import net.amygdalum.comtemplate.engine.expressions.EvalTemplateFunction; import net.amygdalum.comtemplate.engine.expressions.EvalTemplateMixed; import net.amygdalum.comtemplate.engine.expressions.EvalVar; import net.amygdalum.comtemplate.engine.expressions.EvalVirtual; import net.amygdalum.comtemplate.engine.expressions.Evaluated; import net.amygdalum.comtemplate.engine.expressions.Exists; import net.amygdalum.comtemplate.engine.expressions.IgnoreErrors; import net.amygdalum.comtemplate.engine.expressions.IntegerLiteral; import net.amygdalum.comtemplate.engine.expressions.ListLiteral; import net.amygdalum.comtemplate.engine.expressions.MapLiteral; import net.amygdalum.comtemplate.engine.expressions.NativeObject; import net.amygdalum.comtemplate.engine.expressions.RawText; import net.amygdalum.comtemplate.engine.expressions.ResolvedListLiteral; import net.amygdalum.comtemplate.engine.expressions.ResolvedMapLiteral; import net.amygdalum.comtemplate.engine.expressions.StringLiteral; import net.amygdalum.comtemplate.engine.expressions.ToObject; public interface TemplateExpressionVisitor<T> { T visitRawText(RawText rawText, Scope scope); T visitEvalVar(EvalVar evalVar, Scope scope); T visitEvalContextVar(EvalContextVar evalContextVar, Scope scope); T visitEvalTemplate(EvalTemplate evalTemplate, Scope scope); T visitEvalTemplateFunction(EvalTemplateFunction evalTemplateFunction, Scope scope); T visitEvalTemplateMixed(EvalTemplateMixed evalTemplateMixed, Scope scope); T visitEvalAnonymousTemplate(EvalAnonymousTemplate evalAnonymousTemplate, Scope scope); T visitEvalAttribute(EvalAttribute evalAttribute, Scope scope); T visitEvalVirtual(EvalVirtual evalAttribute, Scope scope); T visitEvalFunction(EvalFunction evalFunction, Scope scope); T visitEvaluated(Evaluated evaluated, Scope scope); T visitIgnoreErrors(IgnoreErrors ignoreErrors, Scope scope); T visitExists(Exists exists, Scope scope); T visitDefaulted(Defaulted defaulted, Scope scope); T visitConcat(Concat concat, Scope scope); T visitToObject(ToObject toObject, Scope scope); T visitMapLiteral(MapLiteral mapLiteral, Scope scope); T visitMapLiteral(ResolvedMapLiteral mapLiteral, Scope scope); T visitListLiteral(ListLiteral listLiteral, Scope scope); T visitListLiteral(ResolvedListLiteral listLiteral, Scope scope); T visitStringLiteral(StringLiteral stringLiteral, Scope scope); T visitIntegerLiteral(IntegerLiteral integerLiteral, Scope scope); T visitDecimalLiteral(DecimalLiteral decimalLiteral, Scope scope); T visitBooleanLiteral(BooleanLiteral booleanLiteral, Scope scope); T visitNativeObject(NativeObject nativeObject, Scope scope); T visitCast(Cast cast, Scope scope); T visitErrorExpression(ErrorExpression errorExpression, Scope scope); }
lgpl-3.0
glidernet/ogn-commons-java
src/main/java/org/ogn/commons/igc/IgcLogger.java
11674
/** * Copyright (c) 2014 OGN, All Rights Reserved. */ package org.ogn.commons.igc; import java.io.File; import java.io.FileWriter; import java.io.IOException; import java.time.Instant; import java.time.LocalDate; import java.time.LocalTime; import java.time.ZoneOffset; import java.time.ZonedDateTime; import java.util.Optional; import java.util.concurrent.BlockingQueue; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; import java.util.concurrent.LinkedBlockingQueue; import javax.annotation.PostConstruct; import org.ogn.commons.beacon.AircraftBeacon; import org.ogn.commons.beacon.AircraftDescriptor; import org.ogn.commons.utils.AprsUtils; import org.ogn.commons.utils.AprsUtils.Coordinate; import org.ogn.commons.utils.IgcUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * The IGC logger creates and writes to IGC files. The logger's log() operation is non-blocking (logs are written to a * file by a background thread) * * @author wbuczak */ public class IgcLogger { public enum Mode { ASYNC, SYNC } private static final Logger LOG = LoggerFactory.getLogger(IgcLogger.class); private static final String DEFAULT_IGC_BASE_DIR = "log"; private final String igcBaseDir; private static final String LINE_SEP = System.lineSeparator(); private final Mode workingMode; private BlockingQueue<LogRecord> logRecords; private volatile Future<?> pollerFuture; private ExecutorService executor; private static class LogRecord { AircraftBeacon beacon; Optional<AircraftDescriptor> descriptor; Optional<LocalDate> date; public LogRecord(AircraftBeacon beacon, Optional<LocalDate> date, Optional<AircraftDescriptor> descriptor) { this.beacon = beacon; this.descriptor = descriptor; this.date = date; } } public int getQueueSize() { return this.logRecords.size(); } private class PollerTask implements Runnable { @Override public void run() { LOG.trace("starting..."); LogRecord record = null; while (!Thread.interrupted()) { try { record = logRecords.take(); logToIgcFile(record.beacon, record.date, record.descriptor); } catch (final InterruptedException e) { LOG.trace("interrupted exception caught. Was the poller task interrupted on purpose?"); Thread.currentThread().interrupt(); continue; } catch (final Exception e) { LOG.error("exception caught", e); continue; } } // while LOG.trace("exiting.."); } } @PostConstruct private void logConf() { LOG.info("created igc logger [log-folder: {}, mode: {}]", igcBaseDir, workingMode); } public IgcLogger(Mode mode) { this(DEFAULT_IGC_BASE_DIR, mode); } public IgcLogger(final String logsFolder, Mode mode) { igcBaseDir = logsFolder; workingMode = mode; if (workingMode == Mode.ASYNC) { logRecords = new LinkedBlockingQueue<>(); executor = Executors.newSingleThreadExecutor(); pollerFuture = executor.submit(new PollerTask()); } } public IgcLogger() { this(DEFAULT_IGC_BASE_DIR, Mode.ASYNC); } public IgcLogger(final String logsFolder) { this(logsFolder, Mode.ASYNC); } private void writeIgcHeader(FileWriter igcFile, ZonedDateTime datetime, Optional<AircraftDescriptor> descriptor) { // Write IGC file header final StringBuilder bld = new StringBuilder(); try { bld.append("AGNE001 OGN gateway").append(LINE_SEP); bld.append("HFDTE").append(String.format("%02d", datetime.getDayOfMonth())) .append(String.format("%02d", datetime.getMonthValue())) .append(String.format("%04d", datetime.getYear()).substring(2)); // last // 2 // chars // of // the // year if (descriptor.isPresent()) bld.append(LINE_SEP).append("HFGIDGLIDERID:").append(descriptor.get().getRegNumber()).append(LINE_SEP) .append("HFGTYGLIDERTYPE:").append(descriptor.get().getModel()).append(LINE_SEP) .append("HFCIDCOMPETITIONID:").append(descriptor.get().getCN()).append(LINE_SEP); igcFile.write(bld.toString()); } catch (final IOException e) { LOG.error("exception caught", e); } } private void logToIgcFile(final AircraftBeacon beacon, final Optional<LocalDate> date, final Optional<AircraftDescriptor> descriptor) { final String igcId = IgcUtils.toIgcLogFileId(beacon, descriptor); final LocalDate d = date.isPresent() ? date.get() : LocalDate.now(); final ZonedDateTime beaconTimestamp = ZonedDateTime.ofInstant(Instant.ofEpochMilli(beacon.getTimestamp()), ZoneOffset.UTC); // take the time part from the beacon final ZonedDateTime timestamp = ZonedDateTime.of(d, LocalTime.of(beaconTimestamp.getHour(), beaconTimestamp.getMinute(), beaconTimestamp.getSecond()), ZoneOffset.UTC); final StringBuilder dateString = new StringBuilder(String.format("%04d", timestamp.getYear())).append("-") .append(String.format("%02d", timestamp.getMonth().getValue())).append("-") .append(String.format("%02d", timestamp.getDayOfMonth())); // Generate filename from date and immat final String igcFileName = dateString + "_" + igcId + ".IGC"; final File theDir = new File(igcBaseDir); if (!theDir.exists() && !theDir.mkdir()) { LOG.warn("the directory {} could not be created", theDir); return; } final File subDir = new File(igcBaseDir + File.separatorChar + dateString); if (!subDir.exists()) { // if directory doesn't exist create it if (!subDir.mkdir()) { LOG.warn("the directory {} could not be created", subDir); return; } } final String filePath = igcBaseDir + File.separatorChar + dateString + File.separatorChar + igcFileName; // Check if the IGC file already exist final File f = new File(filePath); boolean writeHeader = false; if (!f.exists()) // if this is a brand new file - write the header writeHeader = true; FileWriter igcFile = null; // create (if not exists) and/or open the file try { igcFile = new FileWriter(filePath, true); } catch (final IOException ex) { LOG.error("exception caught", ex); return; // no point to continue - file could not be created } // if this is a brand new file - write the header if (writeHeader) { // write the igc header writeIgcHeader(igcFile, timestamp, descriptor); } // Add fix try { final StringBuilder bld = new StringBuilder(); // log original APRS sentence to IGC file for debug, SAR & co bld.append("LGNE ").append(beacon.getRawPacket()).append(LINE_SEP); bld.append("B").append(String.format("%02d", timestamp.getHour())) .append(String.format("%02d", timestamp.getMinute())) .append(String.format("%02d", timestamp.getSecond())) .append(AprsUtils.degToIgc(beacon.getLat(), Coordinate.LAT)) .append(AprsUtils.degToIgc(beacon.getLon(), Coordinate.LON)).append("A") // A // for // 3D // fix // (and // not // 2D) .append("00000") // baro. altitude (but it is false as we // have only GPS altitude .append(String.format("%05.0f", beacon.getAlt())) // GPS // altitude .append(LINE_SEP); igcFile.write(bld.toString()); } catch (final IOException e) { LOG.error("exception caught", e); } finally { try { igcFile.close(); } catch (final Exception ex) { LOG.warn("could not close igc file", ex); } } } /** * @param immat * aircraft registration (if known) or unique tracker/flarm id * @param lat * latitude * @param lon * longitude * @param alt * altitude * @param comment * a string which will fall into the igc file as a comment (e.g. aprs sentence can be logged for * debugging purposes) */ public void log(final AircraftBeacon beacon, final Optional<LocalDate> date, final Optional<AircraftDescriptor> descriptor) { switch (workingMode) { case ASYNC: if (!logRecords.offer(new LogRecord(beacon, date, descriptor))) { LOG.warn("could not insert LogRecord to the igc logging queue"); } break; default: logToIgcFile(beacon, date, descriptor); } } public void log(final AircraftBeacon beacon, final Optional<AircraftDescriptor> descriptor) { log(beacon, Optional.empty(), descriptor); } /** * can be used to stop the poller thread. only affects IgcLogger in ASYNC mode */ public void stop() { if (pollerFuture != null) { pollerFuture.cancel(false); } } } /* * From IGC spec (http://www.fai.org/gnss-recording-devices/igc-approved-flight-recorders): * * Altitude - Metres, separate records for GNSS and pressure altitudes. Date (of the first line in the B record) - UTC * DDMMYY (day, month, year). Latitude and Longitude - Degrees, minutes and decimal minutes to three decimal places, * with N,S,E,W designators Time - UTC, for source, see para 3.4 in the main body in this document. Note that UTC is not * the same as the internal system time in the U.S. GPS system, see under "GPS system time" in the Glossary. * * --- * * Altitude - AAAAAaaa AAAAA - fixed to 5 digits with leading 0 aaa - where used, the number of altitude decimals (the * number of fields recorded are those available for altitude in the Record concerned, less fields already used for * AAAAA) Altitude, GNSS. Where GNSS altitude is not available from GNSS position-lines such as in the case of a 2D fix * (altitude drop-out), it shall be recorded in the IGC format file as zero so that the lack of valid GNSS altitude can * be clearly seen during post-flight analysis. * * Date - DDMMYY DD - number of the day in the month, fixed to 2 digits with leading 0 where necessary MM - number of * the month in year, fixed to 2 digits with leading 0 where necessary YY - number of the year, fixed to 2 digits with * leading 0 where necessary * * Lat/Long - D D M M m m m N D D D M M m m m E DD - Latitude degrees with leading 0 where necessary DDD - Longitude * degrees with leading 0 or 00 where necessary MMmmmNSEW - Lat/Long minutes with leading 0 where necessary, 3 decimal * places of minutes (mandatory, not optional), followed by North, South, East or West letter as appropriate * * Time - HHMMSS (UTC) - for optional decimal seconds see "s" below HH - Hours fixed to 2 digits with leading 0 where * necessary MM - Minutes fixed to 2 digits with leading 0 where necessary SS - Seconds fixed to 2 digits with leading 0 * where necessary s - number of decimal seconds (if used), placed after seconds (SS above). If the recorder uses fix * intervals of less than one second, the extra number(s) are added in the B-record line, their position on the line * being identified in the I-record under the Three Letter Code TDS (Time Decimal Seconds, see the codes in para A7). * One number "s" indicates tenths of seconds and "ss" is tenths and hundredths, and so forth. If tenths are used at, * for instance, character number 49 in the B-record (after other codes such as FXA, SIU, ENL), this is indicated in the * I record as: "4949TDS". * * B HHMMSS DDMMmmmN DDDMMmmmE V PPPPP GGGGG CR LF B 130353 4344108N 00547165E A 00275 00275 4533.12N 00559.93E * * Condor example: HFDTE140713 HFGIDGLIDERID:F-SEB B1303534344108N00547165EA0027500275 */
lgpl-3.0
cybertiger/Bukkit-Instances
instances-core/src/main/java/org/cyberiantiger/minecraft/instances/util/DependencyFactory.java
2015
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.cyberiantiger.minecraft.instances.util; import java.util.logging.Level; import org.bukkit.plugin.Plugin; /** * * @author antony */ public abstract class DependencyFactory<P extends Plugin, T extends Dependency> { private final P thisPlugin; private final String plugin; private boolean cannotLoad = false; private T dependency; public DependencyFactory(P thisPlugin, String plugin) { this.thisPlugin = thisPlugin; this.plugin = plugin; } public final String getPlugin() { return plugin; } public final P getThisPlugin() { return thisPlugin; } public final T getDependecy() { Plugin depPlugin; if (plugin.equals(thisPlugin.getName())) { depPlugin = thisPlugin; if (dependency != null) { return dependency; } } else { depPlugin = thisPlugin.getServer().getPluginManager().getPlugin(plugin); if (depPlugin == null || !depPlugin.isEnabled()) { dependency = null; return null; } if (dependency != null) { if (dependency.getPlugin() != depPlugin) { dependency = null; } else { return dependency; } } if (cannotLoad) { return dependency; } } try { dependency = createInterface(depPlugin); } catch (Throwable ex) { cannotLoad = true; thisPlugin.getLogger().log(Level.WARNING, "Error loading dependecy interface " + getInterfaceClass().getName() + " for plugin " + plugin, ex); } return dependency; } public abstract Class<T> getInterfaceClass(); protected abstract T createInterface(Plugin plugin) throws Exception; }
lgpl-3.0
biotextmining/processes
src/main/java/com/silicolife/textmining/processes/resources/dictionary/loaders/kegg/deprecated/AKeggClassLoader.java
1075
package com.silicolife.textmining.processes.resources.dictionary.loaders.kegg.deprecated; import java.io.BufferedReader; import java.io.File; import java.io.FileReader; import java.io.IOException; import java.util.regex.Matcher; import java.util.regex.Pattern; @Deprecated public abstract class AKeggClassLoader { private Pattern externalID = Pattern.compile("ENTRY\\s+(.+)\\s+?"); public abstract boolean checkFile(File file); public abstract String getClassLoader(); public boolean checkAllFile(File file, String type) { if (!file.isFile()) { return false; } try (FileReader fr = new FileReader(file); BufferedReader br = new BufferedReader(fr)) { String line; int i = 0; while ((line = br.readLine()) != null && i < 100) { Matcher m = externalID.matcher(line); if (m.find()) { if (line.contains(type)) { return true; } else { return false; } } i++; } } catch (IOException e) { e.printStackTrace(); return false; } return false; } }
lgpl-3.0
dana-i2cat/opennaas
core/resources/src/main/java/org/opennaas/core/resources/mock/MockCapAction.java
1724
package org.opennaas.core.resources.mock; /* * #%L * OpenNaaS :: Core :: Resources * %% * Copyright (C) 2007 - 2014 Fundació Privada i2CAT, Internet i Innovació a Catalunya * %% * 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 General Lesser Public License for more details. * * You should have received a copy of the GNU General Lesser Public * License along with this program. If not, see * <http://www.gnu.org/licenses/lgpl-3.0.html>. * #L% */ import org.apache.commons.logging.Log; import org.apache.commons.logging.LogFactory; import org.opennaas.core.resources.action.Action; import org.opennaas.core.resources.action.ActionException; import org.opennaas.core.resources.action.ActionResponse; import org.opennaas.core.resources.protocol.IProtocolSessionManager; public class MockCapAction extends Action { private Log log = LogFactory.getLog(MockCapAction.class); private String actionID; @Override public void setActionID(String actionID) { this.actionID = actionID; } public ActionResponse execute(IProtocolSessionManager protocolSessionManager) throws ActionException { log.info("----> Executing action: MOCK ACTION"); return null; } public boolean checkParams(Object params) throws ActionException { // TODO Auto-generated method stub return false; } }
lgpl-3.0
SonarOpenCommunity/sonar-cxx
cxx-sensors/src/test/java/org/sonar/cxx/sensors/pclint/CxxPCLintSensorTest.java
8573
/* * C++ Community Plugin (cxx plugin) * Copyright (C) 2010-2022 SonarOpenCommunity * http://github.com/SonarOpenCommunity/sonar-cxx * * 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.cxx.sensors.pclint; import java.util.ArrayList; import static org.assertj.core.api.Assertions.assertThat; import org.assertj.core.api.SoftAssertions; import org.junit.Before; import org.junit.Test; import org.sonar.api.batch.fs.internal.DefaultFileSystem; import org.sonar.api.batch.fs.internal.TestInputFileBuilder; import org.sonar.api.batch.sensor.internal.DefaultSensorDescriptor; import org.sonar.api.batch.sensor.internal.SensorContextTester; import org.sonar.api.batch.sensor.issue.Issue; import org.sonar.api.config.internal.MapSettings; import org.sonar.cxx.sensors.utils.CxxReportSensor; import org.sonar.cxx.sensors.utils.TestUtils; public class CxxPCLintSensorTest { private DefaultFileSystem fs; private final MapSettings settings = new MapSettings(); @Before public void setUp() { fs = TestUtils.mockFileSystem(); settings.setProperty(CxxReportSensor.ERROR_RECOVERY_KEY, true); } @Test public void shouldReportCorrectViolations() { var context = SensorContextTester.create(fs.baseDir()); settings.setProperty(CxxPCLintSensor.REPORT_PATH_KEY, "pclint-reports/pclint-result-SAMPLE.xml"); context.setSettings(settings); context.fileSystem().add(TestInputFileBuilder.create("ProjectKey", "FileZip.cpp").setLanguage("cxx").initMetadata( "asd\nasdas\nasda\n").build()); context.fileSystem().add(TestInputFileBuilder.create("ProjectKey", "FileZip.h").setLanguage("cxx").initMetadata( "asd\nasdas\nasda\n").build()); context.fileSystem().add(TestInputFileBuilder.create("ProjectKey", "ZipManager.cpp").setLanguage("cxx") .initMetadata("asd\nasdas\nasda\n").build()); var sensor = new CxxPCLintSensor(); sensor.execute(context); assertThat(context.allIssues()).hasSize(16); } @Test public void shouldReportCorrectMisra2004Violations() { var context = SensorContextTester.create(fs.baseDir()); settings.setProperty(CxxPCLintSensor.REPORT_PATH_KEY, "pclint-reports/pclint-result-MISRA2004-SAMPLE1.xml"); context.setSettings(settings); context.fileSystem().add(TestInputFileBuilder.create("ProjectKey", "test.c").setLanguage("cxx").initMetadata( "asd\nasdas\nasda\n").build()); var sensor = new CxxPCLintSensor(); sensor.execute(context); assertThat(context.allIssues()).hasSize(29); } @Test public void shouldReportCorrectMisra2004PcLint9Violations() { var context = SensorContextTester.create(fs.baseDir()); settings.setProperty(CxxPCLintSensor.REPORT_PATH_KEY, "pclint-reports/pclint-result-MISRA2004-SAMPLE2.xml"); context.setSettings(settings); context.fileSystem().add(TestInputFileBuilder.create("ProjectKey", "test.c").setLanguage("cxx").initMetadata( "asd\nasdas\nasda\n").build()); var sensor = new CxxPCLintSensor(); sensor.execute(context); assertThat(context.allIssues()).hasSize(1); } @Test public void shouldReportCorrectMisraCppViolations() { var context = SensorContextTester.create(fs.baseDir()); settings.setProperty(CxxPCLintSensor.REPORT_PATH_KEY, "pclint-reports/pclint-result-MISRACPP.xml"); context.setSettings(settings); context.fileSystem().add(TestInputFileBuilder.create("ProjectKey", "test.c").setLanguage("cxx").initMetadata( "asd\nasdas\nasda\n").build()); var sensor = new CxxPCLintSensor(); sensor.execute(context); assertThat(context.allIssues()).hasSize(2); var issuesList = new ArrayList<Issue>(context.allIssues()); assertThat(issuesList.get(0).ruleKey().rule()).isEqualTo("M5-0-19"); assertThat(issuesList.get(1).ruleKey().rule()).isEqualTo("M18-4-1"); } @Test public void shouldNotSaveIssuesWhenMisra2004DescIsWrong() { var context = SensorContextTester.create(fs.baseDir()); settings.setProperty(CxxPCLintSensor.REPORT_PATH_KEY, "pclint-reports/incorrect-pclint-MISRA2004-desc.xml"); context.setSettings(settings); context.fileSystem().add(TestInputFileBuilder.create("ProjectKey", "test.c").setLanguage("cxx").initMetadata( "asd\nasdas\nasda\n").build()); var sensor = new CxxPCLintSensor(); sensor.execute(context); assertThat(context.allIssues()).isEmpty(); } @Test public void shouldNotSaveAnythingWhenMisra2004RuleDoNotExist() { var context = SensorContextTester.create(fs.baseDir()); settings.setProperty(CxxPCLintSensor.REPORT_PATH_KEY, "pclint-reports/incorrect-pclint-MISRA2004-rule-do-not-exist.xml"); context.setSettings(settings); context.fileSystem().add(TestInputFileBuilder.create("ProjectKey", "test.c").setLanguage("cxx").initMetadata( "asd\nasdas\nasda\n").build()); var sensor = new CxxPCLintSensor(); sensor.execute(context); assertThat(context.allIssues()).isEmpty(); } @Test public void shouldNotRemapMisra1998Rules() { var context = SensorContextTester.create(fs.baseDir()); settings.setProperty(CxxPCLintSensor.REPORT_PATH_KEY, "pclint-reports/pclint-result-MISRA1998-SAMPLE.xml"); context.setSettings(settings); context.fileSystem().add(TestInputFileBuilder.create("ProjectKey", "test.c").setLanguage("cxx").initMetadata( "asd\nasdas\nasda\n").build()); var sensor = new CxxPCLintSensor(); sensor.execute(context); assertThat(context.allIssues()).hasSize(1); } @Test public void shouldReportProjectLevelViolations() { var context = SensorContextTester.create(fs.baseDir()); settings.setProperty(CxxPCLintSensor.REPORT_PATH_KEY, "pclint-reports/pclint-result-projectlevelviolation.xml"); context.setSettings(settings); var sensor = new CxxPCLintSensor(); sensor.execute(context); assertThat(context.allIssues()).hasSize(1); } @Test public void shouldThrowExceptionInvalidChar() { var context = SensorContextTester.create(fs.baseDir()); settings.setProperty(CxxPCLintSensor.REPORT_PATH_KEY, "pclint-reports/pclint-result-invalid-char.xml"); context.setSettings(settings); var sensor = new CxxPCLintSensor(); sensor.execute(context); assertThat(context.allIssues().size()).isZero(); } @Test public void sensorDescriptor() { var descriptor = new DefaultSensorDescriptor(); var sensor = new CxxPCLintSensor(); sensor.describe(descriptor); var softly = new SoftAssertions(); softly.assertThat(descriptor.name()).isEqualTo("CXX PC-lint report import"); softly.assertThat(descriptor.languages()).containsOnly("cxx", "cpp", "c++", "c"); softly.assertThat(descriptor.ruleRepositories()).containsOnly(CxxPCLintRuleRepository.KEY); softly.assertAll(); } @Test public void loadSupplementalMsg() { var context = SensorContextTester.create(fs.baseDir()); settings.setProperty(CxxPCLintSensor.REPORT_PATH_KEY, "pclint-reports/pclint-result-with-supplemental.xml"); context.setSettings(settings); context.fileSystem().add(TestInputFileBuilder.create("ProjectKey", "FileZip.cpp").setLanguage("cxx").initMetadata( "asd\nasdas\nasda\n").build()); context.fileSystem().add(TestInputFileBuilder.create("ProjectKey", "FileZip.h").setLanguage("cxx").initMetadata( "asd\nasdas\nasda\n").build()); var sensor = new CxxPCLintSensor(); sensor.execute(context); assertThat(context.allIssues()).hasSize(2); var allIssues = new ArrayList<Issue>(context.allIssues()); Issue firstIssue = allIssues.get(0); assertThat(firstIssue.flows()).hasSize(1); assertThat(firstIssue.flows().get(0).locations()).hasSize(3); Issue secondIssue = allIssues.get(1); assertThat(secondIssue.flows()).hasSize(1); assertThat(secondIssue.flows().get(0).locations()).hasSize(1); } }
lgpl-3.0
abdollahpour/xweb-wiki
src/main/java/info/bliki/wiki/tags/WPParagraphTag.java
204
package info.bliki.wiki.tags; public class WPParagraphTag extends WPTag { public WPParagraphTag() { super("p"); } @Override public boolean isReduceTokenStack() { return true; } }
lgpl-3.0
OpenModLoader/OpenModLoader
src/main/java/com/openmodloader/api/mod/config/IModConfigurator.java
203
package com.openmodloader.api.mod.config; public interface IModConfigurator { default IModConfig initConfig() { return new SimpleModConfig(); } void configure(IModConfig config); }
lgpl-3.0
raffaeleconforti/ResearchCode
noisefiltering-event-prom/src/main/java/com/raffaeleconforti/noisefiltering/event/noise/prom/ui/NoiseUI.java
1611
/* * Copyright (C) 2018 Raffaele Conforti (www.raffaeleconforti.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, see <http://www.gnu.org/licenses/>. */ package com.raffaeleconforti.noisefiltering.event.noise.prom.ui; import com.raffaeleconforti.noisefiltering.event.noise.selection.NoiseResult; import org.deckfour.uitopia.api.event.TaskListener; import org.processmining.contexts.uitopia.UIPluginContext; import java.util.concurrent.CancellationException; /** * Created by conforti on 26/02/15. */ public class NoiseUI { public NoiseResult showGUI(UIPluginContext context) { Noise noise = new Noise(); TaskListener.InteractionResult guiResult = context.showWizard("Select Noise Level", true, true, noise); if (guiResult == TaskListener.InteractionResult.CANCEL) { context.getFutureResult(0).cancel(true); throw new CancellationException("The wizard has been cancelled."); } return noise.getSelections(); } }
lgpl-3.0
iamMehedi/imageCropLib
ImageCropLibrary/src/com/mhk/android/croplib/BaseActivity.java
7863
package com.mhk.android.croplib; import java.io.File; import java.io.IOException; import java.io.InputStream; import java.io.OutputStream; import android.app.Activity; import android.content.ActivityNotFoundException; import android.content.Intent; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.graphics.Rect; import android.graphics.RectF; import android.net.Uri; import android.os.Build; import android.os.Bundle; import android.os.Environment; import android.os.Handler; import android.widget.Toast; public class BaseActivity extends Activity implements HostActivityActionListener{ public static final String EXTRA_OUTPUT_PATH="output_file"; final int REQUEST_PICK=121; public final static int CROP_WIDTH = 600, CROP_HEIGHT = 600; //in dp final int OUTPUT_WIDTH = 165, OUTPUT_HEIGHT = 165; public static float MIN_SIZE = CROP_WIDTH; private boolean isSaving; private String OUTPUT_PATH = Environment.getExternalStorageDirectory().getAbsolutePath()+"/cropTest"; private final String OUTPUT_FILENAME = "cropped_image.jpg"; private Uri sourceUri, outputUri; private int sampleSize, exifRotation; private RotateBitmap rotateBitmap; public CropImageView imageView; CropView cropView; Handler handler; @Override protected void onCreate(Bundle savedInstanceState) { // TODO Auto-generated method stub super.onCreate(savedInstanceState); handler = new Handler(); if(getIntent().getStringExtra(EXTRA_OUTPUT_PATH)!=null) { File file = new File(getIntent().getStringExtra(EXTRA_OUTPUT_PATH)); outputUri = Uri.fromFile(file); } else { File dir=new File(OUTPUT_PATH); if(!dir.exists()) { dir.mkdirs(); } File file=new File(dir, OUTPUT_FILENAME); outputUri = Uri.fromFile(file); } } void setImageView(CropImageView view){ imageView = view; } @Override public boolean isSaving() { // TODO Auto-generated method stub return isSaving; } public void pickImageFromGallery() { if(Build.VERSION.SDK_INT<19) { Intent intent = new Intent(Intent.ACTION_GET_CONTENT).setType("image/*"); try { startActivityForResult(intent, REQUEST_PICK); } catch (ActivityNotFoundException e) { Toast.makeText(this, "No image sources found", Toast.LENGTH_SHORT).show(); } } else { Intent i = new Intent(Intent.ACTION_PICK,android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI); startActivityForResult(i, REQUEST_PICK); } } @Override protected void onActivityResult(int requestCode, int resultCode, Intent data) { // TODO Auto-generated method stub super.onActivityResult(requestCode, resultCode, data); if (requestCode == REQUEST_PICK && resultCode == RESULT_OK && data!=null) { sourceUri = data.getData(); setupImage(); } } void setupImage() { if (sourceUri != null) { exifRotation = CropUtil.getExifRotation(CropUtil.getFromMediaUri(getContentResolver(), sourceUri)); InputStream is = null; try { sampleSize = CropUtil.calculateBitmapSampleSize(this, sourceUri); is = getContentResolver().openInputStream(sourceUri); BitmapFactory.Options option = new BitmapFactory.Options(); option.inSampleSize = sampleSize; rotateBitmap = new RotateBitmap(BitmapFactory.decodeStream(is, null, option), exifRotation); } catch (IOException e) { e.printStackTrace(); } catch (OutOfMemoryError e) { e.printStackTrace(); } finally { CropUtil.closeSilently(is); } initCropView(); } } void initCropView() { if(rotateBitmap!=null) { imageView.setImageRotateBitmapResetBase(rotateBitmap, true); CropView cv=new CropView(imageView); final int width = rotateBitmap.getWidth(); final int height = rotateBitmap.getHeight(); Rect imageRect = new Rect(0, 0, width, height); float cropWidth = CROP_WIDTH; float cropHeight = CROP_HEIGHT; if(width<cropWidth) { cropWidth = cropHeight = width-20; } else if(height<cropHeight) { cropHeight = cropWidth = height - 20; } MIN_SIZE = Math.max(cropWidth, cropHeight); float x = (width - cropWidth) / 2; float y = (height - cropHeight) / 2; RectF cropRect = new RectF(x, y, x + cropWidth, y + cropHeight); cv.setup(imageView.getUnrotatedMatrix(), imageRect, cropRect); imageView.add(cv); imageView.invalidate(); if(imageView.mCropView!=null) { cropView=imageView.mCropView; } } } private float dpToPx(float dp) { return dp * imageView.getResources().getDisplayMetrics().density; } void clearImageView() { imageView.clear(); if (rotateBitmap != null) { rotateBitmap.recycle(); } System.gc(); } public void cropImage() { if(cropView==null || isSaving()) { return; } isSaving = true; //release memory clearImageView(); Bitmap croppedImage = null; Rect r = cropView.getScaledCropRect(sampleSize); int width = r.width(); int height = r.height(); int outWidth = width, outHeight = height; if (OUTPUT_WIDTH > 0 && OUTPUT_HEIGHT > 0 && (width > OUTPUT_WIDTH || height > OUTPUT_HEIGHT)) { float ratio = (float) width / (float) height; if ((float) OUTPUT_WIDTH / (float) OUTPUT_HEIGHT > ratio) { outHeight = OUTPUT_HEIGHT; outWidth = (int) ((float) OUTPUT_HEIGHT * ratio + .5f); } else { outWidth = OUTPUT_WIDTH; outHeight = (int) ((float) OUTPUT_WIDTH / ratio + .5f); } } try { croppedImage = CropUtil.decodeRegionCrop(this, sourceUri, r); } catch (IllegalArgumentException e) { e.printStackTrace(); isSaving = false; return; } if (croppedImage != null) { imageView.setImageRotateBitmapResetBase(new RotateBitmap(croppedImage, exifRotation), true); imageView.center(true, true); imageView.mCropView=null; cropView=null; saveImage(croppedImage); } else { isSaving=false; } } void saveImage(Bitmap croppedImage) { if (outputUri != null) { OutputStream outputStream = null; try { outputStream = getContentResolver().openOutputStream(outputUri); if (outputStream != null) { croppedImage.compress(Bitmap.CompressFormat.JPEG, 100, outputStream); } } catch (IOException e) { e.printStackTrace(); } finally { CropUtil.closeSilently(outputStream); } CropUtil.copyExifRotation( CropUtil.getFromMediaUri(getContentResolver(), sourceUri), CropUtil.getFromMediaUri(getContentResolver(), outputUri) ); } /*final Bitmap b = croppedImage; handler.post(new Runnable() { public void run() { b.recycle(); } });*/ isSaving=false; } @Override protected void onDestroy() { super.onDestroy(); if (rotateBitmap != null) { rotateBitmap.recycle(); } } }
lgpl-3.0
MrRiegel/Quick-Crafting
src/main/java/mrriegel/qucra/PacketHandler.java
586
package mrriegel.qucra; import cpw.mods.fml.common.network.simpleimpl.SimpleNetworkWrapper; import cpw.mods.fml.relauncher.Side; public class PacketHandler { public static final SimpleNetworkWrapper INSTANCE = new SimpleNetworkWrapper( QuickCrafting.MODID); public static void init() { int id = 0; INSTANCE.registerMessage(ScrollMessage.class, ScrollMessage.class, id++, Side.SERVER); INSTANCE.registerMessage(KeyMessage.class, KeyMessage.class, id++, Side.SERVER); INSTANCE.registerMessage(SearchMessage.class, SearchMessage.class, id++, Side.SERVER); } }
lgpl-3.0
aflanagan/jsprit
jsprit-core/src/test/java/jsprit/core/algorithm/MeetTimeWindowConstraint_IT.java
12863
/******************************************************************************* * Copyright (c) 2014 Stefan Schroeder. * * 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.0 of the License, or (at your option) any later version. * * This library is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public * License along with this library. If not, see <http://www.gnu.org/licenses/>. * * Contributors: * Stefan Schroeder - initial API and implementation ******************************************************************************/ package jsprit.core.algorithm; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; import java.util.ArrayList; import java.util.Collection; import java.util.List; import jsprit.core.algorithm.box.SchrimpfFactory; import jsprit.core.algorithm.io.VehicleRoutingAlgorithms; import jsprit.core.algorithm.recreate.listener.JobInsertedListener; import jsprit.core.algorithm.recreate.listener.VehicleSwitchedListener; import jsprit.core.problem.VehicleRoutingProblem; import jsprit.core.problem.io.VrpXMLReader; import jsprit.core.problem.job.Job; import jsprit.core.problem.solution.VehicleRoutingProblemSolution; import jsprit.core.problem.solution.route.VehicleRoute; import jsprit.core.problem.vehicle.Vehicle; import jsprit.core.util.Solutions; import org.junit.Test; public class MeetTimeWindowConstraint_IT { @Test public void whenEmployingVehicleWithDifferentWorkingShifts_nRoutesShouldBeCorrect(){ VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance(); new VrpXMLReader(vrpBuilder).read("src/test/resources/simpleProblem.xml"); VehicleRoutingProblem vrp = vrpBuilder.build(); VehicleRoutingAlgorithm vra = new SchrimpfFactory().createAlgorithm(vrp); vra.setNuOfIterations(100); Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions(); assertEquals(2,Solutions.bestOf(solutions).getRoutes().size()); } @Test public void whenEmployingVehicleWithDifferentWorkingShifts_certainJobsCanNeverBeAssignedToCertainVehicles(){ VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance(); new VrpXMLReader(vrpBuilder).read("src/test/resources/simpleProblem.xml"); VehicleRoutingProblem vrp = vrpBuilder.build(); VehicleRoutingAlgorithm vra = new SchrimpfFactory().createAlgorithm(vrp); vra.setNuOfIterations(100); final List<Boolean> testFailed = new ArrayList<Boolean>(); vra.addListener(new JobInsertedListener() { @Override public void informJobInserted(Job job2insert, VehicleRoute inRoute, double additionalCosts, double additionalTime) { if(job2insert.getId().equals("1")){ if(inRoute.getVehicle().getId().equals("19")){ testFailed.add(true); } } if(job2insert.getId().equals("2")){ if(inRoute.getVehicle().getId().equals("21")){ testFailed.add(true); } } } }); @SuppressWarnings("unused") Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions(); assertTrue(testFailed.isEmpty()); } @Test public void whenEmployingVehicleWithDifferentWorkingShifts_certainVehiclesCanNeverBeAssignedToCertainRoutes(){ VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance(); new VrpXMLReader(vrpBuilder).read("src/test/resources/simpleProblem.xml"); VehicleRoutingProblem vrp = vrpBuilder.build(); VehicleRoutingAlgorithm vra = new SchrimpfFactory().createAlgorithm(vrp); vra.setNuOfIterations(100); final List<Boolean> testFailed = new ArrayList<Boolean>(); vra.addListener(new VehicleSwitchedListener() { @Override public void vehicleSwitched(VehicleRoute vehicleRoute, Vehicle oldVehicle, Vehicle newVehicle) { if(oldVehicle==null) return; if(oldVehicle.getId().equals("21") && newVehicle.getId().equals("19")){ for(Job j : vehicleRoute.getTourActivities().getJobs()){ if(j.getId().equals("1")){ testFailed.add(true); } } } if(oldVehicle.getId().equals("19") && newVehicle.getId().equals("21")){ for(Job j : vehicleRoute.getTourActivities().getJobs()){ if(j.getId().equals("2")){ testFailed.add(true); } } } } }); @SuppressWarnings("unused") Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions(); System.out.println("failed " + testFailed.size()); assertTrue(testFailed.isEmpty()); } @Test public void whenEmployingVehicleWithDifferentWorkingShifts_job2CanNeverBeInVehicle21(){ VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance(); new VrpXMLReader(vrpBuilder).read("src/test/resources/simpleProblem.xml"); VehicleRoutingProblem vrp = vrpBuilder.build(); VehicleRoutingAlgorithm vra = new SchrimpfFactory().createAlgorithm(vrp); vra.setNuOfIterations(100); Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions(); assertEquals(2,Solutions.bestOf(solutions).getRoutes().size()); } @Test public void whenEmployingVehicleWithDifferentWorkingShifts_job1ShouldBeAssignedCorrectly(){ VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance(); new VrpXMLReader(vrpBuilder).read("src/test/resources/simpleProblem.xml"); VehicleRoutingProblem vrp = vrpBuilder.build(); VehicleRoutingAlgorithm vra = new SchrimpfFactory().createAlgorithm(vrp); vra.setNuOfIterations(100); Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions(); // assertEquals(2,Solutions.bestOf(solutions).getRoutes().size()); assertTrue(containsJob(vrp.getJobs().get("1"),getRoute("21",Solutions.bestOf(solutions)))); } @Test public void whenEmployingVehicleWithDifferentWorkingShifts_job2ShouldBeAssignedCorrectly(){ VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance(); new VrpXMLReader(vrpBuilder).read("src/test/resources/simpleProblem.xml"); VehicleRoutingProblem vrp = vrpBuilder.build(); VehicleRoutingAlgorithm vra = new SchrimpfFactory().createAlgorithm(vrp); vra.setNuOfIterations(100); Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions(); // assertEquals(2,Solutions.bestOf(solutions).getRoutes().size()); assertTrue(containsJob(vrp.getJobs().get("2"),getRoute("19",Solutions.bestOf(solutions)))); } @Test public void whenEmployingVehicleWithDifferentWorkingShifts_and_vehicleSwitchIsNotAllowed_nRoutesShouldBeCorrect(){ VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance(); new VrpXMLReader(vrpBuilder).read("src/test/resources/simpleProblem.xml"); VehicleRoutingProblem vrp = vrpBuilder.build(); VehicleRoutingAlgorithm vra = VehicleRoutingAlgorithms.readAndCreateAlgorithm(vrp, "src/test/resources/schrimpf_vehicleSwitchNotAllowed.xml"); vra.setNuOfIterations(100); Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions(); assertEquals(2,Solutions.bestOf(solutions).getRoutes().size()); } @Test public void whenEmployingVehicleWithDifferentWorkingShifts_and_vehicleSwitchIsNotAllowed_certainJobsCanNeverBeAssignedToCertainVehicles(){ VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance(); new VrpXMLReader(vrpBuilder).read("src/test/resources/simpleProblem.xml"); VehicleRoutingProblem vrp = vrpBuilder.build(); VehicleRoutingAlgorithm vra = VehicleRoutingAlgorithms.readAndCreateAlgorithm(vrp, "src/test/resources/schrimpf_vehicleSwitchNotAllowed.xml"); vra.setNuOfIterations(100); final List<Boolean> testFailed = new ArrayList<Boolean>(); vra.addListener(new JobInsertedListener() { @Override public void informJobInserted(Job job2insert, VehicleRoute inRoute, double additionalCosts, double additionalTime) { if(job2insert.getId().equals("1")){ if(inRoute.getVehicle().getId().equals("19")){ testFailed.add(true); } } if(job2insert.getId().equals("2")){ if(inRoute.getVehicle().getId().equals("21")){ testFailed.add(true); } } } }); @SuppressWarnings("unused") Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions(); assertTrue(testFailed.isEmpty()); } @Test public void whenEmployingVehicleWithDifferentWorkingShifts_and_vehicleSwitchIsNotAllowed_certainVehiclesCanNeverBeAssignedToCertainRoutes(){ VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance(); new VrpXMLReader(vrpBuilder).read("src/test/resources/simpleProblem.xml"); VehicleRoutingProblem vrp = vrpBuilder.build(); VehicleRoutingAlgorithm vra = VehicleRoutingAlgorithms.readAndCreateAlgorithm(vrp, "src/test/resources/schrimpf_vehicleSwitchNotAllowed.xml"); vra.setNuOfIterations(100); final List<Boolean> testFailed = new ArrayList<Boolean>(); vra.addListener(new VehicleSwitchedListener() { @Override public void vehicleSwitched(VehicleRoute vehicleRoute, Vehicle oldVehicle, Vehicle newVehicle) { if(oldVehicle==null) return; if(oldVehicle.getId().equals("21") && newVehicle.getId().equals("19")){ for(Job j : vehicleRoute.getTourActivities().getJobs()){ if(j.getId().equals("1")){ testFailed.add(true); } } } if(oldVehicle.getId().equals("19") && newVehicle.getId().equals("21")){ for(Job j : vehicleRoute.getTourActivities().getJobs()){ if(j.getId().equals("2")){ testFailed.add(true); } } } } }); @SuppressWarnings("unused") Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions(); System.out.println("failed " + testFailed.size()); assertTrue(testFailed.isEmpty()); } @Test public void whenEmployingVehicleWithDifferentWorkingShifts_and_vehicleSwitchIsNotAllowed_job2CanNeverBeInVehicle21(){ VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance(); new VrpXMLReader(vrpBuilder).read("src/test/resources/simpleProblem.xml"); VehicleRoutingProblem vrp = vrpBuilder.build(); VehicleRoutingAlgorithm vra = VehicleRoutingAlgorithms.readAndCreateAlgorithm(vrp, "src/test/resources/schrimpf_vehicleSwitchNotAllowed.xml"); vra.setNuOfIterations(100); Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions(); assertEquals(2,Solutions.bestOf(solutions).getRoutes().size()); } @Test public void whenEmployingVehicleWithDifferentWorkingShifts_and_vehicleSwitchIsNotAllowed_job1ShouldBeAssignedCorrectly(){ VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance(); new VrpXMLReader(vrpBuilder).read("src/test/resources/simpleProblem.xml"); VehicleRoutingProblem vrp = vrpBuilder.build(); VehicleRoutingAlgorithm vra = VehicleRoutingAlgorithms.readAndCreateAlgorithm(vrp, "src/test/resources/schrimpf_vehicleSwitchNotAllowed.xml"); vra.setNuOfIterations(100); Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions(); assertEquals(2,Solutions.bestOf(solutions).getRoutes().size()); assertTrue(containsJob(vrp.getJobs().get("1"),getRoute("21",Solutions.bestOf(solutions)))); } @Test public void whenEmployingVehicleWithDifferentWorkingShifts_and_vehicleSwitchIsNotAllowed_job2ShouldBeAssignedCorrectly(){ VehicleRoutingProblem.Builder vrpBuilder = VehicleRoutingProblem.Builder.newInstance(); new VrpXMLReader(vrpBuilder).read("src/test/resources/simpleProblem.xml"); VehicleRoutingProblem vrp = vrpBuilder.build(); VehicleRoutingAlgorithm vra = VehicleRoutingAlgorithms.readAndCreateAlgorithm(vrp, "src/test/resources/schrimpf_vehicleSwitchNotAllowed.xml"); vra.setNuOfIterations(100); Collection<VehicleRoutingProblemSolution> solutions = vra.searchSolutions(); assertEquals(2,Solutions.bestOf(solutions).getRoutes().size()); assertTrue(containsJob(vrp.getJobs().get("2"),getRoute("19",Solutions.bestOf(solutions)))); } private boolean containsJob(Job job, VehicleRoute route) { if(route == null) return false; for(Job j : route.getTourActivities().getJobs()){ if(job == j){ return true; } } return false; } private VehicleRoute getRoute(String vehicleId, VehicleRoutingProblemSolution vehicleRoutingProblemSolution) { for(VehicleRoute r : vehicleRoutingProblemSolution.getRoutes()){ if(r.getVehicle().getId().equals(vehicleId)){ return r; } } return null; } }
lgpl-3.0
sebkpp/TUIFramework
xmlconfigurationtool/src/configmodel/InternalException.java
1358
/* Copyright (C) 2010, 2011, 2012 The Fraunhofer Institute for Production Systems and Design Technology IPK. All rights reserved. This file is part of the TUIFramework library. It includes a software framework which contains common code providing generic functionality for developing applications with a tangible user interface (TUI). The TUIFramework 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. The TUIFramework 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 TUIFramework. If not, see <http://www.gnu.org/licenses/>. */ package configmodel; /** * InternalException * * @author Oliver Belaifa */ public class InternalException extends Exception { private static final long serialVersionUID = 3093984324871351718L; public InternalException() { } public InternalException(String msg) { super(msg); } }
lgpl-3.0
lbndev/sonarqube
sonar-plugin-api/src/test/java/org/sonar/api/resources/LanguagesTest.java
2167
/* * 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.resources; import org.junit.Test; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class LanguagesTest { @Test public void should_add_several_times_the_same_language() { Languages languages = new Languages( language("fake"), language("fake")); assertThat(languages.get("fake").getKey()).isEqualTo("fake"); } @Test public void should_get_suffixes() { Languages languages = new Languages( language("java", "java"), language("php", "php4", "php5")); assertThat(languages.getSuffixes()).containsOnly("java", "php4", "php5"); assertThat(languages.getSuffixes("java")).containsOnly("java"); assertThat(languages.getSuffixes("php")).containsOnly("php4", "php5"); assertThat(languages.getSuffixes("xxx")).isEmpty(); } @Test public void test_no_languages() { Languages languages = new Languages(); assertThat(languages.get("foo")).isNull(); assertThat(languages.getSuffixes("foo")).isEmpty(); } static Language language(String key, String... suffixes) { Language lang = mock(Language.class); when(lang.getKey()).thenReturn(key); when(lang.getFileSuffixes()).thenReturn(suffixes); return lang; } }
lgpl-3.0
Dschinghis-Kahn/eveapi
api/net/dschinghiskahn/eveapi/api/calllist/Call.java
1132
package net.dschinghiskahn.eveapi.api.calllist; import org.simpleframework.xml.Attribute; import org.simpleframework.xml.Root; @Root(name = "row") public class Call { @Attribute(required = false) private Long accessMask; @Attribute(required = false) private String description; @Attribute(name = "groupID", required = false) private Long groupId; @Attribute(required = false) private String name; @Attribute(required = false) private String type; public Long getAccessMask() { return accessMask; } public String getDescription() { return description; } public Long getGroupId() { return groupId; } public String getName() { return name; } public String getType() { return type; } @Override public String toString() { return "Call [" + "accessMask = " + accessMask + ", " + "description = " + description + ", " + "groupId = " + groupId + ", " + "name = " + name + ", " + "type = " + type + ", " + "]"; } }
lgpl-3.0
UsernameZero/xenorite
src/main/java/com/techiecrow/tools/weapons/XCFMasterSword.java
827
package com.techiecrow.tools.weapons; import net.minecraft.entity.Entity; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.ItemStack; import net.minecraft.potion.PotionEffect; import net.minecraft.world.World; public class XCFMasterSword extends WeaponXenorite { public static double rand; public XCFMasterSword(ToolMaterial material) { super(material); this.setUnlocalizedName("xcfMasterSword"); } @Override public void onUpdate(ItemStack stack, World world, Entity entity, int par4, boolean par5) { super.onUpdate(stack, world, entity, par4, par5); { EntityPlayer player = (EntityPlayer) entity; ItemStack equipped = player.getCurrentEquippedItem(); if (world.isDaytime() && equipped == stack) { player.addPotionEffect((new PotionEffect(5, 10, 1))); } } } }
lgpl-3.0
joaorenno/obinject
src/org/obinject/sample/image/AppWrapper.java
428
/* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package org.obinject.sample.image; import org.obinject.meta.generator.Wrapper; /** * * @author system */ public class AppWrapper { public static void main(String[] args) { Wrapper.create("org.obinject.sample.image"); } }
lgpl-3.0
schemaspy/schemaspy
src/test/java/org/schemaspy/integrationtesting/mysql/MysqlHTMLOrphanIT.java
5626
/* * Copyright (C) 2018 Nils Petzaell * * This file is part of SchemaSpy. * * SchemaSpy is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SchemaSpy is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with SchemaSpy. If not, see <http://www.gnu.org/licenses/>. */ package org.schemaspy.integrationtesting.mysql; import com.github.npetzall.testcontainers.junit.jdbc.JdbcContainerRule; import org.assertj.core.api.SoftAssertions; import org.junit.Before; import org.junit.ClassRule; import org.junit.Test; import org.junit.runner.RunWith; import org.schemaspy.cli.SchemaSpyRunner; import org.schemaspy.integrationtesting.MysqlSuite; import org.schemaspy.testing.HtmlOutputValidator; import org.schemaspy.testing.SuiteOrTestJdbcContainerRule; import org.schemaspy.testing.XmlOutputDiff; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.junit4.SpringRunner; import org.testcontainers.containers.MySQLContainer; import org.xmlunit.builder.Input; import org.xmlunit.diff.Diff; import java.io.IOException; import java.net.URL; import java.nio.file.Files; import java.nio.file.Path; import java.nio.file.Paths; import java.nio.file.StandardOpenOption; import java.util.concurrent.atomic.AtomicBoolean; import static com.github.npetzall.testcontainers.junit.jdbc.JdbcAssumptions.assumeDriverIsPresent; import static org.assertj.core.api.Assertions.assertThat; /** * @author Nils Petzaell */ @RunWith(SpringRunner.class) @SpringBootTest @DirtiesContext public class MysqlHTMLOrphanIT { private static final Path outputPath = Paths.get("target","testout","integrationtesting","mysql","htmlorphanit"); private static URL expectedXML = MysqlHTMLOrphanIT.class.getResource("/integrationTesting/mysql/expecting/mysqlhtmlorphan/htmlorphanit.htmlorphanit.xml"); private static URL expectedDeletionOrder = MysqlHTMLOrphanIT.class.getResource("/integrationTesting/mysql/expecting/mysqlhtmlorphan/deletionOrder.txt"); private static URL expectedInsertionOrder = MysqlHTMLOrphanIT.class.getResource("/integrationTesting/mysql/expecting/mysqlhtmlorphan/insertionOrder.txt"); @SuppressWarnings("unchecked") @ClassRule public static JdbcContainerRule<MySQLContainer<?>> jdbcContainerRule = new SuiteOrTestJdbcContainerRule<MySQLContainer<?>>( MysqlSuite.jdbcContainerRule, new JdbcContainerRule<MySQLContainer<?>>(() -> new MySQLContainer<>("mysql:5")) .assumeDockerIsPresent().withAssumptions(assumeDriverIsPresent()) .withQueryString("?useSSL=false") .withInitScript("integrationTesting/mysql/dbScripts/htmlorphanit.sql") .withInitUser("root", "test") ); @Autowired private SchemaSpyRunner schemaSpyRunner; private static final AtomicBoolean shouldRun = new AtomicBoolean(true); @Before public synchronized void generateHTML() throws Exception { if (shouldRun.get()) { String[] args = new String[]{ "-t", "mysql", "-db", "htmlorphanit", "-s", "htmlorphanit", "-host", jdbcContainerRule.getContainer().getContainerIpAddress() + ":" + jdbcContainerRule.getContainer().getMappedPort(3306), "-port", String.valueOf(jdbcContainerRule.getContainer().getMappedPort(3306)), "-u", jdbcContainerRule.getContainer().getUsername(), "-p", jdbcContainerRule.getContainer().getPassword(), "-o", outputPath.toString(), "-connprops", "useSSL\\=false" }; schemaSpyRunner.run(args); shouldRun.set(false); } } @Test public void verifyXML() { Diff d = XmlOutputDiff.diffXmlOutput( Input.fromFile(outputPath.resolve("htmlorphanit.htmlorphanit.xml").toString()), Input.fromURL(expectedXML) ); assertThat(d.getDifferences()).isEmpty(); } @Test public void verifyDeletionOrder() throws IOException { assertThat(Files.newInputStream(outputPath.resolve("deletionOrder.txt"), StandardOpenOption.READ)).hasSameContentAs(expectedDeletionOrder.openStream()); } @Test public void verifyInsertionOrder() throws IOException { assertThat(Files.newInputStream(outputPath.resolve("insertionOrder.txt"), StandardOpenOption.READ)).hasSameContentAs(expectedInsertionOrder.openStream()); } @Test public void producesSameContent() throws IOException { SoftAssertions softAssertions = HtmlOutputValidator .hasProducedValidOutput( outputPath, Paths.get("src","test","resources","integrationTesting","mysql","expecting","mysqlhtmlorphan") ); softAssertions.assertThat(softAssertions.wasSuccess()).isTrue(); softAssertions.assertAll(); } }
lgpl-3.0
galleon1/chocolate-milk
src/org/chocolate_milk/model/DataEventSubscriptionRet.java
20123
/* * This class was automatically generated with * <a href="http://www.castor.org">Castor 1.3.1</a>, using an XML * Schema. * $Id: DataEventSubscriptionRet.java,v 1.1.1.1 2010-05-04 22:06:00 ryan Exp $ */ package org.chocolate_milk.model; /** * Class DataEventSubscriptionRet. * * @version $Revision: 1.1.1.1 $ $Date: 2010-05-04 22:06:00 $ */ @SuppressWarnings("serial") public class DataEventSubscriptionRet implements java.io.Serializable { //--------------------------/ //- Class/Member Variables -/ //--------------------------/ /** * Field _subscriberID. */ private java.lang.String _subscriberID; /** * Field _timeCreated. */ private java.lang.String _timeCreated; /** * Field _timeLastProcessed. */ private java.lang.String _timeLastProcessed; /** * Field _COMCallbackInfo. */ private org.chocolate_milk.model.COMCallbackInfo _COMCallbackInfo; /** * Field _deliveryPolicy. */ private org.chocolate_milk.model.types.DeliveryPolicyType _deliveryPolicy; /** * Field _trackLostEvents. */ private org.chocolate_milk.model.types.TrackLostEventsType _trackLostEvents = org.chocolate_milk.model.types.TrackLostEventsType.fromValue("None"); /** * Field _deliverOwnEvents. */ private java.lang.String _deliverOwnEvents; /** * Field _listEventSubscriptionList. */ private java.util.List<org.chocolate_milk.model.ListEventSubscription> _listEventSubscriptionList; /** * Field _txnEventSubscriptionList. */ private java.util.List<org.chocolate_milk.model.TxnEventSubscription> _txnEventSubscriptionList; //----------------/ //- Constructors -/ //----------------/ public DataEventSubscriptionRet() { super(); setTrackLostEvents(org.chocolate_milk.model.types.TrackLostEventsType.fromValue("None")); this._listEventSubscriptionList = new java.util.ArrayList<org.chocolate_milk.model.ListEventSubscription>(); this._txnEventSubscriptionList = new java.util.ArrayList<org.chocolate_milk.model.TxnEventSubscription>(); } //-----------/ //- Methods -/ //-----------/ /** * * * @param vListEventSubscription * @throws java.lang.IndexOutOfBoundsException if the index * given is outside the bounds of the collection */ public void addListEventSubscription( final org.chocolate_milk.model.ListEventSubscription vListEventSubscription) throws java.lang.IndexOutOfBoundsException { this._listEventSubscriptionList.add(vListEventSubscription); } /** * * * @param index * @param vListEventSubscription * @throws java.lang.IndexOutOfBoundsException if the index * given is outside the bounds of the collection */ public void addListEventSubscription( final int index, final org.chocolate_milk.model.ListEventSubscription vListEventSubscription) throws java.lang.IndexOutOfBoundsException { this._listEventSubscriptionList.add(index, vListEventSubscription); } /** * * * @param vTxnEventSubscription * @throws java.lang.IndexOutOfBoundsException if the index * given is outside the bounds of the collection */ public void addTxnEventSubscription( final org.chocolate_milk.model.TxnEventSubscription vTxnEventSubscription) throws java.lang.IndexOutOfBoundsException { this._txnEventSubscriptionList.add(vTxnEventSubscription); } /** * * * @param index * @param vTxnEventSubscription * @throws java.lang.IndexOutOfBoundsException if the index * given is outside the bounds of the collection */ public void addTxnEventSubscription( final int index, final org.chocolate_milk.model.TxnEventSubscription vTxnEventSubscription) throws java.lang.IndexOutOfBoundsException { this._txnEventSubscriptionList.add(index, vTxnEventSubscription); } /** * Method enumerateListEventSubscription. * * @return an Enumeration over all possible elements of this * collection */ public java.util.Enumeration<? extends org.chocolate_milk.model.ListEventSubscription> enumerateListEventSubscription( ) { return java.util.Collections.enumeration(this._listEventSubscriptionList); } /** * Method enumerateTxnEventSubscription. * * @return an Enumeration over all possible elements of this * collection */ public java.util.Enumeration<? extends org.chocolate_milk.model.TxnEventSubscription> enumerateTxnEventSubscription( ) { return java.util.Collections.enumeration(this._txnEventSubscriptionList); } /** * Returns the value of field 'COMCallbackInfo'. * * @return the value of field 'COMCallbackInfo'. */ public org.chocolate_milk.model.COMCallbackInfo getCOMCallbackInfo( ) { return this._COMCallbackInfo; } /** * Returns the value of field 'deliverOwnEvents'. * * @return the value of field 'DeliverOwnEvents'. */ public java.lang.String getDeliverOwnEvents( ) { return this._deliverOwnEvents; } /** * Returns the value of field 'deliveryPolicy'. * * @return the value of field 'DeliveryPolicy'. */ public org.chocolate_milk.model.types.DeliveryPolicyType getDeliveryPolicy( ) { return this._deliveryPolicy; } /** * Method getListEventSubscription. * * @param index * @throws java.lang.IndexOutOfBoundsException if the index * given is outside the bounds of the collection * @return the value of the * org.chocolate_milk.model.ListEventSubscription at the given * index */ public org.chocolate_milk.model.ListEventSubscription getListEventSubscription( final int index) throws java.lang.IndexOutOfBoundsException { // check bounds for index if (index < 0 || index >= this._listEventSubscriptionList.size()) { throw new IndexOutOfBoundsException("getListEventSubscription: Index value '" + index + "' not in range [0.." + (this._listEventSubscriptionList.size() - 1) + "]"); } return (org.chocolate_milk.model.ListEventSubscription) _listEventSubscriptionList.get(index); } /** * Method getListEventSubscription.Returns the contents of the * collection in an Array. <p>Note: Just in case the * collection contents are changing in another thread, we pass * a 0-length Array of the correct type into the API call. * This way we <i>know</i> that the Array returned is of * exactly the correct length. * * @return this collection as an Array */ public org.chocolate_milk.model.ListEventSubscription[] getListEventSubscription( ) { org.chocolate_milk.model.ListEventSubscription[] array = new org.chocolate_milk.model.ListEventSubscription[0]; return (org.chocolate_milk.model.ListEventSubscription[]) this._listEventSubscriptionList.toArray(array); } /** * Method getListEventSubscriptionCount. * * @return the size of this collection */ public int getListEventSubscriptionCount( ) { return this._listEventSubscriptionList.size(); } /** * Returns the value of field 'subscriberID'. * * @return the value of field 'SubscriberID'. */ public java.lang.String getSubscriberID( ) { return this._subscriberID; } /** * Returns the value of field 'timeCreated'. * * @return the value of field 'TimeCreated'. */ public java.lang.String getTimeCreated( ) { return this._timeCreated; } /** * Returns the value of field 'timeLastProcessed'. * * @return the value of field 'TimeLastProcessed'. */ public java.lang.String getTimeLastProcessed( ) { return this._timeLastProcessed; } /** * Returns the value of field 'trackLostEvents'. * * @return the value of field 'TrackLostEvents'. */ public org.chocolate_milk.model.types.TrackLostEventsType getTrackLostEvents( ) { return this._trackLostEvents; } /** * Method getTxnEventSubscription. * * @param index * @throws java.lang.IndexOutOfBoundsException if the index * given is outside the bounds of the collection * @return the value of the * org.chocolate_milk.model.TxnEventSubscription at the given * index */ public org.chocolate_milk.model.TxnEventSubscription getTxnEventSubscription( final int index) throws java.lang.IndexOutOfBoundsException { // check bounds for index if (index < 0 || index >= this._txnEventSubscriptionList.size()) { throw new IndexOutOfBoundsException("getTxnEventSubscription: Index value '" + index + "' not in range [0.." + (this._txnEventSubscriptionList.size() - 1) + "]"); } return (org.chocolate_milk.model.TxnEventSubscription) _txnEventSubscriptionList.get(index); } /** * Method getTxnEventSubscription.Returns the contents of the * collection in an Array. <p>Note: Just in case the * collection contents are changing in another thread, we pass * a 0-length Array of the correct type into the API call. * This way we <i>know</i> that the Array returned is of * exactly the correct length. * * @return this collection as an Array */ public org.chocolate_milk.model.TxnEventSubscription[] getTxnEventSubscription( ) { org.chocolate_milk.model.TxnEventSubscription[] array = new org.chocolate_milk.model.TxnEventSubscription[0]; return (org.chocolate_milk.model.TxnEventSubscription[]) this._txnEventSubscriptionList.toArray(array); } /** * Method getTxnEventSubscriptionCount. * * @return the size of this collection */ public int getTxnEventSubscriptionCount( ) { return this._txnEventSubscriptionList.size(); } /** * Method isValid. * * @return true if this object is valid according to the schema */ public boolean isValid( ) { try { validate(); } catch (org.exolab.castor.xml.ValidationException vex) { return false; } return true; } /** * Method iterateListEventSubscription. * * @return an Iterator over all possible elements in this * collection */ public java.util.Iterator<? extends org.chocolate_milk.model.ListEventSubscription> iterateListEventSubscription( ) { return this._listEventSubscriptionList.iterator(); } /** * Method iterateTxnEventSubscription. * * @return an Iterator over all possible elements in this * collection */ public java.util.Iterator<? extends org.chocolate_milk.model.TxnEventSubscription> iterateTxnEventSubscription( ) { return this._txnEventSubscriptionList.iterator(); } /** * * * @param out * @throws org.exolab.castor.xml.MarshalException if object is * null or if any SAXException is thrown during marshaling * @throws org.exolab.castor.xml.ValidationException if this * object is an invalid instance according to the schema */ public void marshal( final java.io.Writer out) throws org.exolab.castor.xml.MarshalException, org.exolab.castor.xml.ValidationException { org.exolab.castor.xml.Marshaller.marshal(this, out); } /** * * * @param handler * @throws java.io.IOException if an IOException occurs during * marshaling * @throws org.exolab.castor.xml.ValidationException if this * object is an invalid instance according to the schema * @throws org.exolab.castor.xml.MarshalException if object is * null or if any SAXException is thrown during marshaling */ public void marshal( final org.xml.sax.ContentHandler handler) throws java.io.IOException, org.exolab.castor.xml.MarshalException, org.exolab.castor.xml.ValidationException { org.exolab.castor.xml.Marshaller.marshal(this, handler); } /** */ public void removeAllListEventSubscription( ) { this._listEventSubscriptionList.clear(); } /** */ public void removeAllTxnEventSubscription( ) { this._txnEventSubscriptionList.clear(); } /** * Method removeListEventSubscription. * * @param vListEventSubscription * @return true if the object was removed from the collection. */ public boolean removeListEventSubscription( final org.chocolate_milk.model.ListEventSubscription vListEventSubscription) { boolean removed = _listEventSubscriptionList.remove(vListEventSubscription); return removed; } /** * Method removeListEventSubscriptionAt. * * @param index * @return the element removed from the collection */ public org.chocolate_milk.model.ListEventSubscription removeListEventSubscriptionAt( final int index) { java.lang.Object obj = this._listEventSubscriptionList.remove(index); return (org.chocolate_milk.model.ListEventSubscription) obj; } /** * Method removeTxnEventSubscription. * * @param vTxnEventSubscription * @return true if the object was removed from the collection. */ public boolean removeTxnEventSubscription( final org.chocolate_milk.model.TxnEventSubscription vTxnEventSubscription) { boolean removed = _txnEventSubscriptionList.remove(vTxnEventSubscription); return removed; } /** * Method removeTxnEventSubscriptionAt. * * @param index * @return the element removed from the collection */ public org.chocolate_milk.model.TxnEventSubscription removeTxnEventSubscriptionAt( final int index) { java.lang.Object obj = this._txnEventSubscriptionList.remove(index); return (org.chocolate_milk.model.TxnEventSubscription) obj; } /** * Sets the value of field 'COMCallbackInfo'. * * @param COMCallbackInfo the value of field 'COMCallbackInfo'. */ public void setCOMCallbackInfo( final org.chocolate_milk.model.COMCallbackInfo COMCallbackInfo) { this._COMCallbackInfo = COMCallbackInfo; } /** * Sets the value of field 'deliverOwnEvents'. * * @param deliverOwnEvents the value of field 'deliverOwnEvents' */ public void setDeliverOwnEvents( final java.lang.String deliverOwnEvents) { this._deliverOwnEvents = deliverOwnEvents; } /** * Sets the value of field 'deliveryPolicy'. * * @param deliveryPolicy the value of field 'deliveryPolicy'. */ public void setDeliveryPolicy( final org.chocolate_milk.model.types.DeliveryPolicyType deliveryPolicy) { this._deliveryPolicy = deliveryPolicy; } /** * * * @param index * @param vListEventSubscription * @throws java.lang.IndexOutOfBoundsException if the index * given is outside the bounds of the collection */ public void setListEventSubscription( final int index, final org.chocolate_milk.model.ListEventSubscription vListEventSubscription) throws java.lang.IndexOutOfBoundsException { // check bounds for index if (index < 0 || index >= this._listEventSubscriptionList.size()) { throw new IndexOutOfBoundsException("setListEventSubscription: Index value '" + index + "' not in range [0.." + (this._listEventSubscriptionList.size() - 1) + "]"); } this._listEventSubscriptionList.set(index, vListEventSubscription); } /** * * * @param vListEventSubscriptionArray */ public void setListEventSubscription( final org.chocolate_milk.model.ListEventSubscription[] vListEventSubscriptionArray) { //-- copy array _listEventSubscriptionList.clear(); for (int i = 0; i < vListEventSubscriptionArray.length; i++) { this._listEventSubscriptionList.add(vListEventSubscriptionArray[i]); } } /** * Sets the value of field 'subscriberID'. * * @param subscriberID the value of field 'subscriberID'. */ public void setSubscriberID( final java.lang.String subscriberID) { this._subscriberID = subscriberID; } /** * Sets the value of field 'timeCreated'. * * @param timeCreated the value of field 'timeCreated'. */ public void setTimeCreated( final java.lang.String timeCreated) { this._timeCreated = timeCreated; } /** * Sets the value of field 'timeLastProcessed'. * * @param timeLastProcessed the value of field * 'timeLastProcessed'. */ public void setTimeLastProcessed( final java.lang.String timeLastProcessed) { this._timeLastProcessed = timeLastProcessed; } /** * Sets the value of field 'trackLostEvents'. * * @param trackLostEvents the value of field 'trackLostEvents'. */ public void setTrackLostEvents( final org.chocolate_milk.model.types.TrackLostEventsType trackLostEvents) { this._trackLostEvents = trackLostEvents; } /** * * * @param index * @param vTxnEventSubscription * @throws java.lang.IndexOutOfBoundsException if the index * given is outside the bounds of the collection */ public void setTxnEventSubscription( final int index, final org.chocolate_milk.model.TxnEventSubscription vTxnEventSubscription) throws java.lang.IndexOutOfBoundsException { // check bounds for index if (index < 0 || index >= this._txnEventSubscriptionList.size()) { throw new IndexOutOfBoundsException("setTxnEventSubscription: Index value '" + index + "' not in range [0.." + (this._txnEventSubscriptionList.size() - 1) + "]"); } this._txnEventSubscriptionList.set(index, vTxnEventSubscription); } /** * * * @param vTxnEventSubscriptionArray */ public void setTxnEventSubscription( final org.chocolate_milk.model.TxnEventSubscription[] vTxnEventSubscriptionArray) { //-- copy array _txnEventSubscriptionList.clear(); for (int i = 0; i < vTxnEventSubscriptionArray.length; i++) { this._txnEventSubscriptionList.add(vTxnEventSubscriptionArray[i]); } } /** * Method unmarshal. * * @param reader * @throws org.exolab.castor.xml.MarshalException if object is * null or if any SAXException is thrown during marshaling * @throws org.exolab.castor.xml.ValidationException if this * object is an invalid instance according to the schema * @return the unmarshaled * org.chocolate_milk.model.DataEventSubscriptionRet */ public static org.chocolate_milk.model.DataEventSubscriptionRet unmarshal( final java.io.Reader reader) throws org.exolab.castor.xml.MarshalException, org.exolab.castor.xml.ValidationException { return (org.chocolate_milk.model.DataEventSubscriptionRet) org.exolab.castor.xml.Unmarshaller.unmarshal(org.chocolate_milk.model.DataEventSubscriptionRet.class, reader); } /** * * * @throws org.exolab.castor.xml.ValidationException if this * object is an invalid instance according to the schema */ public void validate( ) throws org.exolab.castor.xml.ValidationException { org.exolab.castor.xml.Validator validator = new org.exolab.castor.xml.Validator(); validator.validate(this); } }
lgpl-3.0
visape-uni/PES_2Change
TwoChange/app/src/main/java/pes/twochange/presentation/controller/ChatActivity.java
7690
package pes.twochange.presentation.controller; import android.annotation.TargetApi; import android.content.DialogInterface; import android.content.Intent; import android.content.pm.PackageManager; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.media.MediaScannerConnection; import android.net.Uri; import android.os.Build; import android.os.Environment; import android.provider.MediaStore; import android.provider.Settings; import android.support.annotation.NonNull; import android.support.design.widget.FloatingActionButton; import android.support.design.widget.Snackbar; import android.support.v7.app.AlertDialog; import android.support.v7.app.AppCompatActivity; import android.os.Bundle; import android.text.format.DateFormat; import android.util.Log; import android.view.Menu; import android.view.MenuItem; import android.view.View; import android.widget.EditText; import android.widget.LinearLayout; import android.widget.ListView; import android.widget.RelativeLayout; import android.widget.TextView; import android.widget.Toast; import com.firebase.ui.database.FirebaseListAdapter; import com.google.firebase.database.DatabaseReference; import com.google.firebase.database.FirebaseDatabase; import com.google.firebase.messaging.FirebaseMessaging; import java.io.File; import pes.twochange.R; import pes.twochange.domain.callback.BlockedResponse; import pes.twochange.domain.model.Chat; import pes.twochange.domain.model.Message; import pes.twochange.domain.themes.ChatTheme; import pes.twochange.domain.themes.SettingsTheme; import pes.twochange.presentation.controller.BaseActivity; import pes.twochange.services.NotificationSender; import static android.Manifest.permission.CAMERA; import static android.Manifest.permission.WRITE_EXTERNAL_STORAGE; public class ChatActivity extends BaseActivity { private static final String TAG = "ChatActivitiy"; private String userSender; private String userReciver; private DatabaseReference mFirebaseChatRefSender; private DatabaseReference mFirebaseChatRefReciver; FloatingActionButton sendBtn; private RelativeLayout mRlView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_chat); //Relative view mRlView = (RelativeLayout) findViewById(R.id.rl_view); //Coger chat pasado como extra en el intent final Chat chat = (Chat) getIntent().getExtras().getSerializable("chat"); //User sender userSender = chat.getMessageSender(); //User reciver userReciver = chat.getMessageReciver(); //Suscribirse al topic para recibir notificaciones de chat FirebaseMessaging.getInstance() .subscribeToTopic(userReciver); //Instance to Firebase database FirebaseDatabase mFirebaseDatabase = FirebaseDatabase.getInstance(); //Firebase ref to sender's chat mFirebaseChatRefSender = mFirebaseDatabase.getReference().child("chats").child(userSender).child(userReciver); //Firebase ref to reciver's chat mFirebaseChatRefReciver = mFirebaseDatabase.getReference().child("chats").child(userReciver).child(userSender); //Display the messages of the DB into the list view displayChatMessage(); //OnClickListener to send messages sendBtn = (FloatingActionButton)findViewById(R.id.sender_btn); sendBtn.setOnClickListener(new View.OnClickListener() { @Override public void onClick (View view) { //Get the message to string EditText messageInput = (EditText) findViewById(R.id.message_input); String content = messageInput.getText().toString(); //Delete blank spaces of the messages content = content.trim(); if (!content.isEmpty()) { ChatTheme.getInstance(chat).sendChatMessage(content); //Put the text field empty again messageInput.setText(""); } } }); } @Override protected int currentMenuItemIndex() { return CHAT_ACTIVITY; } @Override public boolean onCreateOptionsMenu (Menu menu) { getMenuInflater().inflate(R.menu.menu_chat, menu); return true; } @Override public boolean onOptionsItemSelected(MenuItem item) { switch (item.getItemId()) { case R.id.send_details: Chat chat = new Chat(userSender,userReciver); ChatTheme.getInstance(chat).sendContactDetails(); break; case R.id.block_user: SettingsTheme.getInstance(userSender).userIsBlocked(userReciver, new BlockedResponse() { @Override public void isBlocked(boolean blocked, String userblocked) { if (blocked) Toast.makeText(ChatActivity.this, "User unblocked successfully", Toast.LENGTH_SHORT).show(); else Toast.makeText(ChatActivity.this, "User blocked successfully", Toast.LENGTH_SHORT).show(); } }); SettingsTheme.getInstance(userSender).blockUser(userReciver); break; } return super.onOptionsItemSelected(item); } private void displayChatMessage() { ListView messagesList = (ListView)findViewById(R.id.messages_list); //Firebase adapter for getting the messages FirebaseListAdapter<Message> adapter = new FirebaseListAdapter<Message>(this, Message.class, R.layout.message, mFirebaseChatRefSender) { @Override protected void populateView(View v, Message model, int position) { //Getting the textviews of the Message's layout TextView messageContent, messageSender, messageTime; messageContent = (TextView) v.findViewById(R.id.message_content); messageSender = (TextView) v.findViewById(R.id.message_sender); messageTime = (TextView) v.findViewById(R.id.message_time); LinearLayout layoutMessageContent = (LinearLayout) v.findViewById(R.id.layout_message_content); RelativeLayout.LayoutParams rl = (RelativeLayout.LayoutParams) layoutMessageContent.getLayoutParams(); if (model.getMessageSender().equals(userSender)) { //If it's a message from the sender use the green (message) and align right layoutMessageContent.setBackgroundResource(R.drawable.ic_send_message); rl.addRule(RelativeLayout.ALIGN_PARENT_LEFT,0); rl.addRule(RelativeLayout.ALIGN_PARENT_RIGHT); } else { //If it's a message from the reciver use the orange (message) and align left layoutMessageContent.setBackgroundResource(R.drawable.ic_recive_message); rl.addRule(RelativeLayout.ALIGN_PARENT_RIGHT,0); rl.addRule(RelativeLayout.ALIGN_PARENT_LEFT); } //Set with the content of the message, the message sender, and the time when the message was sent messageContent.setText(model.getMessageContent()); messageSender.setText(model.getMessageSender()); messageTime.setText(DateFormat.format("dd-MM-yyyy (HH:mm)", model.getMessageTime())); } }; //Use the firebase adapter on the listview messagesList.setAdapter(adapter); } }
lgpl-3.0
InteractiveSystemsGroup/GamificationEngine-Kinben
src/main/java/info/interactivesystems/gamificationengine/utils/ImageUtils.java
2075
package info.interactivesystems.gamificationengine.utils; import info.interactivesystems.gamificationengine.api.exeption.ApiError; import java.awt.image.BufferedImage; import java.io.ByteArrayOutputStream; import java.io.IOException; import java.net.URL; import javax.imageio.ImageIO; import javax.ws.rs.core.Response; import org.apache.commons.codec.binary.Base64; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class ImageUtils { private static final Logger LOGGER = LoggerFactory.getLogger(ImageUtils.class); /** * The passed String represents an URL. With this URL a byte[] is created from the image file that was passed as a String that * represents an URL. The format of the image has to be .jpg or .png. Otherwise * an exception is thrown with the hint, that the URL was not valid. * * @param fileLocation * The path an image can be located. This is an URL. * @return byte[] of the image content. */ public static byte[] imageToByte(String fileLocation) { BufferedImage originalImage; byte[] byteImage = null; String format = fileLocation.substring(fileLocation.lastIndexOf(".") + 1); if (format.equals("png") || format.equals("jpg")) { try { URL fileImage = new URL(fileLocation); originalImage = ImageIO.read(fileImage); ByteArrayOutputStream baos = new ByteArrayOutputStream(); ImageIO.write(originalImage, format, baos); byteImage = baos.toByteArray(); } catch (IOException e) { throw new ApiError(Response.Status.FORBIDDEN, "No valid url was transferred"); } }else{ throw new ApiError(Response.Status.FORBIDDEN, "The image format has to be .png or .jpg"); } return byteImage; } /** * The passed byte array is Base64-encoded to ensure that the data is transmitted * correctly as String. * * @param bytes * The byte array that should be encoded. * @return The Base64 encoded String of the byte array. */ public static String encodeByteArrayToBase64(byte[] bytes){ String b64 = Base64.encodeBase64String(bytes); return b64; } }
lgpl-3.0
NavidK0/Carbon
src/main/java/com/lastabyss/carbon/ai/NavigationPath.java
2739
package com.lastabyss.carbon.ai; public class NavigationPath { private NavigationPathPoint[] pathPoints = new NavigationPathPoint[1024]; private int count; public NavigationPathPoint addPoint(NavigationPathPoint pathPoint) { if (pathPoint.index >= 0) { throw new IllegalStateException("OW KNOWS!"); } else { if (this.count == this.pathPoints.length) { NavigationPathPoint[] var2 = new NavigationPathPoint[this.count << 1]; System.arraycopy(this.pathPoints, 0, var2, 0, this.count); this.pathPoints = var2; } this.pathPoints[this.count] = pathPoint; pathPoint.index = this.count; this.sortBack(this.count++); return pathPoint; } } public void clearPath() { this.count = 0; } public NavigationPathPoint remove() { NavigationPathPoint pathPoint = this.pathPoints[0]; this.pathPoints[0] = this.pathPoints[--this.count]; this.pathPoints[this.count] = null; if (this.count > 0) { this.sortForward(0); } pathPoint.index = -1; return pathPoint; } public void changeDistance(NavigationPathPoint pathPoint, float distance) { float var3 = pathPoint.distanceToTarget; pathPoint.distanceToTarget = distance; if (distance < var3) { this.sortBack(pathPoint.index); } else { this.sortForward(pathPoint.index); } } private void sortBack(int index) { NavigationPathPoint pathPoint = this.pathPoints[index]; int i; for (float distance = pathPoint.distanceToTarget; index > 0; index = i) { i = index - 1 >> 1; NavigationPathPoint otherPathPoint = this.pathPoints[i]; if (distance >= otherPathPoint.distanceToTarget) { break; } this.pathPoints[index] = otherPathPoint; otherPathPoint.index = index; } this.pathPoints[index] = pathPoint; pathPoint.index = index; } private void sortForward(int index) { NavigationPathPoint pathPoint = this.pathPoints[index]; float distance = pathPoint.distanceToTarget; while (true) { int i = 1 + (index << 1); int j = i + 1; if (i >= this.count) { break; } NavigationPathPoint var6 = this.pathPoints[i]; float var7 = var6.distanceToTarget; NavigationPathPoint var8; float var9; if (j >= this.count) { var8 = null; var9 = Float.POSITIVE_INFINITY; } else { var8 = this.pathPoints[j]; var9 = var8.distanceToTarget; } if (var7 < var9) { if (var7 >= distance) { break; } this.pathPoints[index] = var6; var6.index = index; index = i; } else { if (var9 >= distance) { break; } this.pathPoints[index] = var8; var8.index = index; index = j; } } this.pathPoints[index] = pathPoint; pathPoint.index = index; } public boolean isEmpty() { return this.count == 0; } }
lgpl-3.0
exodev/social
webapp/portlet/src/main/java/org/exoplatform/social/portlet/UISpaceActivityStreamPortlet.java
2786
/* * Copyright (C) 2003-2010 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.social.portlet; import org.exoplatform.social.core.space.model.Space; import org.exoplatform.social.core.space.spi.SpaceService; import org.exoplatform.social.webui.Utils; import org.exoplatform.social.webui.composer.PopupContainer; import org.exoplatform.social.webui.composer.UIComposer; import org.exoplatform.social.webui.space.UISpaceActivitiesDisplay; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.core.UIPortletApplication; import org.exoplatform.webui.core.lifecycle.UIApplicationLifecycle; /** * UISpaceActivityPortlet.java * <br> * Displaying space activities and its member's posts * * @author <a href="http://hoatle.net">hoatle</a> * @since Apr 6, 2010 */ @ComponentConfig( lifecycle = UIApplicationLifecycle.class, template = "war:/groovy/social/portlet/UISpaceActivityStreamPortlet.gtmpl" ) public class UISpaceActivityStreamPortlet extends UIPortletApplication { private Space space; private UISpaceActivitiesDisplay uiDisplaySpaceActivities; /** * constructor */ public UISpaceActivityStreamPortlet() throws Exception { UIComposer uiComposer = addChild(UIComposer.class, null, null); uiComposer.setPostContext(UIComposer.PostContext.SPACE); uiDisplaySpaceActivities = addChild(UISpaceActivitiesDisplay.class, null, null); space = getSpaceService().getSpaceByUrl(Utils.getSpaceUrlByContext()); uiDisplaySpaceActivities.setSpace(space); uiComposer.setActivityDisplay(uiDisplaySpaceActivities); addChild(PopupContainer.class, null, "HiddenContainer_" + hashCode()); } public SpaceService getSpaceService() { return getApplicationComponent(SpaceService.class); } public Space getSpace() { return space; } public void setSpace(Space space) { this.space = space; } /** * resets to reload all activities * * @throws Exception */ public void refresh() throws Exception { space = getSpaceService().getSpaceByUrl(Utils.getSpaceUrlByContext()); uiDisplaySpaceActivities.setSpace(space); } }
lgpl-3.0
lbndev/sonarqube
server/sonar-process/src/test/java/org/sonar/process/ProcessPropertiesTest.java
2074
/* * 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.process; import java.util.Properties; import org.junit.Test; import org.sonar.test.TestUtils; import static org.assertj.core.api.Assertions.assertThat; public class ProcessPropertiesTest { @Test public void init_defaults() { Props props = new Props(new Properties()); ProcessProperties.completeDefaults(props); assertThat(props.value("sonar.search.javaOpts")).contains("-Xmx"); assertThat(props.valueAsInt("sonar.jdbc.maxActive")).isEqualTo(60); } @Test public void do_not_override_existing_properties() { Properties p = new Properties(); p.setProperty("sonar.jdbc.username", "angela"); Props props = new Props(p); ProcessProperties.completeDefaults(props); assertThat(props.value("sonar.jdbc.username")).isEqualTo("angela"); } @Test public void use_random_port_if_zero() { Properties p = new Properties(); p.setProperty("sonar.search.port", "0"); Props props = new Props(p); ProcessProperties.completeDefaults(props); assertThat(props.valueAsInt("sonar.search.port")).isGreaterThan(0); } @Test public void private_constructor() { assertThat(TestUtils.hasOnlyPrivateConstructors(ProcessProperties.class)).isTrue(); } }
lgpl-3.0
schemaspy/schemaspy
src/test/java/org/schemaspy/input/dbms/service/TableServiceAddForeignKeyTest.java
9126
/* * Copyright (C) 2019 Nils Petzaell * * This file is part of SchemaSpy. * * SchemaSpy is free software: you can redistribute it and/or modify * it under the terms of the GNU Lesser General Public License as published by * the Free Software Foundation, either version 3 of the License, or * (at your option) any later version. * * SchemaSpy is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with SchemaSpy. If not, see <http://www.gnu.org/licenses/>. */ package org.schemaspy.input.dbms.service; import org.junit.Before; import org.junit.Rule; import org.junit.Test; import org.schemaspy.Config; import org.schemaspy.input.dbms.service.helper.ImportForeignKey; import org.schemaspy.model.*; import org.schemaspy.testing.ConfigRule; import org.schemaspy.testing.Logger; import org.schemaspy.testing.LoggingRule; import java.sql.DatabaseMetaData; import java.sql.ResultSet; import java.sql.SQLException; import java.util.HashMap; import static org.assertj.core.api.Assertions.assertThat; import static org.mockito.ArgumentMatchers.anyString; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class TableServiceAddForeignKeyTest { @Rule public LoggingRule loggingRule = new LoggingRule(); @Rule public ConfigRule configRule = new ConfigRule(); private SqlService sqlService = mock(SqlService.class); private ColumnService columnService = new ColumnService(sqlService); private IndexService indexService = new IndexService(sqlService); private TableService tableService = new TableService(sqlService, columnService, indexService); private DbmsMeta dbmsMeta = mock(DbmsMeta.class); private Database database; private Table table; @Before public void setup() { database = new Database(dbmsMeta, "tableServiceTest","addFK", "tst"); table = new Table(database, database.getCatalog().getName(), database.getSchema().getName(), "mainTable", "mainTable"); database.getTablesMap().put(table.getName(), table); } @Test @Logger(value = TableService.class, level = "debug") public void excludingTable() throws SQLException { Config.getInstance().setTableExclusions("excludeMePlease"); ImportForeignKey foreignKey = new ImportForeignKey.Builder() .withFkName("notNull") .withFkColumnName(null) .withPkTableCat("CAT") .withPkTableSchema("S") .withPkTableName("excludeMePlease") .withPkColumnName("aColumn") .withUpdateRule(0) .withDeleteRule(0) .build(); tableService.addForeignKey(database, null, foreignKey, new HashMap<>()); assertThat(loggingRule.getLog()).contains("Ignoring CAT.S.excludeMePlease referenced by FK notNull"); } @Test @Logger(TableService.class) public void addsForeignKeyIfMissing() throws SQLException { ImportForeignKey foreignKey = new ImportForeignKey.Builder() .withFkName("newFK") .withFkColumnName("fkColumn") .withPkTableCat("pkCat") .withPkTableSchema("pkSchema") .withPkTableName("pkTable") .withPkColumnName("pkColumn") .withUpdateRule(0) .withDeleteRule(0) .build(); tableService.addForeignKey(database, table, foreignKey, database.getTablesMap()); assertThat(table.getForeignKeysMap().get("newFK")).isNotNull(); assertThat(table.getForeignKeysMap().get("newFK").getName()).isEqualTo("newFK"); assertThat(loggingRule.getLog()).contains("Couldn't add FK 'newFK' to table 'mainTable' - Column 'fkColumn' doesn't exist"); } @Test @Logger(TableService.class) public void usesExistingForeignKeyIfExists() throws SQLException { table.getForeignKeysMap().put("existingFK", new ForeignKeyConstraint(table, "existingFK", 1,1)); ImportForeignKey foreignKey = new ImportForeignKey.Builder() .withFkName("existingFK") .withFkColumnName("fkColumn") .withPkTableCat("pkCat") .withPkTableSchema("pkSchema") .withPkTableName("pkTable") .withPkColumnName("pkColumn") .withUpdateRule(0) .withDeleteRule(0) .build(); tableService.addForeignKey(database, table, foreignKey, new HashMap<>()); assertThat(table.getForeignKeysMap().get("existingFK").getUpdateRule()).isEqualTo(1); assertThat(table.getForeignKeysMap().get("existingFK").getDeleteRule()).isEqualTo(1); assertThat(loggingRule.getLog()).contains("Couldn't add FK 'existingFK' to table 'mainTable' - Column 'fkColumn' doesn't exist"); } @Test @Logger(value = TableService.class, level = "debug") public void addingRemoteTable() throws SQLException { DatabaseMetaData databaseMetaData = mock(DatabaseMetaData.class); ResultSet resultSet = mock(ResultSet.class); when(resultSet.next()).thenReturn(false); when(databaseMetaData.getColumns(anyString(), anyString(), anyString(), anyString())).thenReturn(resultSet); when(databaseMetaData.getImportedKeys(anyString(), anyString(), anyString())).thenReturn(resultSet); when(sqlService.getDatabaseMetaData()).thenReturn(databaseMetaData); TableColumn childColumn = new TableColumn(table); childColumn.setId(0); childColumn.setName("childColumn"); table.getColumnsMap().put(childColumn.getName(), childColumn); ImportForeignKey foreignKey = new ImportForeignKey.Builder() .withFkName("withChild") .withFkColumnName("childColumn") .withPkTableCat("other") .withPkTableSchema("other") .withPkTableName("parent") .withPkColumnName("parent") .withUpdateRule(0) .withDeleteRule(0) .build(); tableService.addForeignKey(database, table, foreignKey, database.getTablesMap()); String log = loggingRule.getLog(); assertThat(log).contains("Adding remote table other.other.parent"); assertThat(log).contains("Couldn't add FK 'withChild' to table 'mainTable' - Column 'parent' doesn't exist in table 'parent'"); assertThat(database.getRemoteTablesMap().get("other.other.parent")).isNotNull(); assertThat(table.getForeignKeysMap().get("withChild")).isNotNull(); } @Test public void addedForeignKeyAndWiring() throws SQLException { TableColumn childColumn = new TableColumn(table); childColumn.setId(0); childColumn.setName("childColumn"); table.getColumnsMap().put(childColumn.getName(), childColumn); RemoteTable remoteTable = new RemoteTable(database, "other", "other", "parent", "tst"); database.getRemoteTablesMap().clear(); database.getRemoteTablesMap().put("other.other.parent", remoteTable); TableColumn parentColumn = new TableColumn(remoteTable); parentColumn.setId(0); parentColumn.setName("parent"); remoteTable.getColumnsMap().put(parentColumn.getName(), parentColumn); assertThat(childColumn.getChildren().size()).isEqualTo(0); assertThat(childColumn.getParents().size()).isEqualTo(0); assertThat(parentColumn.getChildren().size()).isEqualTo(0); assertThat(parentColumn.getParents().size()).isEqualTo(0); assertThat(table.getMaxChildren()).isEqualTo(0); assertThat(table.getMaxParents()).isEqualTo(0); assertThat(remoteTable.getMaxChildren()).isEqualTo(0); assertThat(remoteTable.getMaxParents()).isEqualTo(0); ImportForeignKey foreignKey = new ImportForeignKey.Builder() .withFkName("withChild") .withFkColumnName("childColumn") .withPkTableCat("other") .withPkTableSchema("other") .withPkTableName("parent") .withPkColumnName("parent") .withUpdateRule(0) .withDeleteRule(0) .build(); tableService.addForeignKey(database, table, foreignKey, database.getTablesMap()); assertThat(childColumn.getChildren().size()).isEqualTo(0); assertThat(childColumn.getParents().size()).isEqualTo(1); assertThat(parentColumn.getChildren().size()).isEqualTo(1); assertThat(parentColumn.getParents().size()).isEqualTo(0); assertThat(table.getMaxChildren()).isEqualTo(0); assertThat(table.getMaxParents()).isEqualTo(1); assertThat(remoteTable.getMaxChildren()).isEqualTo(1); assertThat(remoteTable.getMaxParents()).isEqualTo(0); } }
lgpl-3.0
premium-minds/billy
billy-france/src/main/java/com/premiumminds/billy/france/services/documents/exceptions/InvalidInvoiceTypeException.java
1347
/* * Copyright (C) 2017 Premium Minds. * * This file is part of billy france (FR Pack). * * billy france (FR Pack) 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. * * billy france (FR Pack) 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 billy france (FR Pack). If not, see <http://www.gnu.org/licenses/>. */ package com.premiumminds.billy.france.services.documents.exceptions; public class InvalidInvoiceTypeException extends FRDocumentIssuingException { private static final long serialVersionUID = 1L; public InvalidInvoiceTypeException(String series, String type, String expectedType) { super("Invalid invoice type " + type + "in series " + series + " when expected " + expectedType); } public InvalidInvoiceTypeException(String series, String type) { super("Invalid invoice type " + type + "in series " + series); } }
lgpl-3.0
midoblgsm/occi4java
http/src/main/java/occi/http/OcciRestNetworkInterface.java
12950
/** * Copyright (C) 2010-2011 Sebastian Heckmann, Sebastian Laag * * Contact Email: <sebastian.heckmann@udo.edu>, <sebastian.laag@udo.edu> * * Contact Email for Autonomic Resources: <mohamed.mohamed@telecom-sudparis.eu> * * Licensed under the GNU LESSER GENERAL PUBLIC LICENSE, Version 3.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.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 occi.http; import java.util.HashMap; import java.util.HashSet; import java.util.Set; import java.util.StringTokenizer; import java.util.UUID; import occi.config.OcciConfig; import occi.core.Kind; import occi.core.Mixin; import occi.http.check.OcciCheck; import occi.infrastructure.Network; import occi.infrastructure.Network.State; import occi.infrastructure.links.NetworkInterface; import org.restlet.Response; import org.restlet.data.Form; import org.restlet.data.Status; import org.restlet.representation.Representation; import org.restlet.resource.Delete; import org.restlet.resource.Get; import org.restlet.resource.Post; import org.restlet.resource.Put; import org.restlet.resource.ServerResource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class OcciRestNetworkInterface extends ServerResource { private static final Logger LOGGER = LoggerFactory .getLogger(OcciRestNetwork.class); private final OcciCheck occiCheck = new OcciCheck(); @Get public String getOCCIRequest() { // set occi version info getServerInfo().setAgent( OcciConfig.getInstance().config.getString("occi.version")); Form requestHeaders = (Form) getRequest().getAttributes().get( "org.restlet.http.headers"); LOGGER.debug("Current request: " + requestHeaders); String acceptCase = OcciCheck.checkCaseSensitivity( requestHeaders.toString()).get("accept"); StringBuffer buffer = new StringBuffer(); StringBuffer buffer2 = new StringBuffer(); NetworkInterface networkinterface = NetworkInterface.getNetworkInterfaceList() .get(UUID .fromString(getReference().getLastSegment().toString())); buffer.append("Category: networkinterface;"); buffer.append("\t\t scheme=\"" + networkinterface.getLink().getKind().getScheme() + "\";"); buffer.append("\r\n"); buffer.append("\t\t class=\"kind\";\n"); // buffer.append("\r\n"); buffer2.append("X-OCCI-Attribute:"); buffer2.append(" occi.networkinterface.interface=" + networkinterface.getNetworkInterface()); buffer2.append(" occi.networkinterface.mac=" + networkinterface.getMac() + " "); buffer2.append(" occi.networkinterface.state=" + networkinterface.getState() + " "); // buffer.append("Link: "); // buffer.append(networkinterface.getLink()); buffer2.append(" source=/" + networkinterface.getLink().getKind().getTerm() + "/" + networkinterface.getLink().getId()); buffer2.append(" target=/" + networkinterface.getTarget().getKind().getTerm() + "/" + networkinterface.getTarget().getId()); buffer.append(buffer2.toString()); // access the request headers and get the Accept attribute Representation representation = OcciCheck.checkContentType( requestHeaders, buffer, getResponse()); // Check the accept header if (requestHeaders.getFirstValue(acceptCase).equals("text/occi")) { // generate header rendering occiCheck.setHeaderRendering(null, networkinterface, buffer .toString(), buffer2); // set right representation and status code getResponse().setEntity(representation); getResponse().setStatus(Status.SUCCESS_OK); return " "; } // set right representation and status code getResponse().setEntity(representation); getResponse().setStatus(Status.SUCCESS_OK, buffer.toString()); return buffer.toString(); } /** * Deletes the resource which applies to the parameters in the header. * * @return string deleted or not */ @Delete public String deleteOCCIRequest() { // set occi version info getServerInfo().setAgent( OcciConfig.getInstance().config.getString("occi.version")); LOGGER.debug("Incoming delete request at network"); try { // get network resource that should be deleted NetworkInterface networkInterface = NetworkInterface.getNetworkInterfaceList() .get(UUID.fromString(getReference().getLastSegment())); // remove it from network resource list if (NetworkInterface.getNetworkInterfaceList().remove(UUID .fromString(networkInterface.getId().toString())) == null) { throw new NullPointerException( "There is no resorce with the given ID"); } // set network resource to null networkInterface = null; getResponse().setStatus(Status.SUCCESS_OK); return " "; } catch (NullPointerException e) { getResponse().setStatus(Status.CLIENT_ERROR_NOT_FOUND, e.getMessage()); return "UUID not found! " + e.toString() + "\n Network resource could not be deleted."; } catch (Exception e) { getResponse().setStatus(Status.CLIENT_ERROR_NOT_FOUND, e.getMessage()); return e.toString(); } } /** * Method to create a new network instance. * * @param representation * @return string * @throws Exception */ @Post public String postOCCIRequest(Representation representation) throws Exception { LOGGER.info("Incoming POST request."); // set occi version info getServerInfo().setAgent( OcciConfig.getInstance().config.getString("occi.version")); try { // access the request headers and get the X-OCCI-Attribute Form requestHeaders = (Form) getRequest().getAttributes().get( "org.restlet.http.headers"); LOGGER.debug("Current request: " + requestHeaders); String attributeCase = OcciCheck.checkCaseSensitivity( requestHeaders.toString()).get("x-occi-attribute"); String xocciattributes = requestHeaders.getValues(attributeCase) .replace(",", " "); LOGGER.debug("Media-Type: " + requestHeaders.getFirstValue("accept", true)); // OcciCheck.countColons(xocciattributes, 2); // split the single occi attributes and put it into a (key,value) // map LOGGER.debug("Raw X-OCCI Attributes: " + xocciattributes); StringTokenizer xoccilist = new StringTokenizer(xocciattributes); HashMap<String, Object> xoccimap = new HashMap<String, Object>(); LOGGER.debug("Tokens in XOCCIList: " + xoccilist.countTokens()); while (xoccilist.hasMoreTokens()) { String[] temp = xoccilist.nextToken().split("\\="); if (temp[0] != null && temp[1] != null) { LOGGER.debug(temp[0] + " " + temp[1] + "\n"); xoccimap.put(temp[0], temp[1]); } } // put occi attributes into a buffer for the response StringBuffer buffer = new StringBuffer(); buffer.append("occi.networkinterface.interface=").append( xoccimap.get("occi.networkinterface.interface")); buffer.append(" occi.networkinterface.mac=").append( xoccimap.get("occi.networkinterface.mac")); buffer.append(" occi.networkinterface.state=").append( xoccimap.get("occi.networkinterface.state")); Set<String> set = new HashSet<String>(); set.add("summary: "); set.add(buffer.toString()); set.add(requestHeaders.getFirstValue("scheme")); if (!requestHeaders.contains("Link")) { // create new NetworkInterface instance with the given // attributes NetworkInterface networkInterface = new NetworkInterface( (String) xoccimap .get("occi.networkinterface.interface"), (String) xoccimap.get("occi.networkinterface.mac"), occi.infrastructure.links.NetworkInterface.State.inactive, null, null); networkInterface.setKind(new Kind(null, "networkinterface", "networkinterface", null)); StringBuffer resource = new StringBuffer(); resource.append("/").append( networkInterface.getKind().getTerm()).append("/"); getRootRef().setPath(resource.toString()); // check of the category if (!"networkinterface".equalsIgnoreCase(xoccimap.get( "occi.networkinterface.Category").toString())) { throw new IllegalArgumentException( "Illegal Category type: " + xoccimap .get("occi.networkinterface.Category")); } for (Mixin mixin : Mixin.getMixins()) { if (mixin.getEntities() != null) { if (mixin.getEntities().contains(networkInterface)) { buffer.append("Category: " + mixin.getTitle() + "; scheme=\"" + mixin.getScheme() + "\"; class=\"mixin\""); } } } // Check accept header if (requestHeaders.getFirstValue("accept", true).equals( "text/occi") || requestHeaders.getFirstValue("content-type", true) .equals("text/occi")) { // Generate header rendering occiCheck.setHeaderRendering(null, networkInterface, buffer .toString(), null); getResponse().setEntity(representation); getResponse().setStatus(Status.SUCCESS_OK); } // Location Rendering in HTTP Header, not in body setLocationRef((getRootRef().toString() + networkInterface .getId())); representation = OcciCheck.checkContentType(requestHeaders, buffer, getResponse()); getResponse().setEntity(representation); // set response status getResponse().setStatus(Status.SUCCESS_OK, buffer.toString()); return Response.getCurrent().toString(); } } catch (Exception e) { e.printStackTrace(); getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST, e.toString()); return "Exception caught: " + e.toString() + "\n"; } return " "; } /** * Edit the parameters of a given resource instance. * * @param representation * @return data of altered instance * @throws Exception */ @Put public String putOCCIRequest(Representation representation) { try { // set occi version info getServerInfo().setAgent( OcciConfig.getInstance().config.getString("occi.version")); OcciCheck.isUUID(getReference().getLastSegment()); Network network = Network.getNetworkList().get(UUID .fromString(getReference().getLastSegment())); // access the request headers and get the X-OCCI-Attribute Form requestHeaders = (Form) getRequest().getAttributes().get( "org.restlet.http.headers"); LOGGER.debug("Raw Request Headers: " + requestHeaders); String xocciattributes = ""; xocciattributes = requestHeaders.getFirstValue("x-occi-attribute", true); // Check if some attributes are given by the request if (xocciattributes != null) { // Count the colons in the Request OcciCheck.countColons(xocciattributes, 1); /* * split the single occi attributes and put it into a * (key,value) map */ LOGGER.debug("Raw X-OCCI Attributes: " + xocciattributes); StringTokenizer xoccilist = new StringTokenizer(xocciattributes); HashMap<String, Object> xoccimap = new HashMap<String, Object>(); while (xoccilist.hasMoreTokens()) { String[] temp = xoccilist.nextToken().split("\\="); if (temp.length > 1 && temp[0] != null && temp[1] != null) { xoccimap.put(temp[0], temp[1]); } } LOGGER.debug("X-OCCI-Map empty?: " + xoccimap.isEmpty()); if (!xoccimap.isEmpty()) { // Change the network attribute if it is send by the request if (xoccimap.containsKey("occi.network.vlan")) { network.setVlan(Integer.parseInt(xoccimap.get( "occi.network.vlan").toString())); } if (xoccimap.containsKey("occi.network.label")) { network.setLabel(xoccimap.get("occi.network.label") .toString()); } if (xoccimap.containsKey("occi.network.state")) { network.setState(State.valueOf((String) xoccimap .get("occi.network.state"))); } // Location Rendering in HTTP Header, not in body setLocationRef(getRootRef().toString()); // set response status getResponse().setStatus(Status.SUCCESS_OK); return Response.getCurrent().toString(); } else { getResponse().setStatus(Status.SUCCESS_OK); return "Nothing changed"; } } // Catch possible exceptions } catch (Exception e) { LOGGER.error("Exception caught: " + e.toString()); getResponse().setStatus(Status.CLIENT_ERROR_BAD_REQUEST, e.toString()); return "Exception: " + e.getMessage() + "\n"; } return " "; } }
lgpl-3.0
benothman/jboss-web-nio2
java/org/apache/catalina/ssi/SSIInclude.java
2662
/* * 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.catalina.ssi; import java.io.IOException; import java.io.PrintWriter; /** * Implements the Server-side #include command * * @author Bip Thelin * @author Paul Speed * @author Dan Sandberg * @author David Becker * @version $Revision: 515 $, $Date: 2008-03-17 22:02:23 +0100 (Mon, 17 Mar 2008) $ */ public final class SSIInclude implements SSICommand { /** * @see SSICommand */ public long process(SSIMediator ssiMediator, String commandName, String[] paramNames, String[] paramValues, PrintWriter writer) { long lastModified = 0; String configErrMsg = ssiMediator.getConfigErrMsg(); for (int i = 0; i < paramNames.length; i++) { String paramName = paramNames[i]; String paramValue = paramValues[i]; String substitutedValue = ssiMediator .substituteVariables(paramValue); try { if (paramName.equalsIgnoreCase("file") || paramName.equalsIgnoreCase("virtual")) { boolean virtual = paramName.equalsIgnoreCase("virtual"); lastModified = ssiMediator.getFileLastModified( substitutedValue, virtual); String text = ssiMediator.getFileText(substitutedValue, virtual); writer.write(text); } else { ssiMediator.log("#include--Invalid attribute: " + paramName); writer.write(configErrMsg); } } catch (IOException e) { ssiMediator.log("#include--Couldn't include file: " + substitutedValue, e); writer.write(configErrMsg); } } return lastModified; } }
lgpl-3.0
hunator/Galacticraft
common/micdoodle8/mods/galacticraft/core/client/render/block/GCCoreBlockRendererOxygenPipe.java
5235
package micdoodle8.mods.galacticraft.core.client.render.block; import java.util.Arrays; import micdoodle8.mods.galacticraft.core.util.WorldUtil; import net.minecraft.block.Block; import net.minecraft.client.renderer.RenderBlocks; import net.minecraft.client.renderer.Tessellator; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.IBlockAccess; import org.lwjgl.opengl.GL11; import cpw.mods.fml.client.registry.ISimpleBlockRenderingHandler; /** * GCCoreBlockRendererOxygenPipe.java * * This file is part of the Galacticraft project * * @author micdoodle8 * @license Lesser GNU Public License v3 (http://www.gnu.org/licenses/lgpl.html) * */ public class GCCoreBlockRendererOxygenPipe implements ISimpleBlockRenderingHandler { final int renderID; public GCCoreBlockRendererOxygenPipe(int var1) { this.renderID = var1; } public void renderPipe(RenderBlocks renderblocks, IBlockAccess iblockaccess, Block block, int x, int y, int z) { final TileEntity tileEntity = iblockaccess.getBlockTileEntity(x, y, z); final float minX = 0.40F; final float minY = 0.40F; final float minZ = 0.40F; final float maxX = 0.60F; final float maxY = 0.60F; final float maxZ = 0.60F; if (tileEntity != null) { final TileEntity[] connections = WorldUtil.getAdjacentOxygenConnections(tileEntity); for (TileEntity connection : connections) { if (connection != null) { final int side = Arrays.asList(connections).indexOf(connection); switch (side) { case 0: // DOWN renderblocks.setRenderBounds(minX, 0.0F, minZ, maxX, 0.4F, maxZ); renderblocks.renderStandardBlock(block, x, y, z); break; case 1: // UP renderblocks.setRenderBounds(minX, 0.6F, minZ, maxX, 1.0F, maxZ); renderblocks.renderStandardBlock(block, x, y, z); break; case 2: // NORTH renderblocks.setRenderBounds(minX, minY, 0.0, maxX, maxY, 0.4F); renderblocks.renderStandardBlock(block, x, y, z); break; case 3: // SOUTH renderblocks.setRenderBounds(minX, minY, 0.6F, maxX, maxY, 1.0); renderblocks.renderStandardBlock(block, x, y, z); break; case 4: // WEST renderblocks.setRenderBounds(0.0, minY, minZ, 0.4F, maxY, maxZ); renderblocks.renderStandardBlock(block, x, y, z); break; case 5: // EAST renderblocks.setRenderBounds(0.6F, minY, minZ, 1.0, maxY, maxZ); renderblocks.renderStandardBlock(block, x, y, z); break; } } } renderblocks.setRenderBounds(minX, minY, minZ, maxX, maxY, maxZ); renderblocks.renderStandardBlock(block, x, y, z); } } @Override public void renderInventoryBlock(Block block, int metadata, int modelID, RenderBlocks renderer) { final float minSize = 0.4F; final float maxSize = 0.6F; final Tessellator var3 = Tessellator.instance; GL11.glTranslatef(-0.5F, -0.5F, -0.5F); GL11.glColor4f(1.0F, 1.0F, 1.0F, 1.0F); renderer.setRenderBounds(minSize, minSize, 0.0F, maxSize, maxSize, 1.0F); var3.startDrawingQuads(); var3.setNormal(0.0F, -1.0F, 0.0F); renderer.renderFaceYNeg(block, 0.0D, 0.0D, 0.0D, block.getIcon(0, metadata)); var3.draw(); var3.startDrawingQuads(); var3.setNormal(0.0F, 1.0F, 0.0F); renderer.renderFaceYPos(block, 0.0D, 0.0D, 0.0D, block.getIcon(1, metadata)); var3.draw(); var3.startDrawingQuads(); var3.setNormal(0.0F, 0.0F, -1.0F); renderer.renderFaceXPos(block, 0.0D, 0.0D, 0.0D, block.getIcon(2, metadata)); var3.draw(); var3.startDrawingQuads(); var3.setNormal(0.0F, 0.0F, 1.0F); renderer.renderFaceXNeg(block, 0.0D, 0.0D, 0.0D, block.getIcon(3, metadata)); var3.draw(); var3.startDrawingQuads(); var3.setNormal(-1.0F, 0.0F, 0.0F); renderer.renderFaceZNeg(block, 0.0D, 0.0D, 0.0D, block.getIcon(4, metadata)); var3.draw(); var3.startDrawingQuads(); var3.setNormal(1.0F, 0.0F, 0.0F); renderer.renderFaceZPos(block, 0.0D, 0.0D, 0.0D, block.getIcon(5, metadata)); var3.draw(); } @Override public boolean renderWorldBlock(IBlockAccess world, int x, int y, int z, Block block, int modelId, RenderBlocks renderer) { this.renderPipe(renderer, world, block, x, y, z); return true; } @Override public boolean shouldRender3DInInventory() { return true; } @Override public int getRenderId() { return this.renderID; } }
lgpl-3.0
yangjiandong/appjruby
app-plugin-api/src/test/java/org/sonar/api/qualitymodel/ModelTest.java
3580
/* * Sonar, open source software quality management tool. * Copyright (C) 2009 SonarSource SA * mailto:contact AT sonarsource DOT com * * Sonar 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. * * Sonar 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 Sonar; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 */ package org.sonar.api.qualitymodel; import org.junit.Test; import org.sonar.api.rules.Rule; import static org.hamcrest.CoreMatchers.notNullValue; import static org.hamcrest.CoreMatchers.nullValue; import static org.hamcrest.Matchers.is; import static org.junit.Assert.assertThat; public class ModelTest { @Test public void searchEnabledCharacteristics() { Model model = Model.create(); model.createCharacteristicByKey("foo", "enabled foo"); model.createCharacteristicByKey("foo", "disabled foo").setEnabled(false); assertThat(model.getCharacteristicByKey("foo").getName(), is("enabled foo")); assertThat(model.getCharacteristicByKey("foo").getEnabled(), is(true)); assertThat(model.getCharacteristicByName("enabled foo").getName(), is("enabled foo")); assertThat(model.getCharacteristicByName("disabled foo"), nullValue()); assertThat(model.getCharacteristics().size(), is(1)); assertThat(model.getCharacteristics(false).size(), is(2)); } @Test public void shouldFindCharacteristicByRule() { Model model = Model.create(); Rule rule1 = Rule.create("checkstyle", "regexp", "Regular expression"); Rule rule2 = Rule.create("checkstyle", "import", "Check imports"); Characteristic efficiency = model.createCharacteristicByName("Efficiency"); Characteristic requirement1 = model.createCharacteristicByRule(rule1); Characteristic requirement2 = model.createCharacteristicByRule(rule2); efficiency.addChild(requirement1); efficiency.addChild(requirement2); assertThat(model.getCharacteristicByRule(rule1), is(requirement1)); assertThat(model.getCharacteristicByRule(rule2), is(requirement2)); assertThat(model.getCharacteristicByRule(null), nullValue()); assertThat(model.getCharacteristicByRule(Rule.create("foo", "bar", "Bar")), nullValue()); } @Test public void shouldRemoveCharacteristic() { Model model = Model.create(); Characteristic efficiency = model.createCharacteristicByName("Efficiency"); Characteristic usability = model.createCharacteristicByName("Usability"); assertThat(model.getCharacteristics().size(), is(2)); model.removeCharacteristic(efficiency); assertThat(model.getCharacteristics().size(), is(1)); assertThat(model.getCharacteristicByName("Efficiency"), nullValue()); assertThat(model.getCharacteristicByName("Usability"), notNullValue()); } @Test public void shouldNotFailWhenRemovingUnknownCharacteristic() { Model model = Model.create(); Characteristic efficiency = model.createCharacteristicByName("Efficiency"); model.removeCharacteristic(Characteristic.createByKey("foo", "Foo")); assertThat(model.getCharacteristics().size(), is(1)); } }
lgpl-3.0
syncro/amocrm-client
src/main/java/com/amocrm/amocrmclient/iface/ITaskAPI.java
1679
package com.amocrm.amocrmclient.iface; import com.amocrm.amocrmclient.task.entity.list.LTResponseData; import com.amocrm.amocrmclient.task.entity.set.STParam; import com.amocrm.amocrmclient.task.entity.set.STResponse; import retrofit2.Call; import retrofit2.http.Body; import retrofit2.http.GET; import retrofit2.http.POST; import retrofit2.http.Query; public interface ITaskAPI { @POST("/private/api/v2/json/tasks/set") Call<STResponse> setTask(@Body STParam setTask); @GET("/private/api/v2/json/tasks/list") Call<LTResponseData> list(); @GET("/private/api/v2/json/tasks/list") Call<LTResponseData> list(@Query("limit_rows") int limitRows, @Query("limit_offset") int limitOffset); @GET("/private/api/v2/json/tasks/list") Call<LTResponseData> list(@Query("type") String type); @GET("/private/api/v2/json/tasks/list") Call<LTResponseData> list(@Query("type") String type, @Query("limit_rows") int limitRows, @Query("limit_offset") int limitOffset); @GET("/private/api/v2/json/tasks/list") Call<LTResponseData> list(@Query("id") Long[] ids, @Query("limit_rows") int limitRows, @Query("limit_offset") int limitOffset); @GET("/private/api/v2/json/tasks/list") Call<LTResponseData> listByResponsibleId(@Query("responsible_user_id[]") Long[] responsibleUserIds); @GET("/private/api/v2/json/tasks/list") Call<LTResponseData> listByResponsibleId(@Query("responsible_user_id[]") Long[] responsibleUserIds, @Query("limit_rows") int limitRows, @Query("limit_offset") int limitOffset); @GET("/private/api/v2/json/tasks/list") Call<LTResponseData> listByElementId(@Query("element_id") String elementId); }
lgpl-3.0
automenta/spacegraph1
src/automenta/spacenet/space/widget/window/WindowRect.java
1699
package automenta.spacenet.space.widget.window; import automenta.spacenet.space.control.Draggable; import automenta.spacenet.space.geom.Rect; import automenta.spacenet.space.surface.ColorSurface; import com.ardor3d.math.Plane; import com.ardor3d.math.Ray3; import com.ardor3d.math.Vector3; @Deprecated class WindowRect extends Rect implements Draggable { private final ColorSurface cs; Vector3 a = new Vector3(); Vector3 b = new Vector3(); Vector3 c = new Vector3(); Plane p = new Plane(); Vector3 i = new Vector3(); Vector3 d = new Vector3(); public WindowRect() { super(RectShape.Rect); cs = add(new ColorSurface()); } @Override public boolean isTangible() { return true; } @Override public void onDragStart(Ray3 rayDrag) { updateIntersect(rayDrag); d.set(i); i.subtractLocal(getWorldTranslation()); System.out.println("drag start d=" + d); cs.color(0, 1, 0); } protected void updateIntersect(Ray3 r) { double x = getWorldTranslation().getX(); double y = getWorldTranslation().getY(); double z = getWorldTranslation().getZ(); a.set(x, y, z); b.set(x + 1, y, z); c.set(x, y + 1, z); p.setPlanePoints(a, b, c); r.intersects(p, i); } @Override public void onDragging(final Ray3 rayDrag) { cs.color(0, 1, 0); updateIntersect(rayDrag); //TODO use World -> Local //Vector3 o = getWorldTransform().applyInverseVector(i); getPosition().set(i); } @Override public void onDragStop(Ray3 rayDragStop) { cs.color(0.5, 0.5, 0.5); } }
lgpl-3.0
rintd/jSimulationMoving
src/main/java/json/Direction.java
1303
/* * Copyright (C) 2017 Chirkov Boris <b.v.chirkov@udsu.ru> * * Project website: http://eesystem.ru * Organization website: http://rintd.ru * * --------------------- DO NOT REMOVE THIS NOTICE ----------------------------- * Direction is part of jSimulationMoving. * * jSimulationMoving 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. * * jSimulationMoving 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 jSimulationMoving. If not, see <http://www.gnu.org/licenses/>. * ----------------------------------------------------------------------------- * * This code is in BETA; some features are incomplete and the code * could be written better. */ package json; /** * Created by boris on 03.04.17. */ public class Direction { public static final int UP = 3; public static final int DOWN = -3; }
lgpl-3.0
bullda/DroidText
src/bouncycastle/repack/org/bouncycastle/jce/provider/X509CRLEntryObject.java
8873
package repack.org.bouncycastle.jce.provider; import java.io.IOException; import java.math.BigInteger; import java.security.cert.CRLException; import java.security.cert.X509CRLEntry; import java.util.Date; import java.util.Enumeration; import java.util.HashSet; import java.util.Set; import javax.security.auth.x500.X500Principal; import repack.org.bouncycastle.asn1.ASN1Encodable; import repack.org.bouncycastle.asn1.ASN1InputStream; import repack.org.bouncycastle.asn1.ASN1Sequence; import repack.org.bouncycastle.asn1.DEREnumerated; import repack.org.bouncycastle.asn1.DERObjectIdentifier; import repack.org.bouncycastle.asn1.util.ASN1Dump; import repack.org.bouncycastle.asn1.x509.CRLReason; import repack.org.bouncycastle.asn1.x509.GeneralName; import repack.org.bouncycastle.asn1.x509.GeneralNames; import repack.org.bouncycastle.asn1.x509.TBSCertList; import repack.org.bouncycastle.asn1.x509.X509Extension; import repack.org.bouncycastle.asn1.x509.X509Extensions; import repack.org.bouncycastle.x509.extension.X509ExtensionUtil; /** * The following extensions are listed in RFC 2459 as relevant to CRL Entries * * ReasonCode Hode Instruction Code Invalidity Date Certificate Issuer * (critical) */ public class X509CRLEntryObject extends X509CRLEntry { private TBSCertList.CRLEntry c; private boolean isIndirect; private X500Principal previousCertificateIssuer; private X500Principal certificateIssuer; private int hashValue; private boolean isHashValueSet; public X509CRLEntryObject(TBSCertList.CRLEntry c) { this.c = c; this.certificateIssuer = loadCertificateIssuer(); } /** * Constructor for CRLEntries of indirect CRLs. If <code>isIndirect</code> * is <code>false</code> {@link #getCertificateIssuer()} will always * return <code>null</code>, <code>previousCertificateIssuer</code> is * ignored. If this <code>isIndirect</code> is specified and this CRLEntry * has no certificate issuer CRL entry extension * <code>previousCertificateIssuer</code> is returned by * {@link #getCertificateIssuer()}. * * @param c * TBSCertList.CRLEntry object. * @param isIndirect * <code>true</code> if the corresponding CRL is a indirect * CRL. * @param previousCertificateIssuer * Certificate issuer of the previous CRLEntry. */ public X509CRLEntryObject( TBSCertList.CRLEntry c, boolean isIndirect, X500Principal previousCertificateIssuer) { this.c = c; this.isIndirect = isIndirect; this.previousCertificateIssuer = previousCertificateIssuer; this.certificateIssuer = loadCertificateIssuer(); } /** * Will return true if any extensions are present and marked as critical as * we currently dont handle any extensions! */ public boolean hasUnsupportedCriticalExtension() { Set extns = getCriticalExtensionOIDs(); return extns != null && !extns.isEmpty(); } private X500Principal loadCertificateIssuer() { if (!isIndirect) { return null; } byte[] ext = getExtensionValue(X509Extensions.CertificateIssuer.getId()); if (ext == null) { return previousCertificateIssuer; } try { GeneralName[] names = GeneralNames.getInstance( X509ExtensionUtil.fromExtensionValue(ext)).getNames(); for (int i = 0; i < names.length; i++) { if (names[i].getTagNo() == GeneralName.directoryName) { return new X500Principal(names[i].getName().getDERObject().getDEREncoded()); } } return null; } catch (IOException e) { return null; } } public X500Principal getCertificateIssuer() { return certificateIssuer; } private Set getExtensionOIDs(boolean critical) { X509Extensions extensions = c.getExtensions(); if (extensions != null) { Set set = new HashSet(); Enumeration e = extensions.oids(); while (e.hasMoreElements()) { DERObjectIdentifier oid = (DERObjectIdentifier) e.nextElement(); X509Extension ext = extensions.getExtension(oid); if (critical == ext.isCritical()) { set.add(oid.getId()); } } return set; } return null; } public Set getCriticalExtensionOIDs() { return getExtensionOIDs(true); } public Set getNonCriticalExtensionOIDs() { return getExtensionOIDs(false); } public byte[] getExtensionValue(String oid) { X509Extensions exts = c.getExtensions(); if (exts != null) { X509Extension ext = exts.getExtension(new DERObjectIdentifier(oid)); if (ext != null) { try { return ext.getValue().getEncoded(); } catch (Exception e) { throw new RuntimeException("error encoding " + e.toString()); } } } return null; } /** * Cache the hashCode value - calculating it with the standard method. * @return calculated hashCode. */ public int hashCode() { if (!isHashValueSet) { hashValue = super.hashCode(); isHashValueSet = true; } return hashValue; } public byte[] getEncoded() throws CRLException { try { return c.getEncoded(ASN1Encodable.DER); } catch (IOException e) { throw new CRLException(e.toString()); } } public BigInteger getSerialNumber() { return c.getUserCertificate().getValue(); } public Date getRevocationDate() { return c.getRevocationDate().getDate(); } public boolean hasExtensions() { return c.getExtensions() != null; } public String toString() { StringBuffer buf = new StringBuffer(); String nl = System.getProperty("line.separator"); buf.append(" userCertificate: ").append(this.getSerialNumber()).append(nl); buf.append(" revocationDate: ").append(this.getRevocationDate()).append(nl); buf.append(" certificateIssuer: ").append(this.getCertificateIssuer()).append(nl); X509Extensions extensions = c.getExtensions(); if (extensions != null) { Enumeration e = extensions.oids(); if (e.hasMoreElements()) { buf.append(" crlEntryExtensions:").append(nl); while (e.hasMoreElements()) { DERObjectIdentifier oid = (DERObjectIdentifier)e.nextElement(); X509Extension ext = extensions.getExtension(oid); if (ext.getValue() != null) { byte[] octs = ext.getValue().getOctets(); ASN1InputStream dIn = new ASN1InputStream(octs); buf.append(" critical(").append(ext.isCritical()).append(") "); try { if (oid.equals(X509Extensions.ReasonCode)) { buf.append(new CRLReason(DEREnumerated.getInstance(dIn.readObject()))).append(nl); } else if (oid.equals(X509Extensions.CertificateIssuer)) { buf.append("Certificate issuer: ").append(new GeneralNames((ASN1Sequence)dIn.readObject())).append(nl); } else { buf.append(oid.getId()); buf.append(" value = ").append(ASN1Dump.dumpAsString(dIn.readObject())).append(nl); } } catch (Exception ex) { buf.append(oid.getId()); buf.append(" value = ").append("*****").append(nl); } } else { buf.append(nl); } } } } return buf.toString(); } }
lgpl-3.0
OurGrid/OurGrid
src/main/java/org/ourgrid/peer/ui/async/gui/IssueCertificateDialog.java
8992
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.ourgrid.peer.ui.async.gui; import java.io.File; import javax.swing.JFileChooser; import javax.swing.JOptionPane; import org.ourgrid.common.util.IssuedCertificateGenerator; import org.ourgrid.peer.PeerConfiguration; /** * * @author Abmar */ public class IssueCertificateDialog extends javax.swing.JDialog { /** * */ private static final long serialVersionUID = 1L; /** * Creates new form SignCertificateDialog */ public IssueCertificateDialog(java.awt.Frame parent, boolean modal) { super(parent, modal); initComponents(); setTitle("Issue certificate"); } /** * 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"> private void initComponents() { workerCerticateTxt = new javax.swing.JTextField(); jLabel1 = new javax.swing.JLabel(); browseSourceBtn = new javax.swing.JButton(); jLabel2 = new javax.swing.JLabel(); outputCertificateTxt = new javax.swing.JTextField(); browseOutputBtn = new javax.swing.JButton(); issueBtn = new javax.swing.JButton(); closeBtn = new javax.swing.JButton(); setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE); jLabel1.setText("Worker certificate"); browseSourceBtn.setText("Browse"); browseSourceBtn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { browseSourceBtnActionPerformed(evt); } }); jLabel2.setText("Output certificate"); browseOutputBtn.setText("Browse"); browseOutputBtn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { browseOutputBtnActionPerformed(evt); } }); issueBtn.setText("Issue"); issueBtn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { issueBtnActionPerformed(evt); } }); closeBtn.setText("Close"); closeBtn.addActionListener(new java.awt.event.ActionListener() { public void actionPerformed(java.awt.event.ActionEvent evt) { closeBtnActionPerformed(evt); } }); javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane()); getContentPane().setLayout(layout); layout.setHorizontalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addContainerGap() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(jLabel1) .addComponent(jLabel2) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING) .addGroup(layout.createSequentialGroup() .addGap(0, 159, Short.MAX_VALUE) .addComponent(issueBtn) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(closeBtn)) .addGroup(javax.swing.GroupLayout.Alignment.LEADING, layout.createSequentialGroup() .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false) .addComponent(workerCerticateTxt) .addComponent(outputCertificateTxt, javax.swing.GroupLayout.DEFAULT_SIZE, 210, Short.MAX_VALUE)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addComponent(browseSourceBtn) .addComponent(browseOutputBtn))))) .addContainerGap()) ); layout.setVerticalGroup( layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING) .addGroup(layout.createSequentialGroup() .addGap(8, 8, 8) .addComponent(jLabel1) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(workerCerticateTxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(browseSourceBtn)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addComponent(jLabel2) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(outputCertificateTxt, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE) .addComponent(browseOutputBtn)) .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 22, Short.MAX_VALUE) .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE) .addComponent(closeBtn) .addComponent(issueBtn)) .addContainerGap()) ); pack(); }// </editor-fold> private void browseSourceBtnActionPerformed(java.awt.event.ActionEvent evt) { final JFileChooser fc = new JFileChooser(); fc.setFileFilter(createFileFilter()); int returnVal = fc.showOpenDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { File file = fc.getSelectedFile(); workerCerticateTxt.setText(file.getAbsolutePath()); } } private FileNameExtensionFilter createFileFilter() { return new FileNameExtensionFilter("Certificate file (*.cer)", "cer"); } private void browseOutputBtnActionPerformed(java.awt.event.ActionEvent evt) { final JFileChooser fc = new JFileChooser(); fc.setFileFilter(createFileFilter()); int returnVal = fc.showSaveDialog(this); if (returnVal == JFileChooser.APPROVE_OPTION) { String file = fc.getSelectedFile().getAbsolutePath(); if (!file.endsWith(".cer")) { file += ".cer"; } outputCertificateTxt.setText(file); } } private void issueBtnActionPerformed(java.awt.event.ActionEvent evt) { String certificatePath = workerCerticateTxt.getText(); if (certificatePath == null || certificatePath.isEmpty()) { JOptionPane.showMessageDialog(this, "An input certificate file must be selected.", "Issue certificate", JOptionPane.ERROR_MESSAGE); return; } String outPutCertificatePath = outputCertificateTxt.getText(); if (outPutCertificatePath == null || outPutCertificatePath.isEmpty()) { JOptionPane.showMessageDialog(this, "An output certificate file must be selected.", "Issue certificate", JOptionPane.ERROR_MESSAGE); return; } try { IssuedCertificateGenerator.issueCertificate(certificatePath, PeerConfiguration.PROPERTIES_FILENAME, outPutCertificatePath); JOptionPane.showMessageDialog(this, "Worker certificate was successfully issued.", "Issue certificate", JOptionPane.INFORMATION_MESSAGE); } catch (Exception e) { JOptionPane.showMessageDialog(this, "Worker certificate could not be issued. Error: " + e.getMessage(), "Issue certificate", JOptionPane.ERROR_MESSAGE); } } private void closeBtnActionPerformed(java.awt.event.ActionEvent evt) { this.setVisible(false); } // Variables declaration - do not modify private javax.swing.JButton browseOutputBtn; private javax.swing.JButton browseSourceBtn; private javax.swing.JButton closeBtn; private javax.swing.JButton issueBtn; private javax.swing.JLabel jLabel1; private javax.swing.JLabel jLabel2; private javax.swing.JTextField outputCertificateTxt; private javax.swing.JTextField workerCerticateTxt; // End of variables declaration }
lgpl-3.0
cismet/project-tracker
src/main/java/de/cismet/projecttracker/client/common/ui/OkCancelModal.java
2878
/*************************************************** * * cismet GmbH, Saarbruecken, Germany * * ... and it just works. * ****************************************************/ /* * To change this license header, choose License Headers in Project Properties. * To change this template file, choose Tools | Templates * and open the template in the editor. */ package de.cismet.projecttracker.client.common.ui; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.uibinder.client.UiHandler; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.DialogBox; import com.google.gwt.user.client.ui.Label; import com.google.gwt.user.client.ui.Widget; /** * DOCUMENT ME! * * @author daniel * @version $Revision$, $Date$ */ public class OkCancelModal extends Composite { //~ Static fields/initializers --------------------------------------------- private static OkCancelModalUiBinder uiBinder = GWT.create( OkCancelModal.OkCancelModalUiBinder.class); //~ Instance fields -------------------------------------------------------- @UiField Button closeButton; @UiField Button okButton; @UiField Label lblMessage; @UiField Label lblTitle; private OkCancelCallback callback; private DialogBox form; //~ Constructors ----------------------------------------------------------- /** * Creates a new OkCancelModal object. * * @param form DOCUMENT ME! * @param cb DOCUMENT ME! * @param title DOCUMENT ME! * @param message DOCUMENT ME! */ public OkCancelModal(final DialogBox form, final OkCancelCallback cb, final String title, final String message) { this.form = form; initWidget(uiBinder.createAndBindUi(this)); this.callback = cb; lblMessage.setText(message); lblTitle.setText(title); } //~ Methods ---------------------------------------------------------------- /** * DOCUMENT ME! * * @param event DOCUMENT ME! */ @UiHandler("okButton") void onOkButtonClick(final ClickEvent event) { form.hide(); callback.onOkClicked(); } /** * DOCUMENT ME! * * @param event DOCUMENT ME! */ @UiHandler("closeButton") void onCloseButtonClick(final ClickEvent event) { form.hide(); callback.onCancelClicked(); } //~ Inner Interfaces ------------------------------------------------------- /** * DOCUMENT ME! * * @version $Revision$, $Date$ */ interface OkCancelModalUiBinder extends UiBinder<Widget, OkCancelModal> { } }
lgpl-3.0
viktor-podzigun/charva-lanterna
charva/src/main/java/charvax/swing/JTabbedPane.java
11819
/* class JTabbedPane * * Copyright (C) 2001-2003 R M Pitman * * 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 */ /* * Modified Jul 14, 2003 by Tadpole Computer, Inc. * Modifications Copyright 2003 by Tadpole Computer, Inc. * * Modifications are hereby licensed to all parties at no charge under * the same terms as the original. * * Modified to allow tabs to be focus traversable. Also added the * setEnabledAt and isEnabledAt methods. */ package charvax.swing; import java.util.ArrayList; import charva.awt.BorderLayout; import charva.awt.Component; import charva.awt.Dimension; import charva.awt.Graphics; import charva.awt.GraphicsConstants; import charva.awt.Insets; import charva.awt.Point; import charva.awt.event.ActionEvent; import charva.awt.event.ActionListener; /** * A component that lets the user display one of a set of components (usually * Panels) at a time. The management of the tab-selection has to be performed * outside of this component because it is possible that the currently selected * tab does not contain any focusTraversable components. In this case, this * JTabbedPane will never get the keyboard focus. */ public class JTabbedPane extends JComponent { private ArrayList tabComponents = new ArrayList(); private ArrayList tabs = new ArrayList(); private int selectedIndex = -1; private ButtonGroup buttongroup = new ButtonGroup(); private Insets insets; /** * Constructs a JTabbedPane */ public JTabbedPane() { insets = new Insets(2, 1, 1, 1); layoutMgr = new BorderLayout(); } /** * Add the specified component to the tabbed pane. If * <code>constraints</code> is a String, it will be used as the tab's * title; otherwise the component's name will be used as the title. */ public void add(Component component, Object constraints) { String label; if (constraints instanceof String) { label = (String)constraints; } else { label = component.getName(); } addTab(label, 0, component); } /** * Add a new tab with the specified component, title and function-key * * @param title the title of this tab * @param mnemonic the key code that can be pressed to select this tab * @param component the component to be added in this tab */ public void addTab(String title, int mnemonic, Component component) { TabButton tb = new TabButton(title, component); tb.setMnemonic(mnemonic); tabComponents.add(component); add(tb); tabs.add(tb); buttongroup.add(tb); // arrange for our TabButton to be in the focus list... if (selectedIndex == -1) { setSelectedIndex(0); } else if (isDisplayable()) { // If this component is already displayed, generate a PaintEvent // and post it onto the queue repaint(); } } /** * Makes the tabbed button at the given index selected */ public void setSelectedIndex(int index) { if (index >= tabComponents.size()) { throw new IndexOutOfBoundsException(); } if (index == selectedIndex) { return; } // remove the previously-selected component from the container if (selectedIndex != -1 && selectedIndex < tabComponents.size()) { super.remove((Component)tabComponents.get(selectedIndex)); // components.remove(tabComponents) // currentFocus = null; } selectedIndex = index; // add the newly-selected component to the container Component selected = (Component) tabComponents.get(index); super.add(selected); super.validate(); repaint(); TabButton tb = (TabButton) tabs.get(index); tb.setSelected(true); if (SwingUtilities.windowForComponent(this) != null) { tb.requestFocus(); } } public int getSelectedIndex() { return selectedIndex; } public void setSelectedComponent(Component component) { int index = tabComponents.indexOf(component); setSelectedIndex(index); } public Component getSelectedComponent() { if (selectedIndex != -1) { return (Component) tabComponents.get(selectedIndex); } return null; } public Dimension getSize() { // Override the method in Container. Balazs Poka suggested that we // shouldn't override getSize(), but my applications don't work unless // I do override. (Rob). return getMinimumSize(); } public Insets getInsets() { return insets; } /** * Override the method in Container. */ public Dimension getMinimumSize() { if (super.isValid()) { return minimumSize; } // scan through the components in each tab and determine the smallest // rectangle that will enclose all of them int width = 0; int height = 0; final int countComponents = tabComponents.size(); for (int i = 0; i < countComponents; i++) { Component c = (Component) tabComponents.get(i); Dimension size = c.getMinimumSize(); if (size.width > width) { width = size.width; } if (size.height > height) { height = size.height; } } // now scan through the titles of the tabs, and determine the width // that all of them will fit into int tabwidth = 0; final int countTabs = tabs.size(); for (int i = 0; i < countTabs; i++) { tabwidth += ((TabButton)tabs.get(i)).getWidth(); } tabwidth += 2; if (tabwidth > width) { width = tabwidth; } // take into account the border and the height of the tabs Insets insets = getInsets(); minimumSize = new Dimension(width + insets.left + insets.right, height + insets.top + insets.bottom); //isValid = true; return minimumSize; } public void paint(Graphics g) { g.setColor(getColor()); // draw the enclosing frame Dimension size = getSize(); g.fillRect(0, 0, getWidth(), getHeight()); g.drawRect(0, 1, size.width, size.height - 1); // draw each of the tabs int hoffset = 1; final int countTabs = tabs.size(); Point relative = new Point(0, 0); for (int i = 0; i < countTabs; i++) { TabButton c = (TabButton)tabs.get(i); c.setLocation(relative.addOffset(hoffset, 0)); c.paint(g.create(c.getX(), c.getY(), c.getWidth(), c.getHeight())); hoffset += c.getWidth(); } // now draw the selected component if (selectedIndex != -1) { Component c = (Component)tabComponents.get(selectedIndex); // Note that we draw the component even if isVisible() would be // false; it doesn't make sense to make a component invisible in a // JTabbedPane. c.paint(g.create(c.getX(), c.getY(), c.getWidth(), c.getHeight())); } } /** * Removes the tab and component which corresponds to the specified index */ public void remove(int index) { // save this just in case // Component selected = (Component) tabComponents.elementAt(0); // remove little tab from parent super.remove((Component) tabs.get(index)); // remove it from here also TabButton tb = (TabButton) tabs.remove(index); // here comes the button group buttongroup.remove(tb); // remove deleted container from parent super.remove((Component) tabComponents.get(index)); // and from here tabComponents.remove(index); if (getSelectedIndex() == index) { selectedIndex = -1; if (index - 1 < 0) { if (getTabCount() > 0) { // we NEED to revalidate selection setSelectedIndex(0); } else { this.setFocus(null); super.validate(); } } else { setSelectedIndex(index - 1); } } repaint(); } /** * Returns the first tab index with the specified title, or -1 if no tab * has the title */ public int indexOfTab(String title) { final int countTabs = tabs.size(); for (int i = 0; i < countTabs; i++) { if (title.equals(((TabButton) tabs.get(i)).getText())) { return (i); } } return -1; } /** * Returns the tab's button with the specified index */ public JButton getButtonAt(int index) { return (TabButton)tabs.get(index); } /** * Returns the number of tabs in this tabbed pane */ public int getTabCount() { return tabs.size(); } private class TabButton extends JButton implements ActionListener { private Component c; public TabButton(String label, Component c) { super(label); this.c = c; addActionListener(this); } public void actionPerformed(ActionEvent ev) { setSelectedComponent(c); } public void requestFocus() { super.requestFocus(); Point origin = getLocationOnScreen(); Insets insets = getInsets(); SwingUtilities.windowForComponent(this).setCursor( origin.addOffset(2 + insets.left, insets.top)); } public void paint(Graphics g) { Insets insets = getInsets(); g.translate(insets.left, insets.top); paintText(g, " " + getText() + " "); g.setColor(JTabbedPane.this.getColor()); g.drawChar(GraphicsConstants.VS_ULCORNER, 0, 0); g.drawChar(GraphicsConstants.VS_URCORNER, getText().length() + 3, 0); if (isSelected()) { g.drawChar(GraphicsConstants.VS_LRCORNER, 0, 1); final int len = getText().length() + 2; for (int j = 0; j < len; j++) { g.drawChar(' ', j + 1, 1); } g.drawChar(GraphicsConstants.VS_LLCORNER, len + 1, 1); } else { g.drawChar(GraphicsConstants.VS_BTEE, 0, 1); g.drawChar(GraphicsConstants.VS_BTEE, getText().length() + 3, 1); } } public int getWidth() { Insets insets = getInsets(); return getText().length() + insets.left + insets.right + 4; } } }
lgpl-3.0
leonhad/paradoxdriver
src/main/java/com/googlecode/paradox/function/string/ReplaceFunction.java
2192
/* * Copyright (C) 2009 Leonardo Alves da Costa * * This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public * License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any * later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public * License for more details. You should have received a copy of the GNU General Public License along with this * program. If not, see <http://www.gnu.org/licenses/>. */ package com.googlecode.paradox.function.string; import com.googlecode.paradox.ConnectionInfo; import com.googlecode.paradox.planner.nodes.FieldNode; import com.googlecode.paradox.results.Column; import com.googlecode.paradox.results.ParadoxType; /** * The SQL REPLACE function. * * @version 1.4 * @since 1.6.0 */ @SuppressWarnings("java:S109") public class ReplaceFunction extends AbstractStringFunction { /** * The function name. */ public static final String NAME = "REPLACE"; /** * Column parameter list. */ private static final Column[] COLUMNS = { new Column(null, ParadoxType.VARCHAR, "The string or replaced.", 0, true, RESULT), new Column("value", ParadoxType.VARCHAR, "The original string.", 1, false, IN), new Column("old_string", ParadoxType.VARCHAR, "The string to be replaced.", 2, false, IN), new Column("new_string", ParadoxType.VARCHAR, "The new replacement string..", 3, false, IN) }; @Override public String getRemarks() { return "Replaces all occurrences of a substring within a string, with a new substring."; } @Override public Column[] getColumns() { return COLUMNS; } @Override public Object execute(final ConnectionInfo connectionInfo, final Object[] values, final ParadoxType[] types, final FieldNode[] fields) { return values[0].toString().replace(values[1].toString(), values[2].toString()); } }
lgpl-3.0
cismet/lagis-tree-management-extension
src/main/java/de/cismet/lagis/ressort/baum/BaumModel.java
16037
/*************************************************** * * cismet GmbH, Saarbruecken, Germany * * ... and it just works. * ****************************************************/ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package de.cismet.lagis.ressort.baum; import org.apache.log4j.Logger; import java.util.*; import javax.swing.DefaultListModel; import javax.swing.table.AbstractTableModel; import javax.swing.text.BadLocationException; import de.cismet.cids.custom.beans.lagis.BaumCustomBean; import de.cismet.cids.custom.beans.lagis.BaumKategorieAuspraegungCustomBean; import de.cismet.cids.custom.beans.lagis.BaumKategorieCustomBean; import de.cismet.cids.custom.beans.lagis.BaumNutzungCustomBean; import de.cismet.cismap.commons.features.Feature; import de.cismet.lagis.broker.LagisBroker; import de.cismet.lagis.models.CidsBeanTableModel_Lagis; import de.cismet.lagis.models.documents.SimpleDocumentModel; import de.cismet.lagisEE.entity.extension.baum.Baum; import de.cismet.lagisEE.entity.extension.baum.BaumKategorie; import de.cismet.lagisEE.entity.extension.baum.BaumKategorieAuspraegung; import de.cismet.lagisEE.entity.extension.baum.BaumNutzung; /** * DOCUMENT ME! * * @author Sebastian Puhl * @version $Revision$, $Date$ */ public class BaumModel extends CidsBeanTableModel_Lagis { //~ Static fields/initializers --------------------------------------------- private static final String[] COLUMN_HEADER = { "Lage", "Baumnummer", "Fläche m²", "Nutzung", "Baumbestand", "Ausprägung", "Auftragnehmer", "Erfassungsdatum", "Fälldatum", }; private static final Class[] COLUMN_CLASSES = { String.class, String.class, Integer.class, String.class, BaumNutzung.class, Object.class, String.class, Date.class, Date.class }; public static final int LAGE_COLUMN = 0; public static final int BAUMNUMMER_COLUMN = 1; public static final int FLAECHE_COLUMN = 2; public static final int ALTE_NUTZUNG_COLUMN = 3; public static final int BAUMBESTAND_COLUMN = 4; public static final int AUSPRAEGUNG_COLUMN = 5; public static final int AUFTRAGNEMER_COLUMN = 6; public static final int ERFASSUNGSDATUM_COLUMN = 7; public static final int FAELLDATUM_COLUMN = 8; //~ Instance fields -------------------------------------------------------- private final Logger log = org.apache.log4j.Logger.getLogger(this.getClass()); private SimpleDocumentModel bemerkungDocumentModel; private Baum currentSelectedBaum = null; //~ Constructors ----------------------------------------------------------- /** * Creates a new BaumModel object. */ public BaumModel() { super(COLUMN_HEADER, COLUMN_CLASSES, BaumCustomBean.class); initDocumentModels(); } /** * Creates a new BaumModel object. * * @param baeume DOCUMENT ME! */ public BaumModel(final Collection<BaumCustomBean> baeume) { super(COLUMN_HEADER, COLUMN_CLASSES, baeume); initDocumentModels(); } //~ Methods ---------------------------------------------------------------- @Override public Object getValueAt(final int rowIndex, final int columnIndex) { try { if (rowIndex >= getRowCount()) { log.warn("Cannot access row " + rowIndex + ". There are just " + getRowCount() + " rows."); return null; } final Baum value = getCidsBeanAtRow(rowIndex); switch (columnIndex) { case LAGE_COLUMN: { return value.getLage(); } case BAUMNUMMER_COLUMN: { return value.getBaumnummer(); } case FLAECHE_COLUMN: { if (value.getFlaeche() != null) { return value.getFlaeche().intValue(); } else { return null; } } case ALTE_NUTZUNG_COLUMN: { return value.getAlteNutzung(); } case BAUMBESTAND_COLUMN: { if (value.getBaumNutzung() != null) { return value.getBaumNutzung().getBaumKategorie(); } else { return null; } } case AUSPRAEGUNG_COLUMN: { if ((value.getBaumNutzung() != null) && (value.getBaumNutzung().getBaumKategorie() != null)) { return value.getBaumNutzung().getAusgewaehlteAuspraegung(); } else { return null; } } case AUFTRAGNEMER_COLUMN: { return value.getAuftragnehmer(); } case ERFASSUNGSDATUM_COLUMN: { return value.getErfassungsdatum(); } case FAELLDATUM_COLUMN: { return value.getFaelldatum(); } default: { return "Spalte ist nicht definiert"; } } } catch (Exception ex) { log.error("Fehler beim abrufen von Daten aus dem Modell: Zeile: " + rowIndex + " Spalte" + columnIndex, ex); return null; } } /** * DOCUMENT ME! * * @param rowIndex DOCUMENT ME! */ @Override public void removeCidsBean(final int rowIndex) { final Baum baum = getCidsBeanAtRow(rowIndex); if ((baum != null) && (baum.getGeometry() != null)) { LagisBroker.getInstance().getMappingComponent().getFeatureCollection().removeFeature(baum); } super.removeCidsBean(rowIndex); } @Override public boolean isCellEditable(final int rowIndex, final int columnIndex) { if ((COLUMN_HEADER.length > columnIndex) && (getRowCount() > rowIndex) && isInEditMode()) { if (columnIndex == AUSPRAEGUNG_COLUMN) { final Baum currentBaum = getCidsBeanAtRow(rowIndex); if (((currentBaum != null) && (currentBaum.getBaumNutzung() != null) && (currentBaum.getBaumNutzung().getBaumKategorie() != null)) || ((currentBaum.getBaumNutzung().getBaumKategorie().getKategorieAuspraegungen() != null) && (currentBaum.getBaumNutzung().getBaumKategorie().getKategorieAuspraegungen() .size() > 0))) { return true; } else { return false; } } else { return true; } } else { return false; } } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public ArrayList<Feature> getAllBaumFeatures() { final ArrayList<Feature> tmp = new ArrayList<Feature>(); if (getCidsBeans() != null) { final Iterator<BaumCustomBean> it = (Iterator<BaumCustomBean>)getCidsBeans().iterator(); while (it.hasNext()) { final Baum curBaum = it.next(); if (curBaum.getGeometry() != null) { tmp.add(curBaum); } } return tmp; } else { return null; } } @Override public void setValueAt(final Object aValue, final int rowIndex, final int columnIndex) { try { final Baum value = getCidsBeanAtRow(rowIndex); switch (columnIndex) { case LAGE_COLUMN: { value.setLage((String)aValue); break; } case BAUMNUMMER_COLUMN: { value.setBaumnummer((String)aValue); break; } case FLAECHE_COLUMN: { if (aValue != null) { value.setFlaeche(((Integer)aValue).doubleValue()); } else { value.setFlaeche(null); } break; } case ALTE_NUTZUNG_COLUMN: { value.setAlteNutzung((String)aValue); break; } case BAUMBESTAND_COLUMN: { if ((aValue != null) && (aValue instanceof String)) { if (log.isDebugEnabled()) { log.debug("Leersting wurde eingebenen --> entferene Ausgewählte Kategorien+Ausprägung"); } value.setBaumNutzung(null); return; } if (value.getBaumNutzung() == null) { value.setBaumNutzung(BaumNutzungCustomBean.createNew()); value.getBaumNutzung().setBaumKategorie((BaumKategorieCustomBean)aValue); if ((aValue != null) && (((BaumKategorie)aValue).getKategorieAuspraegungen() != null) && (((BaumKategorie)aValue).getKategorieAuspraegungen().size() == 1)) { for (final BaumKategorieAuspraegungCustomBean currentAuspraegung : ((BaumKategorie)aValue).getKategorieAuspraegungen()) { value.getBaumNutzung().setAusgewaehlteAuspraegung(currentAuspraegung); } } } else { BaumKategorie oldKategory = null; if (((oldKategory = value.getBaumNutzung().getBaumKategorie()) != null) && (aValue != null)) { if (!oldKategory.equals(aValue)) { if (log.isDebugEnabled()) { log.debug("Kategorie hat sich geändert --> Ausprägung ist nicht mehr gültig"); } value.getBaumNutzung().setAusgewaehlteAuspraegung(null); } } value.getBaumNutzung().setBaumKategorie((BaumKategorieCustomBean)aValue); if ((aValue != null) && (((BaumKategorie)aValue).getKategorieAuspraegungen() != null) && (((BaumKategorie)aValue).getKategorieAuspraegungen().size() == 1)) { for (final BaumKategorieAuspraegungCustomBean currentAuspraegung : ((BaumKategorie)aValue).getKategorieAuspraegungen()) { value.getBaumNutzung().setAusgewaehlteAuspraegung(currentAuspraegung); } } } break; } case AUSPRAEGUNG_COLUMN: { if (log.isDebugEnabled()) { log.debug("set AuspraegungColumn:" + aValue.getClass()); } if (value.getBaumNutzung() == null) { if (log.isDebugEnabled()) { log.debug("Nutzung == null --> new BaumNutzung"); } value.setBaumNutzung(BaumNutzungCustomBean.createNew()); } else if ((aValue != null) && (aValue instanceof BaumKategorieAuspraegung)) { if (log.isDebugEnabled()) { log.debug("instance of BaumKategorieAuspraegung"); } value.getBaumNutzung().setAusgewaehlteAuspraegung((BaumKategorieAuspraegungCustomBean)aValue); } else if ((aValue != null) && (aValue instanceof Integer)) { if (log.isDebugEnabled()) { log.debug("instance of integer"); } value.getBaumNutzung().setAusgewaehlteAuspraegung(null); } else { if (log.isDebugEnabled()) { log.debug("else"); } value.getBaumNutzung().setAusgewaehlteAuspraegung(null); } break; } case AUFTRAGNEMER_COLUMN: { if ((aValue != null) && ((String)aValue).equals("")) { value.setAuftragnehmer(null); } else { value.setAuftragnehmer((String)aValue); } break; } case ERFASSUNGSDATUM_COLUMN: { if ((aValue instanceof Date) || (aValue == null)) { value.setErfassungsdatum((Date)aValue); } // else if(aValue == null){ // value.setVertragsbeginn(null); // } break; } case FAELLDATUM_COLUMN: { if ((aValue instanceof Date) || (aValue == null)) { value.setFaelldatum((Date)aValue); } break; } default: { log.warn("Keine Spalte für angegebenen Index vorhanden: " + columnIndex); return; } } fireTableDataChanged(); } catch (Exception ex) { log.error("Fehler beim setzen von Daten in dem Modell: Zeile: " + rowIndex + " Spalte" + columnIndex, ex); } } /** * DOCUMENT ME! */ private void initDocumentModels() { bemerkungDocumentModel = new SimpleDocumentModel() { @Override public void assignValue(final String newValue) { if (log.isDebugEnabled()) { log.debug("Bemerkung assigned"); log.debug("new Value: " + newValue); } valueToCheck = newValue; fireValidationStateChanged(this); if ((currentSelectedBaum != null) && (getStatus() == VALID)) { currentSelectedBaum.setBemerkung(newValue); } } }; } /** * DOCUMENT ME! */ public void clearSlaveComponents() { try { if (log.isDebugEnabled()) { log.debug("Clear Slave Components"); } bemerkungDocumentModel.clear(0, bemerkungDocumentModel.getLength()); } catch (Exception ex) { } } /** * DOCUMENT ME! * * @return DOCUMENT ME! */ public SimpleDocumentModel getBemerkungDocumentModel() { return bemerkungDocumentModel; } /** * DOCUMENT ME! * * @param newBaum DOCUMENT ME! */ public void setCurrentSelectedBaum(final Baum newBaum) { currentSelectedBaum = newBaum; if (currentSelectedBaum != null) { try { bemerkungDocumentModel.clear(0, bemerkungDocumentModel.getLength()); bemerkungDocumentModel.insertString(0, currentSelectedBaum.getBemerkung(), null); } catch (BadLocationException ex) { // TODO Böse log.error("Fehler beim setzen des BemerkungsModells: ", ex); } } else { if (log.isDebugEnabled()) { log.debug("nichts selektiert lösche Felder"); } clearSlaveComponents(); } } }
lgpl-3.0
marikaris/molgenis
molgenis-data-security/src/test/java/org/molgenis/data/security/meta/PackageRepositorySecurityDecoratorTest.java
17524
package org.molgenis.data.security.meta; import static java.util.Arrays.asList; import static java.util.Collections.singletonList; import static java.util.stream.Collectors.toList; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.jupiter.api.Assertions.assertEquals; import static org.junit.jupiter.api.Assertions.assertThrows; import static org.mockito.ArgumentMatchers.any; import static org.mockito.Mockito.doAnswer; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.eq; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.verify; import static org.mockito.Mockito.when; import static org.molgenis.data.security.PackagePermission.UPDATE; import java.util.List; import java.util.function.Consumer; import java.util.stream.Stream; import org.junit.jupiter.api.BeforeEach; import org.junit.jupiter.api.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mock; import org.molgenis.data.AbstractMolgenisSpringTest; import org.molgenis.data.EntityAlreadyExistsException; import org.molgenis.data.Repository; import org.molgenis.data.meta.model.Package; import org.molgenis.data.meta.model.PackageMetadata; import org.molgenis.data.security.PackageIdentity; import org.molgenis.data.security.PackagePermission; import org.molgenis.data.security.exception.NullParentPackageNotSuException; import org.molgenis.data.security.exception.PackagePermissionDeniedException; import org.molgenis.data.security.exception.SystemMetadataModificationException; import org.molgenis.security.core.UserPermissionEvaluator; import org.springframework.security.acls.model.AlreadyExistsException; import org.springframework.security.acls.model.MutableAcl; import org.springframework.security.acls.model.MutableAclService; import org.springframework.security.test.context.support.WithMockUser; import org.springframework.test.context.ContextConfiguration; @ContextConfiguration(classes = {PackageRepositorySecurityDecoratorTest.Config.class}) class PackageRepositorySecurityDecoratorTest extends AbstractMolgenisSpringTest { private static final String USERNAME = "user"; private static final String ROLE_SU = "SU"; @Mock private Repository<Package> delegateRepository; @Mock private MutableAclService mutableAclService; @Mock private UserPermissionEvaluator userPermissionEvaluator; private PackageRepositorySecurityDecorator repo; @BeforeEach void setUp() { repo = new PackageRepositorySecurityDecorator( delegateRepository, mutableAclService, userPermissionEvaluator); } @Test void testUpdate() { Package pack = mock(Package.class); Package parent = mock(Package.class); Package oldPack = mock(Package.class); when(pack.getId()).thenReturn("1"); when(parent.getId()).thenReturn("2"); when(pack.getParent()).thenReturn(parent); when(oldPack.getParent()).thenReturn(parent); when(oldPack.getId()).thenReturn("1"); MutableAcl acl = mock(MutableAcl.class); MutableAcl parentAcl = mock(MutableAcl.class); doReturn(true).when(userPermissionEvaluator).hasPermission(new PackageIdentity("1"), UPDATE); when(mutableAclService.readAclById(any())) .thenAnswer( invocation -> { Object argument = invocation.getArguments()[0]; if (argument.equals(new PackageIdentity("1"))) { return acl; } else if (argument.equals(new PackageIdentity("2"))) { return parentAcl; } return null; }); when(delegateRepository.findOneById(pack.getId())).thenReturn(oldPack); repo.update(pack); verify(mutableAclService).updateAcl(acl); verify(delegateRepository).update(pack); } @Test void testUpdateNoParentPermission() { Package pack = mock(Package.class); Package parent = mock(Package.class); Package oldPack = mock(Package.class); Package oldParent = mock(Package.class); when(pack.getId()).thenReturn("1"); when(parent.getId()).thenReturn("2"); when(pack.getId()).thenReturn("1"); when(oldPack.getId()).thenReturn("2"); when(pack.getParent()).thenReturn(parent); when(oldPack.getParent()).thenReturn(oldParent); MutableAcl acl = mock(MutableAcl.class); when(delegateRepository.findOneById(pack.getId())).thenReturn(oldPack); assertThrows(PackagePermissionDeniedException.class, () -> repo.update(pack)); } @Test void testUpdateToNullPackage() { Package pack = mock(Package.class); when(pack.getId()).thenReturn("pack"); when(pack.getParent()).thenReturn(null); MutableAcl acl1 = mock(MutableAcl.class); Package oldPack = mock(Package.class); Package oldParent = mock(Package.class); when(oldPack.getId()).thenReturn("pack"); when(oldPack.getParent()).thenReturn(oldParent); when(delegateRepository.findOneById(pack.getId())).thenReturn(oldPack); assertThrows(NullParentPackageNotSuException.class, () -> repo.update(pack)); } @Test void testUpdate1() { Package package1 = mock(Package.class); Package package2 = mock(Package.class); Package parent = mock(Package.class); when(package1.getId()).thenReturn("1"); when(package2.getId()).thenReturn("2"); when(parent.getId()).thenReturn("parent"); when(package1.getParent()).thenReturn(parent); when(package2.getParent()).thenReturn(parent); MutableAcl acl1 = mock(MutableAcl.class); MutableAcl acl2 = mock(MutableAcl.class); MutableAcl parentAcl = mock(MutableAcl.class); Package oldPack1 = mock(Package.class); Package oldPack2 = mock(Package.class); when(oldPack1.getParent()).thenReturn(parent); when(oldPack2.getParent()).thenReturn(parent); when(oldPack1.getId()).thenReturn("1"); when(oldPack2.getId()).thenReturn("2"); when(acl1.getParentAcl()).thenReturn(parentAcl); when(acl2.getParentAcl()).thenReturn(parentAcl); doReturn(oldPack1).when(delegateRepository).findOneById("1"); doReturn(oldPack2).when(delegateRepository).findOneById("2"); Stream<Package> packages = Stream.of(package1, package2); repo.update(packages); // TODO: how to verify the deleteAcl method in the "filter" of the stream doReturn(acl1).when(mutableAclService).readAclById(new PackageIdentity("1")); doReturn(acl2).when(mutableAclService).readAclById(new PackageIdentity("2")); doReturn(parentAcl).when(mutableAclService).readAclById(new PackageIdentity("parent")); doReturn(true).when(userPermissionEvaluator).hasPermission(new PackageIdentity("1"), UPDATE); doReturn(true).when(userPermissionEvaluator).hasPermission(new PackageIdentity("2"), UPDATE); @SuppressWarnings("unchecked") ArgumentCaptor<Stream<Package>> captor = ArgumentCaptor.forClass(Stream.class); verify(delegateRepository).update(captor.capture()); assertEquals(asList(package1, package2), captor.getValue().collect(toList())); } @Test void testDelete() { Package package1 = mock(Package.class); Package package2 = mock(Package.class); when(package1.getId()).thenReturn("1"); when(package2.getId()).thenReturn("2"); when(package1.getParent()).thenReturn(package2); doReturn(true).when(userPermissionEvaluator).hasPermission(new PackageIdentity("2"), UPDATE); repo.delete(package1); verify(mutableAclService).deleteAcl(new PackageIdentity("1"), true); verify(delegateRepository).delete(package1); } @Test void testDelete1() { Package package1 = mock(Package.class); Package package2 = mock(Package.class); Package package3 = mock(Package.class); Package package4 = mock(Package.class); when(package1.getId()).thenReturn("1"); when(package2.getId()).thenReturn("2"); when(package3.getId()).thenReturn("3"); when(package4.getId()).thenReturn("4"); when(package1.getParent()).thenReturn(package3); when(package2.getParent()).thenReturn(package4); doReturn(true).when(userPermissionEvaluator).hasPermission(new PackageIdentity("3"), UPDATE); doReturn(false).when(userPermissionEvaluator).hasPermission(new PackageIdentity("4"), UPDATE); Stream<Package> packages = Stream.of(package1, package2); repo.delete(packages); // TODO: how to verify the deleteAcl method in the "filter" of the stream @SuppressWarnings("unchecked") ArgumentCaptor<Stream<Package>> captor = ArgumentCaptor.forClass(Stream.class); verify(delegateRepository).delete(captor.capture()); assertEquals(singletonList(package1), captor.getValue().collect(toList())); } @Test void testDeleteById() { Package package1 = mock(Package.class); Package package2 = mock(Package.class); when(package1.getId()).thenReturn("1"); when(package2.getId()).thenReturn("2"); when(package1.getParent()).thenReturn(package2); doReturn(true).when(userPermissionEvaluator).hasPermission(new PackageIdentity("2"), UPDATE); doReturn(package1).when(delegateRepository).findOneById("1"); repo.deleteById("1"); verify(mutableAclService).deleteAcl(new PackageIdentity("1"), true); verify(delegateRepository).deleteById("1"); } @Test void testDeleteAll() { Package permittedParentPackage = when(mock(Package.class).getId()).thenReturn("permittedParentPackageId").getMock(); Package permittedPackage = when(mock(Package.class).getId()).thenReturn("permittedPackageId").getMock(); when(permittedPackage.getParent()).thenReturn(permittedParentPackage); Package notPermittedPackage = when(mock(Package.class).getId()).thenReturn("notPermittedPackageId").getMock(); doAnswer( invocation -> { Consumer<List<Package>> consumer = invocation.getArgument(0); consumer.accept(asList(permittedPackage, notPermittedPackage)); return null; }) .when(delegateRepository) .forEachBatched(any(), eq(1000)); when(userPermissionEvaluator.hasPermission( new PackageIdentity(permittedParentPackage), PackagePermission.UPDATE)) .thenReturn(true); repo.deleteAll(); @SuppressWarnings("unchecked") ArgumentCaptor<Stream<Package>> entityStreamCaptor = ArgumentCaptor.forClass(Stream.class); verify(delegateRepository).delete(entityStreamCaptor.capture()); assertEquals(singletonList(permittedPackage), entityStreamCaptor.getValue().collect(toList())); } @Test void testDeleteAll1() { Package package1 = mock(Package.class); Package package2 = mock(Package.class); Package package3 = mock(Package.class); Package package4 = mock(Package.class); when(package1.getId()).thenReturn("1"); when(package2.getId()).thenReturn("2"); when(package3.getId()).thenReturn("3"); when(package4.getId()).thenReturn("4"); when(package1.getParent()).thenReturn(package3); when(package2.getParent()).thenReturn(package4); doReturn(true).when(userPermissionEvaluator).hasPermission(new PackageIdentity("3"), UPDATE); doReturn(false).when(userPermissionEvaluator).hasPermission(new PackageIdentity("4"), UPDATE); doReturn(package1).when(delegateRepository).findOneById("1"); doReturn(package2).when(delegateRepository).findOneById("2"); Stream<Object> ids = Stream.of("1", "2"); repo.deleteAll(ids); @SuppressWarnings("unchecked") ArgumentCaptor<Stream<Object>> captor = ArgumentCaptor.forClass(Stream.class); verify(delegateRepository).deleteAll(captor.capture()); assertEquals(singletonList("1"), captor.getValue().collect(toList())); } @Test void testAdd() { Package pack = mock(Package.class); Package parent = mock(Package.class); when(pack.getId()).thenReturn("1"); when(parent.getId()).thenReturn("2"); when(pack.getParent()).thenReturn(parent); MutableAcl acl = mock(MutableAcl.class); MutableAcl parentAcl = mock(MutableAcl.class); when(mutableAclService.createAcl(new PackageIdentity("1"))).thenReturn(acl); when(mutableAclService.readAclById(new PackageIdentity("2"))).thenReturn(parentAcl); when(userPermissionEvaluator.hasPermission( new PackageIdentity(parent.getId()), PackagePermission.ADD_PACKAGE)) .thenReturn(true); repo.add(pack); verify(mutableAclService).createAcl(new PackageIdentity("1")); verify(mutableAclService).updateAcl(acl); verify(delegateRepository).add(pack); } @Test void testAddNoPermissionOnParent() { Package pack = mock(Package.class); Package parent = mock(Package.class); when(pack.getId()).thenReturn("pack"); when(parent.getId()).thenReturn("2"); when(pack.getParent()).thenReturn(parent); when(userPermissionEvaluator.hasPermission( new PackageIdentity(parent.getId()), PackagePermission.ADD_PACKAGE)) .thenReturn(false); assertThrows(PackagePermissionDeniedException.class, () -> repo.add(pack)); } @Test void testAddNullParent() { Package pack = mock(Package.class); when(pack.getId()).thenReturn("pack"); when(pack.getParent()).thenReturn(null); assertThrows(NullParentPackageNotSuException.class, () -> repo.add(pack)); } @WithMockUser( username = USERNAME, roles = {ROLE_SU}) @Test void testAddAlreadyExists() { Package aPackage = mock(Package.class); when(aPackage.getId()).thenReturn("packageId"); when(aPackage.getIdValue()).thenReturn("packageId"); PackageMetadata packageMetadata = when(mock(PackageMetadata.class).getId()).thenReturn("Package").getMock(); when(aPackage.getEntityType()).thenReturn(packageMetadata); when(mutableAclService.createAcl(new PackageIdentity(aPackage))) .thenThrow(new AlreadyExistsException("")); Exception exception = assertThrows(EntityAlreadyExistsException.class, () -> repo.add(aPackage)); assertThat(exception.getMessage()).containsPattern("type:Package id:packageId"); } @Test void testAdd1() { Package package1 = mock(Package.class); Package package2 = mock(Package.class); Package parent = mock(Package.class); when(package1.getId()).thenReturn("1"); when(package2.getId()).thenReturn("2"); when(parent.getId()).thenReturn("parent"); when(package1.getParent()).thenReturn(parent); when(package2.getParent()).thenReturn(parent); when(userPermissionEvaluator.hasPermission( new PackageIdentity(parent.getId()), PackagePermission.ADD_PACKAGE)) .thenReturn(true); MutableAcl acl1 = mock(MutableAcl.class); MutableAcl acl2 = mock(MutableAcl.class); MutableAcl parentAcl = mock(MutableAcl.class); doReturn(acl1).when(mutableAclService).createAcl(new PackageIdentity("1")); doReturn(acl2).when(mutableAclService).createAcl(new PackageIdentity("2")); when(mutableAclService.readAclById(new PackageIdentity("parent"))).thenReturn(parentAcl); Stream<Package> packages = Stream.of(package1, package2); repo.add(packages); @SuppressWarnings("unchecked") ArgumentCaptor<Stream<Package>> captor = ArgumentCaptor.forClass(Stream.class); verify(delegateRepository).add(captor.capture()); assertEquals(asList(package1, package2), captor.getValue().collect(toList())); } @Test void findOneByIdUserPermissionAllowed() { Package pack = mock(Package.class); when(pack.getId()).thenReturn("1"); when(delegateRepository.findOneById("1")).thenReturn(pack); when(userPermissionEvaluator.hasPermission(new PackageIdentity("1"), PackagePermission.VIEW)) .thenReturn(true); assertEquals(pack, repo.findOneById("1")); } @Test void findOneByIdUserPermissionDenied() { Package pack = mock(Package.class); when(pack.getId()).thenReturn("1"); when(delegateRepository.findOneById("1")).thenReturn(pack); when(userPermissionEvaluator.hasPermission(new PackageIdentity("1"), PackagePermission.VIEW)) .thenReturn(false); assertThrows(PackagePermissionDeniedException.class, () -> repo.findOneById("1")); } @Test void testMoveSysPack() { Package sys = mock(Package.class); when(sys.getId()).thenReturn("sys"); Package oldSys = mock(Package.class); when(delegateRepository.findOneById("sys")).thenReturn(oldSys); assertThrows(SystemMetadataModificationException.class, () -> repo.update(sys)); } @Test void testMoveFromSysPack() { Package sys = mock(Package.class); when(sys.getId()).thenReturn("sys"); Package root = mock(Package.class); when(root.getId()).thenReturn("root"); Package test = mock(Package.class); when(test.getId()).thenReturn("test"); when(test.getRootPackage()).thenReturn(root); Package oldTest = mock(Package.class); when(oldTest.getId()).thenReturn("test"); when(oldTest.getRootPackage()).thenReturn(sys); when(delegateRepository.findOneById("test")).thenReturn(oldTest); assertThrows(SystemMetadataModificationException.class, () -> repo.update(test)); } @Test void testMoveToSysPack() { Package sys = mock(Package.class); when(sys.getId()).thenReturn("sys"); Package test = mock(Package.class); when(test.getId()).thenReturn("test"); when(test.getRootPackage()).thenReturn(sys); Package oldTest = mock(Package.class); when(delegateRepository.findOneById("test")).thenReturn(oldTest); assertThrows(SystemMetadataModificationException.class, () -> repo.update(test)); } static class Config {} }
lgpl-3.0
racodond/sonar-css-plugin
css-frontend/src/main/java/org/sonar/css/model/function/standard/Max.java
1237
/* * SonarQube CSS / SCSS / Less Analyzer * Copyright (C) 2013-2017 David RACODON * mailto: david.racodon@gmail.com * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU Lesser General Public * License as published by the Free Software Foundation; either * version 3 of the License, or (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.css.model.function.standard; import org.sonar.css.model.function.StandardFunction; public class Max extends StandardFunction { public Max() { setCss(true); setLess(true); setObsolete(true); addLinks("https://www.w3.org/TR/2011/WD-css3-values-20110906/#max"); addLinks("http://lesscss.org/functions/#math-functions-max"); } }
lgpl-3.0
tango-controls/JTango
common/src/main/java/fr/esrf/TangoApi/DbPipe.java
9175
//+====================================================================== // $Source$ // // Project: Tango // // Description: java source code for the TANGO client/server API. // // $Author: pascal_verdier $ // // Copyright (C) : 2004,2005,2006,2007,2008,2009,2010,2011,2012,2013,2014, // European Synchrotron Radiation Facility // BP 220, Grenoble 38043 // FRANCE // // This file is part of Tango. // // Tango 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. // // Tango 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 Tango. If not, see <http://www.gnu.org/licenses/>. // // $Revision: 25296 $ // //-====================================================================== package fr.esrf.TangoApi; import java.util.concurrent.CopyOnWriteArrayList; /** * Class Description: * This class manage a list of DbDatum for pipe properties read/write * * @author verdier * @version $Revision: 25296 $ */ public class DbPipe extends CopyOnWriteArrayList<DbDatum> implements java.io.Serializable { private final String name; //=========================================================== /** * Default constructor for the DbPipe Object. * * @param name Attribute name. */ //=========================================================== public DbPipe(String name) { super(); this.name = name; } //=========================================================== /** * return pipe name. * * @return the pipe name. */ //=========================================================== public String getName() { return name; } //=========================================================== /** * get the DbDatum object by DbDatum.name. * * @param name index of the DbDatum expected. */ //=========================================================== public DbDatum getDatum(String name) { for (DbDatum datum : this) { if (name.equalsIgnoreCase(datum.name)) return datum; } return null; } //=========================================================== /** * Add a new DbDatum to the list * * @param name property name */ //=========================================================== public void add(String name) { add(new DbDatum(name, "")); } //=========================================================== /** * Add a new DbDatum to the list * * @param name property name * @param value property value */ //=========================================================== public void add(String name, String value) { add(new DbDatum(name, value)); } //=========================================================== /** * Add a new DbDatum to the list * * @param name property name * @param value property value */ //=========================================================== public void add(String name, short value) { add(new DbDatum(name, value)); } //=========================================================== /** * Add a new DbDatum to the list * * @param name property name * @param value property value */ //=========================================================== public void add(String name, int value) { add(new DbDatum(name, value)); } //=========================================================== /** * Add a new DbDatum to the list * * @param name property name * @param value property value */ //=========================================================== public void add(String name, double value) { add(new DbDatum(name, value)); } //=========================================================== /** * Add a new DbDatum to the list * * @param name property name * @param values property value */ //=========================================================== public void add(String name, String[] values) { add(new DbDatum(name, values)); } //=========================================================== /** * Add a new DbDatum to the list * * @param name property name * @param values property value */ //=========================================================== public void add(String name, short[] values) { add(new DbDatum(name, values)); } //=========================================================== /** * Add a new DbDatum to the list * * @param name property name * @param values property value */ //=========================================================== public void add(String name, int[] values) { add(new DbDatum(name, values)); } //=========================================================== /** * Add a new DbDatum to the list * * @param name property name * @param values property value */ //=========================================================== public void add(String name, double[] values) { add(new DbDatum(name, values)); } //=========================================================== /** * Return the property name * * @param index property index * @return property name */ //=========================================================== public String getPropertyName(int index) { return get(index).name; } //=========================================================== /** * Return the property value * * @param idx index of property * @return property values in an array of Strings */ //=========================================================== public String[] getValue(int idx) { return get(idx).extractStringArray(); } //=========================================================== /** * Return the property value as a String object * * @param index index of property * @return property value in a String object. */ //=========================================================== public String getStringValue(int index) { String[] array = get(index).extractStringArray(); StringBuilder str = new StringBuilder(); for (int i=0 ; i<array.length ; i++) { str.append(array[i]); if (i < array.length - 1) str.append("\n"); } return str.toString(); } //=========================================================== /** * Return the property value * * @param name property name * @return property value in an array of Strings */ //=========================================================== public String[] getValue(String name) { return getDatum(name).extractStringArray(); } //=========================================================== /** * Return the property value in aString object * * @param name property name * @return property value in aString object if exists, null otherwise */ //=========================================================== public String getStringValue(String name) { // Check if datum exists for name DbDatum datum = getDatum(name); if (datum == null) return null; // Else get string value String[] array = datum.extractStringArray(); StringBuilder str = new StringBuilder(); for (int i = 0; i < array.length; i++) { str.append(array[i]); if (i < array.length - 1) str.append("\n"); } return str.toString(); } //=========================================================== /** * Return true if property not found; * * @param name property name * @return true if property not found; */ //=========================================================== public boolean is_empty(String name) { DbDatum datum = getDatum(name); return datum == null || datum.is_empty(); } //=========================================================== /** * Return a list of properties found; * * @return a list of properties found; */ //=========================================================== public String[] getPropertyList() { String[] array = new String[size()]; for (int i=0 ; i<size(); i++) array[i] = get(i).name; return array; } }
lgpl-3.0
tomtix/HeuristicTSP
CVRP/Java/GiantTour.java
5352
package cvrp; import util.CustomList; import java.util.List; import java.util.ArrayList; import java.util.Collections; import tsp.HeuristicTSP; import tsp.FarNodeInsertHeuristicTSP; public class GiantTour { private VRPinstance vrp; private int clientCount; private int n; private double[][] distance; private int capacity; private List<VRProute> routes; private VRPcustomer[] customers; private int demand(int i) { return vrp.getDemand(i); } public GiantTour(VRPinstance vrp) { this.vrp = vrp; n = clientCount = vrp.getN(); distance = vrp.getMatrix(); customers = new VRPcustomer[clientCount]; routes = new ArrayList<VRProute>(); capacity = vrp.getCapacity(); } public double[][] getMatrix() { return distance; } public int getN() { return clientCount; } private int[] computeGT() { HeuristicTSP gtHeuristic = new FarNodeInsertHeuristicTSP(); List<Integer> gtList = new ArrayList<Integer>(); gtHeuristic.computeSolution(distance, gtList); int[] gt = new int[gtList.size()]; int[] v = new int[gtList.size()]; int depotPosition = -1; for (int i = 0; i < gtList.size(); ++i) { gt[i] = gtList.get(i); if (gt[i] == 0) depotPosition = i; } for (int i = 0; i < gt.length; ++i) v[i] = gt[(i + depotPosition) % gt.length]; return v; } private double computeSaving(VRProute r1, VRProute r2) { return new VRPmerge( distance, r1.getLastCustomer(), r2.getFirstCustomer() ).getSaving(); } private void buildGraph(int v[], Graph g) { double routeDemand[][] = new double[n][]; double cost[][] = new double[n][]; for (int i = 0; i < n; ++i) { routeDemand[i] = new double[n]; cost[i] = new double[n]; } for (int i = 0; i < n; ++i) { for (int j = i+1; j < n; ++j) { routeDemand[i][j] = routeDemand[i][j-1] + demand(v[j]); if (j == i+1) { cost[i][j] = distance[0][v[j]]+distance[v[j]][0]; } else { cost[i][j] = cost[i][j-1] + distance[v[j-1]][v[j]] + distance[v[j]][0] - distance[v[j-1]][0]; } if (routeDemand[i][j] <= capacity) g.addEdge(v[i], v[j], cost[i][j]); } } } public void buildSolution() { int[] v = computeGT(); Graph g = new Graph(v.length); buildGraph(v, g); for (int i = 0; i < v.length; ++i) System.err.println("v["+i+"] = " + v[i]); List<Integer> shortestPath; shortestPath = new ShortestPath(g, v[0], v[n-1]).getValue(); for (int i = 0; i < shortestPath.size(); ++i) System.err.println("shortestPath["+i+"] = " + shortestPath.get(i)); int k = 1; while (shortestPath.size() > 0) { VRProute r = new VRProute(vrp.getCapacity()); int next = shortestPath.remove(0); while (v[k] != next) { r.addCustomer(v[k], distance, vrp); ++ k; } r.addCustomer(v[k], distance, vrp); ++ k; routes.add(r); } } /**************************************************** * Print functions to debug ****************************************************/ public void printMatrix() { int N = getN(); for (int i = 0; i < N; i++) { for (int j = 0; j < N; j++) { System.err.print(distance[i][j] + " "); } System.err.println(""); } } public void printSolution() { System.out.println("Solution : " + routes.size()); double totalCost = 0; int count = 0; for (int i = 0; i < routes.size(); i++) { System.out.println("Route " + i); VRProute r = routes.get(i); System.out.println(r); totalCost += r.getCost(); count += r.getLength(); } System.out.println("total cost: "+totalCost); System.out.println("Expected client count: "+(clientCount-1)); System.out.println("total client count: "+count); } public void printRoutes() { for (int i = 0; i < routes.size(); i++) { System.err.println("Route num " + i); System.err.println((routes.get(i)).toString()); } } /******************************************************* * Main *******************************************************/ public static void main(String args[]) { GiantTour gt = null; if (args.length < 1) usage(); try { gt = new GiantTour(new VRPinstance(args[0])); } catch (java.io.FileNotFoundException e) { System.out.println("File not Found"); } System.out.println("GiantTour sur : " + args[0]); gt.buildSolution(); gt.printSolution(); } public static void usage() { System.out.println("Usage: GiantTour path/to/instance"); System.exit(1); } }
lgpl-3.0
Ash6390/JarCraft
src/main/java/com/ash6390/jarcraft/items/IlluminatingOrb.java
1814
package com.ash6390.jarcraft.items; import com.ash6390.jarcraft.creativetab.CreativeTabJC; import com.ash6390.jarcraft.init.ModBlocks; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; import net.minecraft.world.World; public class IlluminatingOrb extends ItemJC { public IlluminatingOrb() { super(); this.setUnlocalizedName("illuminatingOrb"); this.setCreativeTab(CreativeTabJC.JC_TAB); } public boolean onItemUse(ItemStack itemstack, EntityPlayer player, World world, int x, int y, int z, int face, float par8, float par9, float par10) { if (world.getBlock(x, y, z) == Blocks.tallgrass) { world.setBlock(x, y, z, ModBlocks.illuminatingOrbBlock); } else { switch (face) { case 0: world.setBlock(x, --y, z, ModBlocks.illuminatingOrbBlock, face, 2); break; case 1: world.setBlock(x, ++y, z, ModBlocks.illuminatingOrbBlock, face, 2); break; case 2: world.setBlock(x, y, --z, ModBlocks.illuminatingOrbBlock, face, 2); break; case 3: world.setBlock(x, y, ++z, ModBlocks.illuminatingOrbBlock, face, 2); break; case 4: world.setBlock(--x, y, z, ModBlocks.illuminatingOrbBlock, face, 2); break; case 5: world.setBlock(++x, y, z, ModBlocks.illuminatingOrbBlock, face, 2); break; default: return false; } } return true; } }
lgpl-3.0
hlfernandez/LogFileWatcher
src/main/java/es/uvigo/ei/sing/hlfernandez/logfilewatcher/listener/FileEvent.java
816
package es.uvigo.ei.sing.hlfernandez.logfilewatcher.listener; import java.util.EventObject; public class FileEvent extends EventObject { private static final long serialVersionUID = 1L; public static enum LogFileAction { CREATE, MODIFY, DELETE }; private LogFileAction action; /** * Constructs a {@link LogFileAction} object with the specified source * component and action type. * * @param source the object that originated the event. * @param action the action type. */ public FileEvent(Object source, LogFileAction action) { super(source); this.action = action; } /** * Returns an {@link LogFileAction} that represents the action type. * * @return an {@link LogFileAction} that represents the action type. */ public LogFileAction getAction() { return action; } }
lgpl-3.0
galleon1/chocolate-milk
src/org/chocolate_milk/model/types/descriptors/PayrollDetailReportTypeTypeDescriptor.java
3505
/* * This class was automatically generated with * <a href="http://www.castor.org">Castor 1.3.1</a>, using an XML * Schema. * $Id: PayrollDetailReportTypeTypeDescriptor.java,v 1.1.1.1 2010-05-04 22:06:02 ryan Exp $ */ package org.chocolate_milk.model.types.descriptors; //---------------------------------/ //- Imported classes and packages -/ //---------------------------------/ import org.chocolate_milk.model.types.PayrollDetailReportTypeType; /** * Class PayrollDetailReportTypeTypeDescriptor. * * @version $Revision: 1.1.1.1 $ $Date: 2010-05-04 22:06:02 $ */ public class PayrollDetailReportTypeTypeDescriptor 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 PayrollDetailReportTypeTypeDescriptor() { super(); _xmlName = "PayrollDetailReportTypeType"; _elementDefinition = false; } //-----------/ //- 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.types.PayrollDetailReportTypeType.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; } }
lgpl-3.0
subes/invesdwin-util
invesdwin-util-parent/invesdwin-util/src/main/java/de/invesdwin/util/marshallers/jackson/DurationDeserializer.java
940
package de.invesdwin.util.marshallers.jackson; import java.io.IOException; import javax.annotation.concurrent.Immutable; import com.fasterxml.jackson.core.JsonParser; import com.fasterxml.jackson.core.JsonProcessingException; import com.fasterxml.jackson.databind.DeserializationContext; import com.fasterxml.jackson.databind.JsonDeserializer; import de.invesdwin.util.time.duration.Duration; @Immutable public final class DurationDeserializer extends JsonDeserializer<Duration> { public static final DurationDeserializer INSTANCE = new DurationDeserializer(); private DurationDeserializer() {} @Override public Duration deserialize(final JsonParser p, final DeserializationContext ctxt) throws IOException, JsonProcessingException { final String string = p.getText().trim(); if (string.length() == 0) { return null; } return Duration.valueOf(string); } }
lgpl-3.0
lbndev/sonarqube
server/sonar-server/src/test/java/org/sonar/server/organization/ws/SearchMyOrganizationsActionTest.java
7970
/* * 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.server.organization.ws; import org.junit.Rule; import org.junit.Test; import org.sonar.api.server.ws.WebService; import org.sonar.api.utils.System2; import org.sonar.db.DbClient; import org.sonar.db.DbTester; import org.sonar.db.organization.OrganizationDto; import org.sonar.db.permission.OrganizationPermission; import org.sonar.db.user.GroupDto; import org.sonar.db.user.UserDto; import org.sonar.server.tester.UserSessionRule; import org.sonar.server.ws.TestResponse; import org.sonar.server.ws.WsActionTester; import static org.assertj.core.api.Assertions.assertThat; import static org.sonar.core.permission.GlobalPermissions.SYSTEM_ADMIN; import static org.sonar.db.permission.OrganizationPermission.ADMINISTER; import static org.sonar.test.JsonAssert.assertJson; public class SearchMyOrganizationsActionTest { private static final String NO_ORGANIZATIONS_RESPONSE = "{\"organizations\": []}"; @Rule public DbTester dbTester = DbTester.create(System2.INSTANCE); @Rule public UserSessionRule userSessionRule = UserSessionRule.standalone(); private DbClient dbClient = dbTester.getDbClient(); private WsActionTester underTest = new WsActionTester(new SearchMyOrganizationsAction(userSessionRule, dbClient)); @Test public void verify_definition() { WebService.Action def = underTest.getDef(); assertThat(def.key()).isEqualTo("search_my_organizations"); assertThat(def.isPost()).isFalse(); assertThat(def.isInternal()).isTrue(); assertThat(def.since()).isEqualTo("6.3"); assertThat(def.description()).isEqualTo("List keys of the organizations for which the currently authenticated user has the System Administer permission for."); assertThat(def.responseExample()).isNotNull(); assertThat(def.params()).isEmpty(); } @Test public void verify_response_example() { OrganizationDto organization1 = dbTester.organizations().insertForKey("my-org"); OrganizationDto organization2 = dbTester.organizations().insertForKey("foo-corp"); UserDto user = dbTester.users().insertUser(); dbTester.users().insertPermissionOnUser(organization1, user, SYSTEM_ADMIN); dbTester.users().insertPermissionOnUser(organization2, user, SYSTEM_ADMIN); userSessionRule.logIn(user); TestResponse response = underTest.newRequest().execute(); assertJson(response.getInput()).isSimilarTo(underTest.getDef().responseExampleAsString()); } @Test public void returns_empty_response_when_user_is_not_logged_in() { TestResponse response = underTest.newRequest().execute(); assertThat(response.getStatus()).isEqualTo(204); assertThat(response.getInput()).isEmpty(); } @Test public void returns_empty_array_when_user_is_logged_in_and_has_no_permission_on_anything() { userSessionRule.logIn(); TestResponse response = underTest.newRequest().execute(); assertJson(response.getInput()).isSimilarTo(NO_ORGANIZATIONS_RESPONSE); } @Test public void returns_organizations_of_authenticated_user_when_user_has_ADMIN_user_permission_on_some_organization() { UserDto user = dbTester.users().insertUser(); dbTester.users().insertPermissionOnUser(dbTester.getDefaultOrganization(), user, SYSTEM_ADMIN); OrganizationDto organization1 = dbTester.organizations().insert(); dbTester.users().insertPermissionOnUser(organization1, user, SYSTEM_ADMIN); UserDto otherUser = dbTester.users().insertUser(); OrganizationDto organization2 = dbTester.organizations().insert(); dbTester.users().insertPermissionOnUser(organization2, otherUser, SYSTEM_ADMIN); userSessionRule.logIn(user); assertJson(underTest.newRequest().execute().getInput()).isSimilarTo("{\"organizations\": [" + "\"" + dbTester.getDefaultOrganization().getKey() + "\"," + "\"" + organization1.getKey() + "\"" + "]}"); userSessionRule.logIn(otherUser); assertJson(underTest.newRequest().execute().getInput()).isSimilarTo("{\"organizations\": [" + "\"" + organization2.getKey() + "\"" + "]}"); userSessionRule.logIn(); assertJson(underTest.newRequest().execute().getInput()).isSimilarTo(NO_ORGANIZATIONS_RESPONSE); } @Test public void returns_organizations_of_authenticated_user_when_user_has_ADMIN_group_permission_on_some_organization() { UserDto user = dbTester.users().insertUser(); GroupDto defaultGroup = dbTester.users().insertGroup(dbTester.getDefaultOrganization()); dbTester.users().insertPermissionOnGroup(defaultGroup, ADMINISTER); dbTester.users().insertMember(defaultGroup, user); OrganizationDto organization1 = dbTester.organizations().insert(); GroupDto group1 = dbTester.users().insertGroup(organization1); dbTester.users().insertPermissionOnGroup(group1, ADMINISTER); dbTester.users().insertMember(group1, user); UserDto otherUser = dbTester.users().insertUser(); OrganizationDto organization2 = dbTester.organizations().insert(); GroupDto group2 = dbTester.users().insertGroup(organization2); dbTester.users().insertPermissionOnGroup(group2, ADMINISTER); dbTester.users().insertMember(group2, otherUser); userSessionRule.logIn(user); assertJson(underTest.newRequest().execute().getInput()).isSimilarTo("{\"organizations\": [" + "\"" + dbTester.getDefaultOrganization().getKey() + "\"," + "\"" + organization1.getKey() + "\"" + "]}"); userSessionRule.logIn(otherUser); assertJson(underTest.newRequest().execute().getInput()).isSimilarTo("{\"organizations\": [" + "\"" + organization2.getKey() + "\"" + "]}"); userSessionRule.logIn(); assertJson(underTest.newRequest().execute().getInput()).isSimilarTo(NO_ORGANIZATIONS_RESPONSE); } @Test public void returns_organization_of_authenticated_user_only_for_ADMIN_permission() { UserDto user = dbTester.users().insertUser(); OrganizationDto organization1 = dbTester.organizations().insert(); OrganizationDto organization2 = dbTester.organizations().insert(); GroupDto group = dbTester.users().insertGroup(organization2); dbTester.users().insertMember(group, user); OrganizationPermission.all() .filter(p -> p != ADMINISTER) .forEach(p -> { dbTester.users().insertPermissionOnUser(organization1, user, p); dbTester.users().insertPermissionOnGroup(group, p); }); userSessionRule.logIn(user); assertJson(underTest.newRequest().execute().getInput()).isSimilarTo(NO_ORGANIZATIONS_RESPONSE); } @Test public void do_not_return_organization_twice_if_user_has_ADMIN_permission_twice_or_more() { UserDto user = dbTester.users().insertUser(); OrganizationDto organization = dbTester.organizations().insert(); GroupDto group1 = dbTester.users().insertGroup(organization); dbTester.users().insertPermissionOnGroup(group1, ADMINISTER); dbTester.users().insertPermissionOnUser(organization, user, SYSTEM_ADMIN); userSessionRule.logIn(user); assertJson(underTest.newRequest().execute().getInput()).isSimilarTo("{\"organizations\": [" + "\"" + organization.getKey() + "\"" + "]}"); } }
lgpl-3.0
modelinglab/ocl
core/src/main/java/org/modelinglab/ocl/core/standard/operations/orderedSet/Append.java
1660
/* * To change this template, choose Tools | Templates * and open the template in the editor. */ package org.modelinglab.ocl.core.standard.operations.orderedSet; import com.google.common.base.Preconditions; import org.modelinglab.ocl.core.ast.Parameter; import org.modelinglab.ocl.core.ast.Operation; import org.modelinglab.ocl.core.ast.types.Classifier; import org.modelinglab.ocl.core.ast.types.OrderedSetType; import org.modelinglab.ocl.core.ast.types.TemplateParameterType; import org.modelinglab.ocl.core.ast.types.TemplateRestrictions; import javax.annotation.concurrent.Immutable; /** * * @author Gonzalo Ortiz Jaureguizar (gortiz at software.imdea.org) */ @Immutable public class Append extends Operation { private static final long serialVersionUID = 1L; public static Append createTemplateOperation() { return new Append(null, TemplateParameterType.getGenericCollectionElement()); } public Append(Operation templateOperation, Classifier tType) { super(templateOperation); OrderedSetType ost = new OrderedSetType(); ost.setElementType(tType); Classifier resultType = ost; setName("append"); setType(resultType); setSource(ost); Parameter s = new Parameter(); s.setName("s"); s.setType(tType); addOwnedParameter(s); } @Override public Operation specificOperation(Classifier sourceType, java.util.List<Classifier> argTypes, TemplateRestrictions restrictions) { return new Append(this.getTemplateOperation(), ((OrderedSetType) sourceType).getElementType()); } }
lgpl-3.0
c2mon/c2mon
c2mon-client/c2mon-client-core/src/test/java/cern/c2mon/client/core/cache/ClientDataTagCacheImplTest.java
10280
/****************************************************************************** * Copyright (C) 2010-2016 CERN. All rights not expressly granted are reserved. * * This file is part of the CERN Control and Monitoring Platform 'C2MON'. * C2MON 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. * * C2MON 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 C2MON. If not, see <http://www.gnu.org/licenses/>. *****************************************************************************/ package cern.c2mon.client.core.cache; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Set; import javax.jms.JMSException; import org.easymock.EasyMock; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import cern.c2mon.client.common.listener.TagListener; import cern.c2mon.client.common.tag.Tag; import cern.c2mon.client.core.config.C2monAutoConfiguration; import cern.c2mon.client.core.config.mock.CoreSupervisionServiceMock; import cern.c2mon.client.core.config.mock.JmsProxyMock; import cern.c2mon.client.core.config.mock.RequestHandlerMock; import java.sql.Timestamp; import java.util.ArrayList; import java.util.Collection; import java.util.HashSet; import java.util.Set; import javax.jms.JMSException; import org.easymock.EasyMock; import org.junit.Before; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.test.annotation.DirtiesContext; import org.springframework.test.context.ContextConfiguration; import org.springframework.test.context.junit4.SpringJUnit4ClassRunner; import cern.c2mon.client.core.jms.JmsProxy; import cern.c2mon.client.core.jms.RequestHandler; import cern.c2mon.client.core.tag.TagController; import cern.c2mon.client.core.service.CoreSupervisionService; import cern.c2mon.shared.client.tag.TagMode; import cern.c2mon.shared.client.tag.TagUpdate; import cern.c2mon.shared.client.tag.TagValueUpdate; import cern.c2mon.shared.client.tag.TransferTagImpl; import cern.c2mon.shared.common.datatag.DataTagQuality; import cern.c2mon.shared.common.datatag.DataTagQualityImpl; import cern.c2mon.shared.rule.RuleFormatException; import static junit.framework.Assert.*; import static org.easymock.EasyMock.anyObject; /** * @author Matthias Braeger */ @RunWith(SpringJUnit4ClassRunner.class) @ContextConfiguration(classes = { C2monAutoConfiguration.class, JmsProxyMock.class, RequestHandlerMock.class, CoreSupervisionServiceMock.class }) @DirtiesContext public class ClientDataTagCacheImplTest { /** * Component to test */ @Autowired private ClientDataTagCacheImpl cache; @Autowired private JmsProxy jmsProxyMock; @Autowired private RequestHandler requestHandlerMock; @Autowired private CoreSupervisionService supervisionManagerMock; @Autowired private CacheController cacheController; @Before public void init() { EasyMock.reset(jmsProxyMock, supervisionManagerMock, requestHandlerMock); cacheController.getLiveCache().clear(); cacheController.getHistoryCache().clear(); } @Test public void testEmptyCache() { assertEquals(0, cache.getAllSubscribedDataTags().size()); } /** * Adds two tags into the cache and subscribes them to a <code>DataTagUpdateListener</code>. * @throws Exception */ @Test public void testAddDataTagUpdateListener() throws Exception { // Test setup Set<Long> tagIds = new HashSet<>(); tagIds.add(1L); tagIds.add(2L); Collection<TagUpdate> serverUpdates = new ArrayList<>(tagIds.size()); for (Long tagId : tagIds) { serverUpdates.add(createValidTransferTag(tagId)); prepareClientDataTagCreateMock(tagId); } EasyMock.expect(requestHandlerMock.requestTags(tagIds)).andReturn(serverUpdates); EasyMock.expect(requestHandlerMock.requestTagValues(tagIds)).andReturn(new ArrayList<>(serverUpdates)); TagListener listener = EasyMock.createMock(TagListener.class); // run test EasyMock.replay(jmsProxyMock, requestHandlerMock); Collection<Tag> cachedTags = cache.getAllSubscribedDataTags(); assertEquals(0, cachedTags.size()); cache.subscribe(tagIds, listener); cachedTags = cache.getAllSubscribedDataTags(); assertEquals(2, cachedTags.size()); Thread.sleep(500); // check test success EasyMock.verify(jmsProxyMock, requestHandlerMock); } @Test public void testUnsubscribeAllDataTags() throws Exception { // test setup Set<Long> tagIds = new HashSet<>(); tagIds.add(1L); tagIds.add(2L); Collection<TagUpdate> serverUpdates = new ArrayList<>(tagIds.size()); for (Long tagId : tagIds) { serverUpdates.add(createValidTransferTag(tagId)); TagController cdtMock = prepareClientDataTagCreateMock(tagId); supervisionManagerMock.removeSupervisionListener(cdtMock); } EasyMock.expect(requestHandlerMock.requestTags(tagIds)).andReturn(serverUpdates); EasyMock.expect(requestHandlerMock.requestTagValues(tagIds)).andReturn(new ArrayList<TagValueUpdate>(serverUpdates)); TagListener listener1 = EasyMock.createMock(TagListener.class); TagListener listener2 = EasyMock.createMock(TagListener.class); // run test EasyMock.replay(jmsProxyMock, requestHandlerMock); cache.subscribe(tagIds, listener1); Thread.sleep(200); Collection<Tag> cachedTags = cache.getAllSubscribedDataTags(); assertEquals(2, cachedTags.size()); // NOT Registered listener cache.unsubscribeAllDataTags(listener2); Thread.sleep(200); cachedTags = cache.getAllSubscribedDataTags(); assertEquals(2, cachedTags.size()); // Registered listener cache.unsubscribeAllDataTags(listener1); Thread.sleep(200); cachedTags = cache.getAllSubscribedDataTags(); assertEquals(0, cachedTags.size()); Thread.sleep(200); // check test success EasyMock.verify(jmsProxyMock, requestHandlerMock); } @Test public void testContainsTag() throws Exception { // Test setup Set<Long> tagIds = new HashSet<>(); tagIds.add(1L); tagIds.add(2L); Collection<TagUpdate> serverUpdates = new ArrayList<>(tagIds.size()); for (Long tagId : tagIds) { serverUpdates.add(createValidTransferTag(tagId)); prepareClientDataTagCreateMock(tagId); } EasyMock.expect(requestHandlerMock.requestTags(tagIds)).andReturn(serverUpdates); EasyMock.expect(requestHandlerMock.requestTagValues(tagIds)).andReturn(new ArrayList<>(serverUpdates)); EasyMock.expectLastCall(); supervisionManagerMock.addSupervisionListener(anyObject(), anyObject(), anyObject(), anyObject()); EasyMock.expectLastCall().times(2); TagListener listener = EasyMock.createMock(TagListener.class); // run test EasyMock.replay(jmsProxyMock, supervisionManagerMock, requestHandlerMock); cache.subscribe(tagIds, listener); assertTrue(cache.containsTag(1L)); assertTrue(cache.containsTag(2L)); assertFalse(cache.containsTag(23423L)); Thread.sleep(500); // check test success EasyMock.verify(jmsProxyMock, supervisionManagerMock, requestHandlerMock); } @Test public void testHistoryMode() throws Exception { // Test setup Set<Long> tagIds = new HashSet<>(); tagIds.add(1L); tagIds.add(2L); Collection<TagUpdate> serverUpdates = new ArrayList<>(tagIds.size()); for (Long tagId : tagIds) { serverUpdates.add(createValidTransferTag(tagId)); prepareClientDataTagCreateMock(tagId); } EasyMock.expect(requestHandlerMock.requestTags(tagIds)).andReturn(serverUpdates); EasyMock.expect(requestHandlerMock.requestTagValues(tagIds)).andReturn(new ArrayList<>(serverUpdates)); TagListener listener = EasyMock.createMock(TagListener.class); // run test EasyMock.replay(jmsProxyMock, requestHandlerMock); cache.subscribe(tagIds, listener); cache.setHistoryMode(true); for (Long tagId : tagIds) { assertTrue(cache.containsTag(tagId)); } assertFalse(cache.containsTag(23423L)); assertTrue(cache.isHistoryModeEnabled()); cache.subscribe(tagIds, listener); Collection<Tag> cachedTags = cache.getAllSubscribedDataTags(); assertEquals(2, cachedTags.size()); Thread.sleep(500); // check test success EasyMock.verify(jmsProxyMock, requestHandlerMock); cache.setHistoryMode(false); } private TagController prepareClientDataTagCreateMock(final Long tagId) throws RuleFormatException, JMSException { TagController cdtMock = new TagController(tagId); cdtMock.update(createValidTransferTag(tagId)); return cdtMock; } private TagUpdate createValidTransferTag(final Long tagId) { return createValidTransferTag(tagId, Float.valueOf(1.234f)); } private TagUpdate createValidTransferTag(final Long tagId, Object value) { DataTagQuality tagQuality = new DataTagQualityImpl(); tagQuality.validate(); TransferTagImpl tagUpdate = new TransferTagImpl( tagId, value, "test value desc", (DataTagQualityImpl) tagQuality, TagMode.TEST, new Timestamp(System.currentTimeMillis() - 10000L), new Timestamp(System.currentTimeMillis() - 5000L), new Timestamp(System.currentTimeMillis()), "Test description", "My.data.tag.name", "My.jms.topic"); if (value != null) { tagUpdate.setValueClassName(value.getClass().getName()); } return tagUpdate; } }
lgpl-3.0
fjlopez/ctl-jvm
cucumber/java/src/main/java/cucumber/api/java/en_lol/ICANHAZ.java
574
package cucumber.api.java.en_lol; import cucumber.runtime.java.StepDefAnnotation; import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Retention(RetentionPolicy.RUNTIME) @Target(ElementType.METHOD) @StepDefAnnotation public @interface ICANHAZ { /** * @return a regular expression */ String value(); /** * @return max amount of time this is allowed to run for. 0 (default) means no restriction. */ int timeout() default 0; }
lgpl-3.0
PearXTeam/PearXLibMC
src/main/java/ru/pearx/libmc/common/tiles/syncable/TileSyncable.java
2698
package ru.pearx.libmc.common.tiles.syncable; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.entity.player.EntityPlayerMP; import net.minecraft.nbt.NBTTagCompound; import net.minecraft.network.NetworkManager; import net.minecraft.network.play.server.SPacketUpdateTileEntity; import net.minecraft.server.management.PlayerChunkMapEntry; import net.minecraft.tileentity.TileEntity; import net.minecraft.world.WorldServer; import net.minecraftforge.fml.relauncher.Side; import net.minecraftforge.fml.relauncher.SideOnly; import ru.pearx.libmc.PXLMC; import ru.pearx.libmc.common.networking.packets.CPacketUpdateTileEntitySyncable; import javax.annotation.Nullable; /** * Created by mrAppleXZ on 11.04.17 20:28. */ public abstract class TileSyncable extends TileEntity { @Override @SideOnly(Side.CLIENT) public void onDataPacket(NetworkManager net, SPacketUpdateTileEntity pkt) { super.onDataPacket(net, pkt); readFromNBT(pkt.getNbtCompound()); } @Override public NBTTagCompound getUpdateTag() { NBTTagCompound tag = super.writeToNBT(new NBTTagCompound()); writeCustomData(tag, WriteTarget.FULL_UPDATE); return tag; } @Nullable @Override public SPacketUpdateTileEntity getUpdatePacket() { return new SPacketUpdateTileEntity(getPos(), 1, getUpdateTag()); } @Override public void readFromNBT(NBTTagCompound compound) { super.readFromNBT(compound); readCustomData(compound); } @Override public NBTTagCompound writeToNBT(NBTTagCompound compound) { super.writeToNBT(compound); writeCustomData(compound, WriteTarget.SAVE); return compound; } public abstract void readCustomData(NBTTagCompound tag); public abstract void writeCustomData(NBTTagCompound tag, WriteTarget target, String... data); public NBTTagCompound writeCustomData(WriteTarget target, String... data) { NBTTagCompound tag = new NBTTagCompound(); writeCustomData(tag, target, data); return tag; } public void sendUpdates(EntityPlayer player, NBTTagCompound tag) { if(getWorld() instanceof WorldServer) { PlayerChunkMapEntry entr = ((WorldServer) getWorld()).getPlayerChunkMap().getEntry(getPos().getX() >> 4, getPos().getZ() >> 4); if(entr != null) { for (EntityPlayerMP p : entr.players) { if(player == null || player != p) PXLMC.NETWORK.sendTo(new CPacketUpdateTileEntitySyncable(getPos(), tag), p); } } } } }
lgpl-3.0
moonsea/maosheji
src/maosheji/core/util/CountInfoUtil.java
1619
package maosheji.core.util; import java.io.Serializable; import java.util.Date; @Deprecated public class CountInfoUtil implements Serializable{ /** * */ private static final long serialVersionUID = 1L; // 总访问量合计 protected int totalCount = 0; // 日访问量 protected int dayCount = 0; // 周访问量 protected int weekCount = 0; // 月访问量 protected int monthCount = 0; // 年访问量 protected int yearCount = 0; // 临时访问量 protected int tempCount = 0; protected Date date = new Date(); /** * @return */ public int getDayCount() { return dayCount; } /** * @return */ public int getMonthCount() { return monthCount; } /** * @return */ public int getTotalCount() { return totalCount; } /** * @return */ public int getWeekCount() { return weekCount; } /** * @return */ public int getYearCount() { return yearCount; } /** * @param i */ public void setDayCount(int i) { dayCount = i; } /** * @param i */ public void setMonthCount(int i) { monthCount = i; } /** * @param i */ public void setTotalCount(int i) { totalCount = i; } /** * @param i */ public void setWeekCount(int i) { weekCount = i; } /** * @param i */ public void setYearCount(int i) { yearCount = i; } /** * @return */ public Date getDate() { return date; } /** * @param date */ public void setDate(Date date) { this.date = date; } /** * @return */ public int getTempCount() { return tempCount; } /** * @param i */ public void setTempCount(int i) { tempCount = i; } }
lgpl-3.0
exodev/social
extras/samples/src/main/java/org/exoplatform/social/extras/samples/activity/UIEmotionActivityComposer.java
2460
/* * Copyright (C) 2003-2010 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 General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, see<http://www.gnu.org/licenses/>. */ package org.exoplatform.social.extras.samples.activity; import org.exoplatform.social.webui.composer.UIActivityComposer; import org.exoplatform.social.webui.composer.UIComposer.PostContext; import org.exoplatform.webui.application.WebuiRequestContext; import org.exoplatform.webui.config.annotation.ComponentConfig; import org.exoplatform.webui.config.annotation.EventConfig; import org.exoplatform.webui.core.UIComponent; import org.exoplatform.webui.core.lifecycle.UIApplicationLifecycle; import org.exoplatform.webui.event.Event; /** * * @author <a href="http://hoatuicomponent.getActivityComposersle.net">hoatle (hoatlevan at gmail dot com)</a> * @since Jul 22, 2010 */ @ComponentConfig( lifecycle = UIApplicationLifecycle.class, template = "classpath:groovy/social/webui/activity/UIEmotionActivityComposer.gtmpl", events = { @EventConfig(listeners = UIActivityComposer.CloseActionListener.class), @EventConfig(listeners = UIActivityComposer.SubmitContentActionListener.class), @EventConfig(listeners = UIActivityComposer.ActivateActionListener.class) }) public class UIEmotionActivityComposer extends UIActivityComposer { @Override protected void onActivate(Event<UIActivityComposer> event) { } @Override protected void onClose(Event<UIActivityComposer> event) { } @Override protected void onSubmit(Event<UIActivityComposer> event) { } @Override public void onPostActivity(PostContext postContext, UIComponent source, WebuiRequestContext requestContext, String postedMessage) throws Exception { } }
lgpl-3.0
ecologylab/ecologylabFundamental
src/ecologylab/generic/ConfParser.java
1277
package ecologylab.generic; import java.io.File; import java.io.FileNotFoundException; import java.util.HashMap; import java.util.NoSuchElementException; import java.util.Scanner; public class ConfParser { private File confFile; private HashMap<String, String> confMap; public ConfParser(File confFile) { this.confFile = confFile; } public void setConfFile(File confFile) { this.confFile = confFile; } public HashMap<String, String> parse() throws FileNotFoundException { confMap = new HashMap<String, String>(); if (!confFile.exists() || !confFile.canRead()) { System.err.println("Failed to parse conf file: " + confFile); throw new FileNotFoundException(); } //go line by line and add to the hash map if it's not a comment; Scanner scanner = new Scanner(confFile); scanner.useDelimiter("=|\\n"); while (scanner.hasNextLine()) { //ignore comments if (scanner.findInLine("#") != null) { scanner.nextLine(); continue; } try { String key = scanner.next().trim(); String value = scanner.next().trim(); System.out.println(key + ": " + value); confMap.put(key, value); } catch (NoSuchElementException e) { break; } } return confMap; } }
lgpl-3.0
mdmzero0/JSatTrak
src/jsattrak/about/CurvesPanel.java
4735
/* * ===================================================================== * Copyright (C) 2009 Shawn E. Gano * * This file is part of JSatTrak. * * JSatTrak 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. * * JSatTrak 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 JSatTrak. If not, see <http://www.gnu.org/licenses/>. * ===================================================================== * * $Id: CurvesPanel.java,v 1.1 2005/05/25 23:13:25 rbair Exp $ * * Copyright 2004 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. All rights reserved. */ package jsattrak.about; import java.awt.Color; import java.awt.GradientPaint; import java.awt.Graphics; import java.awt.Graphics2D; import java.awt.Paint; import java.awt.Rectangle; import java.awt.RenderingHints; import java.awt.Shape; import java.awt.geom.AffineTransform; import java.awt.geom.Area; import java.awt.geom.CubicCurve2D; import java.awt.geom.GeneralPath; public class CurvesPanel extends GradientPanel { private RenderingHints hints; private int counter = 0; public CurvesPanel() { hints = new RenderingHints(RenderingHints.KEY_ALPHA_INTERPOLATION, RenderingHints.VALUE_ALPHA_INTERPOLATION_QUALITY); hints.put(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON); hints.put(RenderingHints.KEY_COLOR_RENDERING, RenderingHints.VALUE_COLOR_RENDER_QUALITY); hints.put(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR); hints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY); } public void paintComponent(Graphics g) { counter++; Graphics2D g2 = (Graphics2D) g; g2.setRenderingHints(hints); super.paintComponent(g2); float width = getWidth(); float height = getHeight(); g2.translate(0, -30); drawCurve(g2, 20.0f, -10.0f, 20.0f, -10.0f, width / 2.0f - 40.0f, 10.0f, 0.0f, -5.0f, width / 2.0f + 40, 1.0f, 0.0f, 5.0f, 50.0f, 5.0f, false); g2.translate(0, 30); g2.translate(0, height - 60); drawCurve(g2, 30.0f, -15.0f, 50.0f, 15.0f, width / 2.0f - 40.0f, 1.0f, 15.0f, -25.0f, width / 2.0f, 1.0f / 2.0f, 0.0f, 25.0f, 15.0f, 6.0f, false); g2.translate(0, -height + 60); drawCurve(g2, height - 35.0f, -5.0f, height - 50.0f, 10.0f, width / 2.0f - 40.0f, 1.0f, height - 35.0f, -25.0f, width / 2.0f, 1.0f / 2.0f, height - 20.0f, 25.0f, 25.0f, 4.0f, true); } private void drawCurve(Graphics2D g2, float y1, float y1_offset, float y2, float y2_offset, float cx1, float cx1_offset, float cy1, float cy1_offset, float cx2, float cx2_offset, float cy2, float cy2_offset, float thickness, float speed, boolean invert) { float width = getWidth(); float height = getHeight(); double offset = Math.sin(counter / (speed * Math.PI)); float start_x = 0.0f; float start_y = y1 + (float) (offset * y1_offset); float end_x = width; float end_y = y2 + (float) (offset * y2_offset); float ctrl1_x = (float) offset * cx1_offset + cx1; float ctrl1_y = cy1 + (float) (offset * cy1_offset); float ctrl2_x = (float) (offset * cx2_offset) + cx2; float ctrl2_y = (float) (offset * cy2_offset) + cy2; CubicCurve2D curve = new CubicCurve2D.Double(start_x, start_y, ctrl1_x, ctrl1_y, ctrl2_x, ctrl2_y, end_x, end_y); GeneralPath path = new GeneralPath(curve); path.lineTo(width, height); path.lineTo(0, height); path.closePath(); Area thickCurve = new Area((Shape) path.clone()); AffineTransform translation = AffineTransform.getTranslateInstance(0, thickness); path.transform(translation); thickCurve.subtract(new Area(path)); Color start = new Color(255, 255, 255, 200); Color end = new Color(255, 255, 255, 0); Rectangle bounds = thickCurve.getBounds(); GradientPaint painter = new GradientPaint(0, curve.getBounds().y, invert ? end : start, 0, bounds.y + bounds.height, invert ? start : end); Paint oldPainter = g2.getPaint(); g2.setPaint(painter); g2.fill(thickCurve); g2.setPaint(oldPainter); } }
lgpl-3.0
Builders-SonarSource/sonarqube-bis
sonar-scanner-engine/src/main/java/org/sonar/scanner/bootstrap/MetricProvider.java
1746
/* * 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.scanner.bootstrap; import com.google.common.collect.Lists; import org.sonar.api.batch.ScannerSide; import org.sonar.api.ExtensionProvider; import org.sonar.api.batch.InstantiationStrategy; import org.sonar.api.measures.CoreMetrics; import org.sonar.api.measures.Metric; import org.sonar.api.measures.Metrics; import java.util.List; @ScannerSide @InstantiationStrategy(InstantiationStrategy.PER_BATCH) public class MetricProvider extends ExtensionProvider { private Metrics[] factories; public MetricProvider(Metrics[] factories) { this.factories = factories; } public MetricProvider() { this.factories = new Metrics[0]; } @Override public List<Metric> provide() { List<Metric> metrics = Lists.newArrayList(CoreMetrics.getMetrics()); for (Metrics factory : factories) { metrics.addAll(factory.getMetrics()); } return metrics; } }
lgpl-3.0
yangrongwei/ray-simple
learn_javaee/learnServlet-annotation/src/cn/yangrongwei/HelloServlet3.java
1138
package cn.yangrongwei; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.ServletOutputStream; import javax.servlet.annotation.WebServlet; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; /** * Servlet implementation class HelloServlet3 */ @WebServlet("/api/h3") public class HelloServlet3 extends HttpServlet { private static final long serialVersionUID = 1L; /** * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response) */ protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletOutputStream out = response.getOutputStream(); out.println("Hello from 3 world for GET"); } /** * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */ protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { ServletOutputStream out = response.getOutputStream(); out.println("Hello from 3 world for GET"); } }
unlicense
andreas-schluens-asdev/asdk
service-env/src/main/java/net/as_development/asdk/api/service/env/IServiceRegistryModule.java
4247
/** * This is free and unencumbered software released into the public domain. * * Anyone is free to copy, modify, publish, use, compile, sell, or * distribute this software, either in source code form or as a compiled * binary, for any purpose, commercial or non-commercial, and by any * means. * * In jurisdictions that recognize copyright laws, the author or authors * of this software dedicate any and all copyright interest in the * software to the public domain. We make this dedication for the benefit * of the public at large and to the detriment of our heirs and * successors. We intend this dedication to be an overt act of * relinquishment in perpetuity of all present and future rights to this * software under copyright law. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. * IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR * OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, * ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR * OTHER DEALINGS IN THE SOFTWARE. * * For more information, please refer to <http://unlicense.org/> */ package net.as_development.asdk.api.service.env; import java.util.List; import net.as_development.asdk.api.service.env.ServiceDescriptor; //============================================================================= /** Knows the binding between interfaces and real classes. * * It has to be used to instanciate real implementations for requested services. * How this will be done depends from the real implementation of this interface. * * E.g. rich platforms use reflection to create new service instances. * E.g. simple platforms use hard-coded stuff like new Xyz() instead. */ public interface IServiceRegistryModule { //-------------------------------------------------------------------------- /** @return a list of service names where this module knows special meta data for. * Note Those list wont be null - but can be empty. */ public List< String > listMetaServices () throws Exception; //-------------------------------------------------------------------------- /** @return a list of service names where this module can map a real implementation. * Note Those list wont be null - but can be empty. */ public List< String > listServices () throws Exception; //-------------------------------------------------------------------------- /** @return a meta object which describe the asked service more in detail. * * Note return value will be null in case service is not registered here. * * @param aService [IN] * the service those meta are asked for. */ public ServiceDescriptor getServiceMeta (final Class< ? > aService) throws Exception; //-------------------------------------------------------------------------- /** @return a meta object which describe the asked service more in detail. * * Note return value will be null in case service is not registered here. * * @param sService [IN] * the full qualified service name where meta data are asked for. */ public ServiceDescriptor getServiceMeta (final String sService) throws Exception; //-------------------------------------------------------------------------- /** maps the given service interface to a real implementation. * * @param aService [IN] * the service (interface) type. * * @return the mapped service object. */ public < T > T mapServiceToImplementation (final Class< ? > aService) throws Exception; //-------------------------------------------------------------------------- /** maps the given service interface to a real implementation. * * @param sService [IN] * the full qualified service (interface) name. * * @return the mapped service object. */ public < T > T mapServiceToImplementation (final String sService) throws Exception; }
unlicense
DataMonster/Java
CTCI/src/edu/java/moderate/TicTacToe.java
245
package edu.java.moderate; //Design an algorithm to figure out if someone has won a game of tic-tac-toe. public class TicTacToe { /** * @param args */ public static void main(String[] args) { // TODO Auto-generated method stub } }
unlicense
Bladefidz/algorithm
coursera/Algorithms/seam/TestArrayCopy.java
769
import edu.princeton.cs.algs4.In; import edu.princeton.cs.algs4.StdIn; import edu.princeton.cs.algs4.StdOut; public class TestArrayCopy { public static void main(String[] args) { int[][] test = new int[5][5]; for (int x = 0; x < 5; x++) { for (int y = 0; y < 5; y++) { test[x][y] = x*y; } } for (int x = 0; x < 5; x++) { for (int y = 0; y < 5; y++) { StdOut.print(test[x][y] + " "); } StdOut.println(); } StdOut.println("------"); int[][] copy = new int[4][5]; for (int x = 0; x < 4; x++) { System.arraycopy(test[x], 0, copy[x], 0, 2); System.arraycopy(test[x], 3, copy[x], 2, 2); } for (int x = 0; x < 4; x++) { for (int y = 0; y < 5; y++) { StdOut.print(copy[x][y] + " "); } StdOut.println(); } } }
unlicense
debop/spring-batch-experiments
chapter09/src/main/java/kr/spring/batch/chapter09/domain/OrderItem.java
1262
package kr.spring.batch.chapter09.domain; import lombok.Getter; import lombok.Setter; import org.hibernate.annotations.DynamicInsert; import org.hibernate.annotations.DynamicUpdate; import javax.persistence.Entity; import javax.persistence.GeneratedValue; import javax.persistence.Id; import javax.persistence.ManyToOne; import java.io.Serializable; import java.util.Objects; /** * kr.spring.batch.chapter09.domain.OrderItem * * @author 배성혁 sunghyouk.bae@gmail.com * @since 13. 8. 15. 오전 9:43 */ @Entity @DynamicInsert @DynamicUpdate @Getter @Setter public class OrderItem implements Serializable { public OrderItem() {} public OrderItem(String productId, Integer quantity) { this.productId = productId; this.quantity = quantity; } @Id @GeneratedValue private Long id; @ManyToOne private OrderEntity order; private String productId; private Integer quantity; @Override public boolean equals(Object obj) { return (obj != null) && (obj instanceof OrderItem) && (hashCode() == obj.hashCode()); } @Override public int hashCode() { return Objects.hashCode(productId); } private static final long serialVersionUID = 3079230828084336402L; }
unlicense
miachm/SODS
src/com/github/miachm/sods/OperationNotSupportedException.java
359
package com.github.miachm.sods; /** * Describe an legal operation which it's not already supported */ public class OperationNotSupportedException extends SodsException { private String message; OperationNotSupportedException(String s) { this.message = s; } @Override public String getMessage(){ return message; } }
unlicense
JDonFern123/Learning
src/main/java/com/strange/learn/handler/ConfigurationHandler.java
1029
package com.strange.learn.handler; import java.io.File; import com.strange.learn.reference.Reference; import cpw.mods.fml.client.event.ConfigChangedEvent; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import net.minecraftforge.common.config.Configuration; public class ConfigurationHandler { public static Configuration configuration; public static boolean testValue = false; public static void init(File configFile) { //Create config if (configuration == null) { configuration = new Configuration(configFile); loadConfiguration(); } } @SubscribeEvent public void onConfigurationChangedEvent (ConfigChangedEvent.OnConfigChangedEvent event) { if (event.modID.equalsIgnoreCase(Reference.MOD_ID)) { //Resync configs loadConfiguration(); } } private static void loadConfiguration() { testValue = configuration.getBoolean("configValue", Configuration.CATEGORY_GENERAL, false, "Test config value"); if (configuration.hasChanged()) { configuration.save(); } } }
unlicense
maxxx/android-utils
src/ru/maxdestroyer/utils/imgcache/ImageLoader.java
6581
package ru.maxdestroyer.utils.imgcache; import android.graphics.Bitmap; import android.graphics.BitmapFactory; import android.os.Environment; import android.util.Log; import android.widget.ImageView; import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import ru.maxdestroyer.utils.Convert; import ru.maxdestroyer.utils.Util; public class ImageLoader // extends AsyncTask<Object, Void, Bitmap> { private int width, height; private ImageView imv; public Bitmap b = null; private String img_addr = ""; public String path = ""; // (iv, url, path, resize, thumb, width, height); public ImageLoader(Object... iv) { imv = (ImageView)iv[0]; img_addr = (String)iv[1]; path = (String) iv[2]; boolean resize = false; if (iv.length > 3) resize = (Boolean) iv[3]; boolean useThumb = false; if (iv.length > 4) useThumb = (Boolean) iv[4]; if (iv.length > 5) width = (Integer) iv[5]; if (iv.length > 6) height = (Integer) iv[6]; if (img_addr.equals("")) { imv.setImageBitmap(null); return; } final boolean u = useThumb; final boolean r = resize; String fname = Convert.toStr(img_addr.hashCode()); if (u) fname = "thumb_" + fname; b = LoadCachedImage(fname, path); if (b != null) { imv.setImageBitmap(b); imv.setTag(1); } else // { Object[] obj = new Object[] {imv, img_addr, path, this, r, u, width, height}; new AsyncLoader().execute(obj); } // new Thread(new Runnable() // { // @Override // public void run() // { // String fname = Util.ToStr(img_addr.hashCode()); // if (u) // fname = "thumb_" + fname; // b = LoadCachedImage(fname, path); // // if (b != null) // { // imv.post(new Runnable() // { // @Override // public void run() // { // imv.setImageBitmap(b); // } // }); // } else // � ���� ���� // { // Object[] obj = new Object[] {imv, img_addr, path, this, r, u}; // new AsyncLoader().execute(obj); // } // } // }).start(); } public static void CacheImage(Bitmap bmp, String path, Object name) { if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) return; String root = Environment.getExternalStorageDirectory().toString(); File myDir = new File(root + path); if (!myDir.exists()) myDir.mkdirs(); String hashname = name + ".jpeg"; //Log.e("cache", hashname + "___" + bmp.getWidth()); try { FileOutputStream out = new FileOutputStream(new File (myDir, hashname)); //bmp.compress(Bitmap.CompressFormat.PNG, 100, out); bmp.compress(Bitmap.CompressFormat.JPEG, 85, out); out.flush(); out.close(); } catch (Exception e) { Log.e("CacheImage error", "a: " + name + ". " + e.toString()); e.printStackTrace(); } } public static void CacheImageThumb(Bitmap bmp, String path, Object name, int maxw, int maxh) { if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) return; String root = Environment.getExternalStorageDirectory().toString(); File myDir = new File(root + path); if (!myDir.exists()) myDir.mkdirs(); String hashname = "thumb_" + name.toString() + ".jpeg"; //Log.e("cache", hashname + "___" + bmp.getWidth()); try { bmp = Resize(bmp, maxw, maxh); FileOutputStream out = new FileOutputStream(new File (myDir, hashname)); bmp.compress(Bitmap.CompressFormat.JPEG, 85, out); out.flush(); out.close(); } catch (Exception e) { Log.e("CacheImageThumb error", "a: " + name + ". " + e.toString()); e.printStackTrace(); } } // public Bitmap CacheImage(InputStream input) // { // if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) // return null; // // String root = Environment.getExternalStorageDirectory().toString(); // File myDir = new File(root + MainFrame.PATH); // myDir.mkdirs(); // String hashname = Integer.toString(img_addr.hashCode()) + ".jpeg"; // File file = new File (myDir, hashname); // // try // { // FileOutputStream out = new FileOutputStream(file); // byte data[] = new byte[1024]; // int count; // while ((count = input.read(data)) != -1) // { // out.write(data, 0, count); // } // out.flush(); // out.close(); // input.close(); // } catch (Exception e) // { // e.printStackTrace(); // } // // return LoadCachedImage(img_addr.hashCode()); // } // public static Bitmap LoadCachedImage(String fileName, String path) { Bitmap bmp = null; if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) return bmp; String root = Environment.getExternalStorageDirectory().toString(); fileName = fileName + ".jpeg"; File f = new File(root + path + "/", fileName); if (!f.exists()) { Util.log("LoadCachedImage: file not found - " + f.getAbsolutePath()); return bmp; } String fullPath = f.getAbsolutePath(); //float sc = LoadScale(hash, suffix); BitmapFactory.Options options = new BitmapFactory.Options(); //if (Build.PRODUCT.equals("sdk_x86")) // �� ��������� ������ ������ �� �������! options.inPreferredConfig = Bitmap.Config.RGB_565; //else //options.inPreferredConfig = Bitmap.Config.ARGB_8888; //options.inSampleSize = 2; try { bmp = BitmapFactory.decodeFile(fullPath, options); } catch (Exception e) { Log.e("LoadCachedImage error", e.toString()); e.printStackTrace(); } return bmp; } public static boolean IsExists(String hash, String path) { if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) return false; String root = Environment.getExternalStorageDirectory().toString(); String filename = hash + ".jpeg"; File f = new File(root + path + "/", filename); if (!f.exists()) return false; return true; } public static Bitmap Resize(Bitmap oldBmp, int w, int h) throws FileNotFoundException { // Find the correct scale value. It should be the power of 2. int width_tmp = oldBmp.getWidth(), height_tmp = oldBmp.getHeight(); int scale = 1; while (true) { if (width_tmp / 2 < w || height_tmp / 2 < h) { break; } width_tmp /= 2; height_tmp /= 2; scale *= 2; } return Bitmap.createScaledBitmap(oldBmp, width_tmp, height_tmp, false); } }
unlicense
Pieterjaninfo/PP
src/pp/slides/cc5/CalcBaseListener.java
2812
// Generated from Calc.g4 by ANTLR 4.7 package pp.slides.cc5; import org.antlr.v4.runtime.ParserRuleContext; import org.antlr.v4.runtime.tree.ErrorNode; import org.antlr.v4.runtime.tree.TerminalNode; /** * This class provides an empty implementation of {@link CalcListener}, * which can be extended to create a listener which only needs to handle a subset * of the available methods. */ public class CalcBaseListener implements CalcListener { /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterMain(CalcParser.MainContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitMain(CalcParser.MainContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterDiv(CalcParser.DivContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitDiv(CalcParser.DivContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterMinus(CalcParser.MinusContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitMinus(CalcParser.MinusContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterMult(CalcParser.MultContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitMult(CalcParser.MultContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterNum(CalcParser.NumContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitNum(CalcParser.NumContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterPlus(CalcParser.PlusContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitPlus(CalcParser.PlusContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void enterEveryRule(ParserRuleContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void exitEveryRule(ParserRuleContext ctx) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void visitTerminal(TerminalNode node) { } /** * {@inheritDoc} * * <p>The default implementation does nothing.</p> */ @Override public void visitErrorNode(ErrorNode node) { } }
unlicense
clilystudio/NetBook
allsrc/com/ushaqi/zhuishushenqi/ui/feed/e.java
830
package com.ushaqi.zhuishushenqi.ui.feed; import android.app.AlertDialog; import android.view.View; import android.view.View.OnClickListener; import com.arcsoft.hpay100.a.a; import com.squareup.a.b; import com.ushaqi.zhuishushenqi.event.i; import com.ushaqi.zhuishushenqi.event.m; final class e implements View.OnClickListener { e(FeedListActivity paramFeedListActivity, AlertDialog paramAlertDialog, int paramInt1, int paramInt2) { } public final void onClick(View paramView) { this.a.dismiss(); if (this.b != this.c) { int i = a.e(this.b); a.b(this.d, "feed_chapter_count", i); i.a().c(new m()); } } } /* Location: E:\Progs\Dev\Android\Decompile\apktool\zssq\zssq-dex2jar.jar * Qualified Name: com.ushaqi.zhuishushenqi.ui.feed.e * JD-Core Version: 0.6.0 */
unlicense
smartictcoop/SmartDental
src/test/java/test/com/smict/appointment/GenerateAppointmentCode.java
1290
package test.com.smict.appointment; import org.junit.Test; import com.smict.appointment.action.AppointmentModel; import com.smict.appointment.action.AppointmentUtil; import org.junit.Assert; public class GenerateAppointmentCode { private String prefix = "APP"; private char separator = '/'; private int length = 5, nextNumber = 1, increment = 3; private String resultCode; @SuppressWarnings("deprecation") public void testGenAppointmentCode(){ int result = this.nextNumber + this.increment; StringBuilder sb = new StringBuilder(); /** * Make length. */ int zeroLength = this.length - String.valueOf(result).length(); if(zeroLength > 0){ while((sb.toString().length() + 1) <= zeroLength){ sb.append("0"); } resultCode = sb.append(String.valueOf(result)).toString(); sb.setLength(0); } /** * Assemply the code. */ this.resultCode = sb.append(this.prefix).append(this.separator).append(this.resultCode).toString(); Assert.assertEquals("APP/00004", this.resultCode); } @Test public void testRunGenAppointmentCode(){ AppointmentModel appModel = new AppointmentModel(); appModel.setBranchID("CMI"); appModel.setBranchCode("431"); AppointmentModel resultModel = AppointmentUtil.getAppointmentCode(appModel); } }
unlicense
Adaptivity/VeganOption
java/squeek/veganoption/blocks/IFluidFlowHandler.java
192
package squeek.veganoption.blocks; import net.minecraft.world.World; public interface IFluidFlowHandler { public boolean onFluidFlowInto(World world, int x, int y, int z, int flowDecay); }
unlicense
rokumar7/trial
AkkaSupervisorExample/src/test/java/org/akka/essentials/supervisor/example1/SupervisorTest.java
2017
package org.akka.essentials.supervisor.example1; import java.util.concurrent.TimeUnit; import org.akka.essentials.supervisor.example1.MyActorSystem.Result; import org.junit.Test; import scala.concurrent.Await; import scala.concurrent.duration.Duration; import akka.actor.ActorRef; import akka.actor.ActorSystem; import akka.actor.Props; import akka.actor.Terminated; import akka.pattern.Patterns; import akka.testkit.TestActorRef; import akka.testkit.TestKit; import akka.testkit.TestProbe; public class SupervisorTest extends TestKit { static ActorSystem _system = ActorSystem.create("faultTolerance"); TestActorRef<SupervisorActor> supervisor = TestActorRef.apply(new Props( SupervisorActor.class), _system); public SupervisorTest() { super(_system); } @Test public void successTest() throws Exception { supervisor.tell(Integer.valueOf(8)); Integer result = (Integer) Await.result( Patterns.ask(supervisor, new Result(), 5000), Duration.create(5000, TimeUnit.MILLISECONDS)); assert result.equals(Integer.valueOf(8)); } @Test public void resumeTest() throws Exception { TestActorRef<SupervisorActor> supervisor = TestActorRef.apply( new Props(SupervisorActor.class), _system); supervisor.tell(Integer.valueOf(-8)); Integer result = (Integer) Await.result( Patterns.ask(supervisor, new Result(), 5000), Duration.create(5000, TimeUnit.MILLISECONDS)); assert result.equals(Integer.valueOf(8)); } @Test public void restartTest() throws Exception { supervisor.tell(null); Integer result = (Integer) Await.result( Patterns.ask(supervisor, new Result(), 5000), Duration.create(5000, TimeUnit.MILLISECONDS)); assert result.equals(Integer.valueOf(0)); } @Test public void stopTest() throws Exception { ActorRef workerActor = supervisor.underlyingActor().childActor; TestProbe probe = new TestProbe(_system); probe.watch(workerActor); supervisor.tell(String.valueOf("Do Something")); probe.expectMsgClass(Terminated.class); } }
unlicense
W0mpRat/IntroToProgramming
Code/lesson7-1/lesson7-1/friends5/Person.java
2505
// BlueJ project: lesson7/friends5 // Implement the unfriend method. import java.util.ArrayList; public class Person { private String name; private ArrayList<Person> friends; public Person(String name) { this.name = name; friends = new ArrayList<Person>(); } /** * Adds the given friend to this Person's friends list. * @param friend the friend to add. */ public void addFriend(Person friend) { friends.add(friend); } /** * Removes nonFriend from the list of friends. * @param nonFriend the friend to remove */ public void unfriend(Person nonFriend) { // YOUR CODE HERE // Implement the unfriend method. // you can use the find(Person friend) method to get // the index of a friend (Code below). int position = find(nonFriend); if (position > 1) { friends.remove(position); } } /** * Finds friend in the friends list * @param a person to search for * @return -1 if the person is not found. The index of the person otherwise. */ public int find(Person friend) { for (int i = 0; i < friends.size(); i++) { if (friends.get(i).equals(friend)) { return i; } } // If the person is not found by the end of the friends list return -1; } /** * Gets a list of all of this Person's friends. * @return the names of the friends separated by a comma and a space. * e.g. "Sara, Cheng-Han, Cay" */ public String getFriends() { return getFriends(", "); } /** * Returns the names of the friends with separator between them. * @param separator string to put between names. * @return the names of the friends. */ public String getFriends(String separator) { String separatedFriends = ""; if (friends.size() > 0) { separatedFriends = separatedFriends + friends.get(0).name; } for (int i = 1; i < friends.size(); i++) { separatedFriends = separatedFriends + separator + friends.get(i).name; } return separatedFriends; } /** * Gets the number of friends this Person has. * @return the number of friends. */ public int getNumFriends() { return friends.size(); } }
unlicense
Arquisoft/ObservaTerra42
test/api/CountryTest.java
3814
package api; import static org.assertj.core.api.Assertions.assertThat; import static org.junit.Assert.assertEquals; import static play.mvc.Http.HeaderNames.LOCATION; import static play.mvc.Http.Status.OK; import static play.mvc.Http.Status.SEE_OTHER; import static play.test.Helpers.GET; import static play.test.Helpers.callAction; import static play.test.Helpers.contentAsString; import static play.test.Helpers.contentType; import static play.test.Helpers.fakeApplication; import static play.test.Helpers.fakeRequest; import static play.test.Helpers.header; import static play.test.Helpers.inMemoryDatabase; import static play.test.Helpers.routeAndCall; import static play.test.Helpers.status; import models.Country; import models.Indicator; import models.Observation; import org.junit.Before; import org.junit.Test; import play.mvc.Result; import play.test.FakeRequest; import play.test.WithApplication; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.node.ArrayNode; import com.fasterxml.jackson.databind.node.JsonNodeFactory; public class CountryTest extends WithApplication { ObjectMapper jsonMapper = new ObjectMapper(); @Before public void setUp() { start(fakeApplication(inMemoryDatabase())); Observation.deleteAll(); Country.deleteAll(); Indicator.deleteAll(); } @Test public void getCountry() throws Exception { Country spain = new Country("es","Spain"); spain.save(); JsonNode jsonSpain = Country.toJson(spain); Result result = callAction(controllers.routes.ref.API.country("es")); assertThat(status(result)).isEqualTo(OK); assertThat(contentType(result)).isEqualTo("application/json"); JsonNode returned = jsonMapper.readTree(contentAsString(result)); assertEquals(jsonSpain, returned); } @Test public void getCountries() throws Exception { // Create 2 countries and save them in db Country spain = new Country("es","Spain"); spain.save(); Country france = new Country("fr","France"); france.save(); // generate the corresponding Json JsonNodeFactory factory = JsonNodeFactory.instance; ArrayNode expected = new ArrayNode(factory); expected.add(Country.toJson(spain)); expected.add(Country.toJson(france)); Result result = callAction(controllers.routes.ref.API.countries()); assertThat(status(result)).isEqualTo(OK); assertThat(contentType(result)).isEqualTo("application/json"); JsonNode returned = jsonMapper.readTree(contentAsString(result)); assertEquals(expected, returned); } @SuppressWarnings("deprecation") @Test public void addCountry() throws Exception { JsonNodeFactory factory = JsonNodeFactory.instance; Country spain = new Country("es","Spain"); JsonNode jsonSpain = Country.toJson(spain); @SuppressWarnings("unused") FakeRequest request = fakeRequest("POST", "/api/country").withJsonBody(jsonSpain); Result result = callAction(controllers.routes.ref.API.addCountry(), fakeRequest(). withHeader("Content-Type", "application/json"). withJsonBody(jsonSpain)); assertThat(status(result)).isEqualTo(SEE_OTHER); String location = header(LOCATION,result); assertEquals(location, "/api/country"); Result result2 = routeAndCall(fakeRequest(GET, location));; assertThat(status(result2)).isEqualTo(OK); assertThat(contentType(result2)).isEqualTo("application/json"); JsonNode returned = jsonMapper.readTree(contentAsString(result2)); ArrayNode expected = new ArrayNode(factory); expected.add(jsonSpain); assertEquals(expected, returned); } }
unlicense
Niclauz/TopVideoNews
app/src/main/java/cn/com/ichile/topvideonews/adapter/BaseRecycleAdapter.java
2033
package cn.com.ichile.topvideonews.adapter; import android.support.v7.widget.RecyclerView; import android.view.LayoutInflater; import android.view.View; import android.view.ViewGroup; import java.util.ArrayList; import java.util.List; import cn.com.ichile.topvideonews.inter.BaseAdapterInter; /** * FBI WARNING ! MAGIC ! DO NOT TOUGH ! * Created by WangZQ on 2017/1/9 - 11:13. */ public class BaseRecycleAdapter<T> extends RecyclerView.Adapter implements BaseAdapterInter { protected List<T> mDataList; protected static final int ITEM = 0; protected static final int FOOTER = 1; BaseRecycleAdapter(List<T> list) { if (mDataList == null) { mDataList = new ArrayList<>(); } // if (list != null) // mDataList.addAll(list); } @Override public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { return null; } @Override public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) { // } protected View getView(ViewGroup parent, int layoutId) { return LayoutInflater.from(parent.getContext()).inflate(layoutId, parent, false); } @Override public int getItemCount() { if (mDataList == null) { return 0; } return mDataList.size(); } public void add(int position, T item) { mDataList.add(position, item); notifyItemInserted(position); } public void addAll(List<T> list) { mDataList.clear(); mDataList.addAll(list); notifyDataSetChanged(); //notifyItemRangeInserted(0,mDataList.size()); } public void addMore(List<T> list) { int startPosition = mDataList.size(); mDataList.addAll(list); notifyItemRangeInserted(startPosition, mDataList.size()); } public List<T> getData() { return mDataList; } public void setData(List<T> data) { mDataList = data; notifyDataSetChanged(); } }
apache-2.0
wiipsp/ClearGuestWebservice
src/main/java/org/projectx/webservice/push/alias_bind_unbind.java
2921
package org.projectx.webservice.push; import java.util.ArrayList; import java.util.List; import com.gexin.rp.sdk.base.IAliasResult; import com.gexin.rp.sdk.base.impl.Target; import com.gexin.rp.sdk.http.IGtPush; public class alias_bind_unbind { static String appId = "请输入appId"; static String appkey = "请输入appkey"; static String master = "请输入master"; static String CID = "请输入CID"; static String Alias = "请输入Alias"; static String host = "http://sdk.open.api.igexin.com/apiex.htm"; /** * @param args * @throws Exception */ public static void main(String[] args) throws Exception { // TODO Auto-generated method stub // 单个ClientId别名绑定 bindAlias(); // 根据别名查询ClientId // queryClientId(); // //根据ClientId查询别名 // queryAilas(); // //解除单个Client的别名绑定 // AliasUnBind(); // //相同别名绑定多个ClientId的功能 // bindAliasAll(); // //解除别名下的所有ClientId绑定 // AliasUnBindAll(); } public static void bindAlias() throws Exception { IGtPush push = new IGtPush(host, appkey, master); push.connect(); // 单个CID绑定别名 IAliasResult bindSCid = push.bindAlias(appId, Alias, CID); System.out.println("绑定结果:" + bindSCid.getResult() + "错误码:" + bindSCid.getErrorMsg()); } public static void queryClientId() throws Exception { IGtPush push = new IGtPush(host, appkey, master); push.connect(); IAliasResult queryClient = push.queryClientId(appId, Alias); System.out.println("根据别名获取的CID:" + queryClient.getClientIdList()); } public static void queryAilas() throws Exception { IGtPush push = new IGtPush(host, appkey, master); push.connect(); IAliasResult queryRet = push.queryAlias(appId, CID); System.out.println("根据cid获取别名:" + queryRet.getAlias()); } public static void AliasUnBind() throws Exception { IGtPush push = new IGtPush(host, appkey, master); push.connect(); IAliasResult AliasUnBind = push.unBindAlias(appId, Alias,CID); System.out.println("解除绑定结果:"+AliasUnBind.getResult()); } public static void bindAliasAll() throws Exception { IGtPush push = new IGtPush(host, appkey, master); push.connect(); List<Target> Lcids = new ArrayList<Target>(); Target target = new Target(); target.setClientId(CID); target.setAlias(Alias); Lcids.add(target); IAliasResult AliasUnBind = push.bindAlias(appId, Lcids); System.out.println("解除绑定结果:"+AliasUnBind.getResult()); } public static void AliasUnBindAll() throws Exception { IGtPush push = new IGtPush(host, appkey, master); push.connect(); IAliasResult AliasUnBindAll = push.unBindAliasAll(appId, Alias); System.out.println("解除绑定结果:"+AliasUnBindAll.getResult()); } }
apache-2.0
chiclaim/android-sample
android-optimization/app/src/main/java/com/chiclaim/optimization/launchtime/TimeRecord.java
371
package com.chiclaim.optimization.launchtime; import android.util.Log; public class TimeRecord { private static long startTime; public static void startRecord() { startTime = System.currentTimeMillis(); } public static void stopRecord(String tag) { Log.e("TimeRecord", tag + ":" + (System.currentTimeMillis() - startTime)); } }
apache-2.0
ingenieux/beanstalker
beanstalk-maven-plugin/src/test/java/br/com/ingenieux/mojo/beanstalk/MinimalTestSuite.java
1153
/* * Copyright (c) 2016 ingenieux Labs * * 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 br.com.ingenieux.mojo.beanstalk; import junit.framework.Test; import junit.framework.TestResult; import junit.framework.TestSuite; import org.junit.Ignore; @Ignore public class MinimalTestSuite { public static Test suite() { TestSuite suite = new TestSuite(MinimalTestSuite.class.getName()); // $JUnit-BEGIN$ suite.addTestSuite(CheckAvailabilityMojoTest.class); suite.addTestSuite(BootstrapTest.class); // $JUnit-END$ return suite; } public static void run(TestResult result) { suite().run(result); } }
apache-2.0
Apicurio/apicurio-studio
back-end/hub-core/src/main/java/io/apicurio/hub/core/beans/ApiTemplatePublication.java
2959
/* * Copyright 2017 JBoss 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 io.apicurio.hub.core.beans; import java.util.Date; /** * @author c.desc2@gmail.com */ public class ApiTemplatePublication { private String designId; private String name; private String description; private long contentVersion; private String createdBy; private Date createdOn; /** * Constructor. */ public ApiTemplatePublication() { } public ApiTemplatePublication(String designId, String name, String description, long contentVersion, String createdBy, Date createdOn) { this.designId = designId; this.name = name; this.description = description; this.contentVersion = contentVersion; this.createdBy = createdBy; this.createdOn = createdOn; } /** * @return the designId */ public String getDesignId() { return designId; } /** * @param designId the designId to set */ public void setDesignId(String designId) { this.designId = designId; } /** * @return the name */ public String getName() { return name; } /** * @param name the name to set */ public void setName(String name) { this.name = name; } /** * @return the description */ public String getDescription() { return description; } /** * @param description the description to set */ public void setDescription(String description) { this.description = description; } /** * @return the contentVersion */ public long getContentVersion() { return contentVersion; } /** * @param contentVersion the contentVersion to set */ public void setContentVersion(long contentVersion) { this.contentVersion = contentVersion; } /** * @return the createdBy */ public String getCreatedBy() { return createdBy; } /** * @param createdBy the createdBy to set */ public void setCreatedBy(String createdBy) { this.createdBy = createdBy; } /** * @return the createdOn */ public Date getCreatedOn() { return createdOn; } /** * @param createdOn the createdOn to set */ public void setCreatedOn(Date createdOn) { this.createdOn = createdOn; } }
apache-2.0
statsbiblioteket/doms-pidregistration
src/main/java/dk/statsbiblioteket/pidregistration/database/dao/JobsIterator.java
1245
package dk.statsbiblioteket.pidregistration.database.dao; import dk.statsbiblioteket.pidregistration.database.DatabaseException; import dk.statsbiblioteket.pidregistration.database.dto.JobDTO; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Iterator; import java.util.NoSuchElementException; public class JobsIterator implements Iterator<JobDTO> { private ResultSet jobs; private JobDTO element; public JobsIterator(ResultSet jobs) { this.jobs = jobs; } @Override public boolean hasNext() { if (element == null){ try { if (jobs.next()) { element = JobsDAO.resultSetToJobDTO(jobs); return true; } else { jobs.close(); return false; } } catch (SQLException e) { throw new DatabaseException(e); } } else { return true; } } @Override public JobDTO next() { if (hasNext()){ JobDTO result = element; element = null; return result; } else { throw new NoSuchElementException(); } } }
apache-2.0
IstiN/android_training_2014
task_manager/app/src/main/java/com/epam/training/taskmanager/VkLoginActivity.java
3997
package com.epam.training.taskmanager; import android.app.AlertDialog; import android.content.DialogInterface; import android.graphics.Bitmap; import android.os.Bundle; import android.support.v7.app.ActionBarActivity; import android.util.Log; import android.view.View; import android.webkit.WebView; import android.webkit.WebViewClient; import com.epam.training.taskmanager.auth.VkOAuthHelper; public class VkLoginActivity extends ActionBarActivity implements VkOAuthHelper.Callbacks { private static final String TAG = VkLoginActivity.class.getSimpleName(); private WebView mWebView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_vk_login); getSupportActionBar().hide(); mWebView = (WebView) findViewById(R.id.webView); mWebView.getSettings().setJavaScriptEnabled(true); mWebView.getSettings().setJavaScriptCanOpenWindowsAutomatically(true); mWebView.setWebViewClient(new VkWebViewClient()); mWebView.loadUrl(VkOAuthHelper.AUTORIZATION_URL); } @Override public void onError(Exception e) { new AlertDialog.Builder(this) .setTitle("Error") .setMessage(e.getMessage()) .setPositiveButton("Ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { setResult(RESULT_CANCELED); finish(); } }) .create() .show(); } @Override public void onSuccess() { setResult(RESULT_OK); finish(); } private class VkWebViewClient extends WebViewClient { public VkWebViewClient() { super(); } @Override public void onPageStarted(WebView view, String url, Bitmap favicon) { Log.d(TAG, "page started " + url); showProgress(); view.setVisibility(View.INVISIBLE); } /* (non-Javadoc) * @see android.webkit.WebViewClient#shouldOverrideUrlLoading(android.webkit.WebView, java.lang.String) */ @Override public boolean shouldOverrideUrlLoading(WebView view, String url) { Log.d(TAG, "overr " + url); if (VkOAuthHelper.proceedRedirectURL(VkLoginActivity.this, url, VkLoginActivity.this)) { Log.d(TAG, "overr redr"); view.setVisibility(View.INVISIBLE); return true; } else { //view.loadUrl(url); return false; } } @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) { super.onReceivedError(view, errorCode, description, failingUrl); //showProgress("Error: " + description); view.setVisibility(View.VISIBLE); dismissProgress(); Log.d(TAG, "error " + failingUrl); } @Override public void onPageFinished(WebView view, String url) { super.onPageFinished(view, url); Log.d(TAG, "finish " + url); /* if (url.contains("&amp;")) { url = url.replace("&amp;", "&"); Log.d(TAG, "overr after replace " + url); view.loadUrl(url); return; }*/ view.setVisibility(View.VISIBLE); //if (!VkOAuthHelper.proceedRedirectURL(VkLoginActivity.this, url, success)) { dismissProgress(); //} } } private void dismissProgress() { findViewById(android.R.id.progress).setVisibility(View.GONE); } private void showProgress() { findViewById(android.R.id.progress).setVisibility(View.VISIBLE); } }
apache-2.0
electrum/presto
plugin/trino-bigquery/src/test/java/io/trino/plugin/bigquery/TestBigQueryIntegrationSmokeTest.java
13954
/* * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package io.trino.plugin.bigquery; import com.google.common.collect.ImmutableMap; import io.trino.testing.AbstractTestIntegrationSmokeTest; import io.trino.testing.MaterializedResult; import io.trino.testing.QueryRunner; import org.testng.annotations.DataProvider; import org.testng.annotations.Test; import static io.trino.plugin.bigquery.BigQueryQueryRunner.BigQuerySqlExecutor; import static io.trino.spi.type.VarcharType.VARCHAR; import static io.trino.testing.MaterializedResult.resultBuilder; import static io.trino.testing.assertions.Assert.assertEquals; import static io.trino.testing.sql.TestTable.randomTableSuffix; import static java.lang.String.format; import static org.assertj.core.api.Assertions.assertThat; import static org.testng.Assert.assertFalse; import static org.testng.Assert.assertTrue; @Test public class TestBigQueryIntegrationSmokeTest // TODO extend BaseConnectorTest extends AbstractTestIntegrationSmokeTest { private BigQuerySqlExecutor bigQuerySqlExecutor; @Override protected QueryRunner createQueryRunner() throws Exception { this.bigQuerySqlExecutor = new BigQuerySqlExecutor(); return BigQueryQueryRunner.createQueryRunner( ImmutableMap.of(), ImmutableMap.of()); } @Test public void testCreateSchema() { String schemaName = "test_create_schema"; assertUpdate("DROP SCHEMA IF EXISTS " + schemaName); assertUpdate("CREATE SCHEMA " + schemaName); assertUpdate("CREATE SCHEMA IF NOT EXISTS " + schemaName); assertQueryFails( "CREATE SCHEMA " + schemaName, format("\\Qline 1:1: Schema 'bigquery.%s' already exists\\E", schemaName)); assertUpdate("DROP SCHEMA " + schemaName); } @Test public void testDropSchema() { String schemaName = "test_drop_schema"; assertUpdate("DROP SCHEMA IF EXISTS " + schemaName); assertUpdate("CREATE SCHEMA " + schemaName); assertUpdate("DROP SCHEMA " + schemaName); assertUpdate("DROP SCHEMA IF EXISTS " + schemaName); assertQueryFails( "DROP SCHEMA " + schemaName, format("\\Qline 1:1: Schema 'bigquery.%s' does not exist\\E", schemaName)); } @Override public void testDescribeTable() { MaterializedResult expectedColumns = resultBuilder(getSession(), VARCHAR, VARCHAR, VARCHAR, VARCHAR) .row("orderkey", "bigint", "", "") .row("custkey", "bigint", "", "") .row("orderstatus", "varchar", "", "") .row("totalprice", "double", "", "") .row("orderdate", "date", "", "") .row("orderpriority", "varchar", "", "") .row("clerk", "varchar", "", "") .row("shippriority", "bigint", "", "") .row("comment", "varchar", "", "") .build(); MaterializedResult actualColumns = computeActual("DESCRIBE orders"); assertEquals(actualColumns, expectedColumns); } @Test(dataProvider = "createTableSupportedTypes") public void testCreateTableSupportedType(String createType, String expectedType) { String tableName = "test_create_table_supported_type_" + createType.replaceAll("[^a-zA-Z0-9]", ""); assertUpdate("DROP TABLE IF EXISTS " + tableName); assertUpdate(format("CREATE TABLE %s (col1 %s)", tableName, createType)); assertEquals( computeScalar("SELECT data_type FROM information_schema.columns WHERE table_name = '" + tableName + "' AND column_name = 'col1'"), expectedType); assertUpdate("DROP TABLE " + tableName); } @DataProvider public Object[][] createTableSupportedTypes() { return new Object[][] { {"boolean", "boolean"}, {"tinyint", "bigint"}, {"smallint", "bigint"}, {"integer", "bigint"}, {"bigint", "bigint"}, {"double", "double"}, {"decimal", "decimal(38,9)"}, {"date", "date"}, {"time with time zone", "time(3) with time zone"}, {"timestamp", "timestamp(3)"}, {"timestamp with time zone", "timestamp(3) with time zone"}, {"char", "varchar"}, {"char(65535)", "varchar"}, {"varchar", "varchar"}, {"varchar(65535)", "varchar"}, {"varbinary", "varbinary"}, {"array(bigint)", "array(bigint)"}, {"row(x bigint, y double)", "row(x bigint, y double)"}, {"row(x array(bigint))", "row(x array(bigint))"}, }; } @Test(dataProvider = "createTableUnsupportedTypes") public void testCreateTableUnsupportedType(String createType) { String tableName = "test_create_table_unsupported_type_" + createType.replaceAll("[^a-zA-Z0-9]", ""); assertUpdate("DROP TABLE IF EXISTS " + tableName); assertQueryFails( format("CREATE TABLE %s (col1 %s)", tableName, createType), "Unsupported column type: " + createType); assertUpdate("DROP TABLE IF EXISTS " + tableName); } @DataProvider public Object[][] createTableUnsupportedTypes() { return new Object[][] { {"json"}, {"uuid"}, {"ipaddress"}, }; } @Test public void testCreateTableWithRowTypeWithoutField() { String tableName = "test_row_type_table"; assertUpdate("DROP TABLE IF EXISTS " + tableName); assertQueryFails( "CREATE TABLE " + tableName + "(col1 row(int))", "\\QROW type does not have field names declared: row(integer)\\E"); assertUpdate("DROP TABLE IF EXISTS " + tableName); } @Test public void testCreateTableAlreadyExists() { String tableName = "test_create_table_already_exists"; assertUpdate("DROP TABLE IF EXISTS " + tableName); assertUpdate("CREATE TABLE " + tableName + "(col1 int)"); assertQueryFails( "CREATE TABLE " + tableName + "(col1 int)", "\\Qline 1:1: Table 'bigquery.tpch.test_create_table_already_exists' already exists\\E"); assertUpdate("DROP TABLE IF EXISTS " + tableName); } @Test public void testCreateTableIfNotExists() { String tableName = "test_create_table_if_not_exists"; assertUpdate("DROP TABLE IF EXISTS " + tableName); assertUpdate("CREATE TABLE " + tableName + "(col1 int)"); assertUpdate("CREATE TABLE IF NOT EXISTS " + tableName + "(col1 int)"); assertUpdate("DROP TABLE IF EXISTS " + tableName); } @Test public void testDropTable() { String tableName = "test_drop_table"; assertUpdate("DROP TABLE IF EXISTS " + tableName); assertUpdate("CREATE TABLE " + tableName + "(col bigint)"); assertTrue(getQueryRunner().tableExists(getSession(), tableName)); assertUpdate("DROP TABLE " + tableName); assertFalse(getQueryRunner().tableExists(getSession(), tableName)); } @Test(enabled = false) public void testSelectFromHourlyPartitionedTable() { onBigQuery("DROP TABLE IF EXISTS test.hourly_partitioned"); onBigQuery("CREATE TABLE test.hourly_partitioned (value INT64, ts TIMESTAMP) PARTITION BY TIMESTAMP_TRUNC(ts, HOUR)"); onBigQuery("INSERT INTO test.hourly_partitioned (value, ts) VALUES (1000, '2018-01-01 10:00:00')"); MaterializedResult actualValues = computeActual("SELECT COUNT(1) FROM test.hourly_partitioned"); assertEquals((long) actualValues.getOnlyValue(), 1L); } @Test(enabled = false) public void testSelectFromYearlyPartitionedTable() { onBigQuery("DROP TABLE IF EXISTS test.yearly_partitioned"); onBigQuery("CREATE TABLE test.yearly_partitioned (value INT64, ts TIMESTAMP) PARTITION BY TIMESTAMP_TRUNC(ts, YEAR)"); onBigQuery("INSERT INTO test.yearly_partitioned (value, ts) VALUES (1000, '2018-01-01 10:00:00')"); MaterializedResult actualValues = computeActual("SELECT COUNT(1) FROM test.yearly_partitioned"); assertEquals((long) actualValues.getOnlyValue(), 1L); } @Test(description = "regression test for https://github.com/trinodb/trino/issues/7784") public void testSelectWithSingleQuoteInWhereClause() { String tableName = "test.select_with_single_quote"; onBigQuery("DROP TABLE IF EXISTS " + tableName); onBigQuery("CREATE TABLE " + tableName + "(col INT64, val STRING)"); onBigQuery("INSERT INTO " + tableName + " VALUES (1,'escape\\'single quote')"); MaterializedResult actualValues = computeActual("SELECT val FROM " + tableName + " WHERE val = 'escape''single quote'"); assertEquals(actualValues.getRowCount(), 1); assertEquals(actualValues.getOnlyValue(), "escape'single quote"); } @Test(description = "regression test for https://github.com/trinodb/trino/issues/5618") public void testPredicatePushdownPrunnedColumns() { String tableName = "test.predicate_pushdown_prunned_columns"; onBigQuery("DROP TABLE IF EXISTS " + tableName); onBigQuery("CREATE TABLE " + tableName + " (a INT64, b INT64, c INT64)"); onBigQuery("INSERT INTO " + tableName + " VALUES (1,2,3)"); assertQuery( "SELECT 1 FROM " + tableName + " WHERE " + " ((NULL IS NULL) OR a = 100) AND " + " b = 2", "VALUES (1)"); } @Test(description = "regression test for https://github.com/trinodb/trino/issues/5635") public void testCountAggregationView() { String tableName = "test.count_aggregation_table"; String viewName = "test.count_aggregation_view"; onBigQuery("DROP TABLE IF EXISTS " + tableName); onBigQuery("DROP VIEW IF EXISTS " + viewName); onBigQuery("CREATE TABLE " + tableName + " (a INT64, b INT64, c INT64)"); onBigQuery("INSERT INTO " + tableName + " VALUES (1, 2, 3), (4, 5, 6)"); onBigQuery("CREATE VIEW " + viewName + " AS SELECT * FROM " + tableName); assertQuery( "SELECT count(*) FROM " + viewName, "VALUES (2)"); assertQuery( "SELECT count(*) FROM " + viewName + " WHERE a = 1", "VALUES (1)"); assertQuery( "SELECT count(a) FROM " + viewName + " WHERE b = 2", "VALUES (1)"); } /** * regression test for https://github.com/trinodb/trino/issues/6696 */ @Test public void testRepeatCountAggregationView() { String viewName = "test.repeat_count_aggregation_view_" + randomTableSuffix(); onBigQuery("DROP VIEW IF EXISTS " + viewName); onBigQuery("CREATE VIEW " + viewName + " AS SELECT 1 AS col1"); assertQuery("SELECT count(*) FROM " + viewName, "VALUES (1)"); assertQuery("SELECT count(*) FROM " + viewName, "VALUES (1)"); onBigQuery("DROP VIEW " + viewName); } @Test public void testViewDefinitionSystemTable() { String schemaName = "test"; String tableName = "views_system_table_base_" + randomTableSuffix(); String viewName = "views_system_table_view_" + randomTableSuffix(); onBigQuery(format("DROP TABLE IF EXISTS %s.%s", schemaName, tableName)); onBigQuery(format("DROP VIEW IF EXISTS %s.%s", schemaName, viewName)); onBigQuery(format("CREATE TABLE %s.%s (a INT64, b INT64, c INT64)", schemaName, tableName)); onBigQuery(format("CREATE VIEW %s.%s AS SELECT * FROM %s.%s", schemaName, viewName, schemaName, tableName)); assertEquals( computeScalar(format("SELECT * FROM %s.\"%s$view_definition\"", schemaName, viewName)), format("SELECT * FROM %s.%s", schemaName, tableName)); assertQueryFails( format("SELECT * FROM %s.\"%s$view_definition\"", schemaName, tableName), format("Table '%s.%s\\$view_definition' not found", schemaName, tableName)); onBigQuery(format("DROP TABLE %s.%s", schemaName, tableName)); onBigQuery(format("DROP VIEW %s.%s", schemaName, viewName)); } @Override public void testShowCreateTable() { assertThat((String) computeActual("SHOW CREATE TABLE orders").getOnlyValue()) .isEqualTo("CREATE TABLE bigquery.tpch.orders (\n" + " orderkey bigint NOT NULL,\n" + " custkey bigint NOT NULL,\n" + " orderstatus varchar NOT NULL,\n" + " totalprice double NOT NULL,\n" + " orderdate date NOT NULL,\n" + " orderpriority varchar NOT NULL,\n" + " clerk varchar NOT NULL,\n" + " shippriority bigint NOT NULL,\n" + " comment varchar NOT NULL\n" + ")"); } private void onBigQuery(String sql) { bigQuerySqlExecutor.execute(sql); } }
apache-2.0
aws/aws-sdk-java
aws-java-sdk-pinpoint/src/main/java/com/amazonaws/services/pinpoint/model/transform/DeleteInAppTemplateRequestMarshaller.java
2382
/* * Copyright 2017-2022 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). You may not use this file except in compliance with * the License. A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file 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.amazonaws.services.pinpoint.model.transform; import javax.annotation.Generated; import com.amazonaws.SdkClientException; import com.amazonaws.services.pinpoint.model.*; import com.amazonaws.protocol.*; import com.amazonaws.annotation.SdkInternalApi; /** * DeleteInAppTemplateRequestMarshaller */ @Generated("com.amazonaws:aws-java-sdk-code-generator") @SdkInternalApi public class DeleteInAppTemplateRequestMarshaller { private static final MarshallingInfo<String> TEMPLATENAME_BINDING = MarshallingInfo.builder(MarshallingType.STRING).marshallLocation(MarshallLocation.PATH) .marshallLocationName("template-name").build(); private static final MarshallingInfo<String> VERSION_BINDING = MarshallingInfo.builder(MarshallingType.STRING) .marshallLocation(MarshallLocation.QUERY_PARAM).marshallLocationName("version").build(); private static final DeleteInAppTemplateRequestMarshaller instance = new DeleteInAppTemplateRequestMarshaller(); public static DeleteInAppTemplateRequestMarshaller getInstance() { return instance; } /** * Marshall the given parameter object. */ public void marshall(DeleteInAppTemplateRequest deleteInAppTemplateRequest, ProtocolMarshaller protocolMarshaller) { if (deleteInAppTemplateRequest == null) { throw new SdkClientException("Invalid argument passed to marshall(...)"); } try { protocolMarshaller.marshall(deleteInAppTemplateRequest.getTemplateName(), TEMPLATENAME_BINDING); protocolMarshaller.marshall(deleteInAppTemplateRequest.getVersion(), VERSION_BINDING); } catch (Exception e) { throw new SdkClientException("Unable to marshall request to JSON: " + e.getMessage(), e); } } }
apache-2.0
misterflud/aoleynikov
chapter_005/set/src/test/java/ru/job4j/UsualSetTest.java
705
package ru.job4j; import org.junit.Test; import java.util.Iterator; /** * Created by Anton on 09.05.2017. */ public class UsualSetTest { /** * Test. */ @Test public void whenThen() { UsualSet<Integer> usualSet = new UsualSet<>(); usualSet.add(1); usualSet.add(2); usualSet.add(3); usualSet.add(4); usualSet.add(5); usualSet.add(6); usualSet.add(7); usualSet.add(8); usualSet.add(9); usualSet.add(10); usualSet.add(11); Iterator<Integer> iterator = usualSet.iterator(); while (iterator.hasNext()) { System.out.println(iterator.next()); } } }
apache-2.0
hanhlh/hadoop-0.20.2_FatBTree
src/core/org/apache/hadoop/fs/FileUtil.java
25277
/** * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.fs; import java.io.*; import java.util.Enumeration; import java.util.zip.ZipEntry; import java.util.zip.ZipFile; import org.apache.hadoop.conf.Configuration; import org.apache.hadoop.hdfs.server.namenodeFBT.msg.MessageException; import org.apache.hadoop.hdfs.server.namenodeFBT.service.ServiceException; import org.apache.hadoop.hdfs.server.namenodeFBT.utils.StringUtility; import org.apache.hadoop.io.IOUtils; import org.apache.hadoop.util.StringUtils; import org.apache.hadoop.util.Shell; import org.apache.hadoop.util.Shell.ShellCommandExecutor; /** * A collection of file-processing util methods */ public class FileUtil { /** * convert an array of FileStatus to an array of Path * * @param stats * an array of FileStatus objects * @return an array of paths corresponding to the input */ public static Path[] stat2Paths(FileStatus[] stats) { if (stats == null) return null; Path[] ret = new Path[stats.length]; for (int i = 0; i < stats.length; ++i) { ret[i] = stats[i].getPath(); } return ret; } /** * convert an array of FileStatus to an array of Path. * If stats if null, return path * @param stats * an array of FileStatus objects * @param path * default path to return in stats is null * @return an array of paths corresponding to the input */ public static Path[] stat2Paths(FileStatus[] stats, Path path) { if (stats == null) return new Path[]{path}; else return stat2Paths(stats); } /** * Delete a directory and all its contents. If * we return false, the directory may be partially-deleted. */ public static boolean fullyDelete(File dir) throws IOException { File contents[] = dir.listFiles(); if (contents != null) { for (int i = 0; i < contents.length; i++) { if (contents[i].isFile()) { if (!contents[i].delete()) { return false; } } else { //try deleting the directory // this might be a symlink boolean b = false; b = contents[i].delete(); if (b){ //this was indeed a symlink or an empty directory continue; } // if not an empty directory or symlink let // fullydelete handle it. if (!fullyDelete(contents[i])) { return false; } } } } return dir.delete(); } /** * Recursively delete a directory. * * @param fs {@link FileSystem} on which the path is present * @param dir directory to recursively delete * @throws IOException * @throws MessageException * @deprecated Use {@link FileSystem#delete(Path, boolean)} */ @Deprecated public static void fullyDelete(FileSystem fs, Path dir) throws IOException, MessageException { fs.delete(dir, true); } // // If the destination is a subdirectory of the source, then // generate exception // private static void checkDependencies(FileSystem srcFS, Path src, FileSystem dstFS, Path dst) throws IOException { if (srcFS == dstFS) { String srcq = src.makeQualified(srcFS).toString() + Path.SEPARATOR; String dstq = dst.makeQualified(dstFS).toString() + Path.SEPARATOR; if (dstq.startsWith(srcq)) { if (srcq.length() == dstq.length()) { throw new IOException("Cannot copy " + src + " to itself."); } else { throw new IOException("Cannot copy " + src + " to its subdirectory " + dst); } } } } /** Copy files between FileSystems. * @throws ServiceException * @throws MessageException */ public static boolean copy(FileSystem srcFS, Path src, FileSystem dstFS, Path dst, boolean deleteSource, Configuration conf) throws IOException, MessageException, ServiceException { return copy(srcFS, src, dstFS, dst, deleteSource, true, conf); } public static boolean copy(FileSystem srcFS, Path[] srcs, FileSystem dstFS, Path dst, boolean deleteSource, boolean overwrite, Configuration conf) throws IOException, MessageException, ServiceException { boolean gotException = false; boolean returnVal = true; StringBuffer exceptions = new StringBuffer(); if (srcs.length == 1) return copy(srcFS, srcs[0], dstFS, dst, deleteSource, overwrite, conf); // Check if dest is directory if (!dstFS.exists(dst)) { throw new IOException("`" + dst +"': specified destination directory " + "doest not exist"); } else { FileStatus sdst = dstFS.getFileStatus(dst); if (!sdst.isDir()) throw new IOException("copying multiple files, but last argument `" + dst + "' is not a directory"); } for (Path src : srcs) { try { if (!copy(srcFS, src, dstFS, dst, deleteSource, overwrite, conf)) returnVal = false; } catch (IOException e) { gotException = true; exceptions.append(e.getMessage()); exceptions.append("\n"); } } if (gotException) { throw new IOException(exceptions.toString()); } return returnVal; } /** Copy files between FileSystems. * @throws ServiceException * @throws MessageException */ public static boolean copy(FileSystem srcFS, Path src, FileSystem dstFS, Path dst, boolean deleteSource, boolean overwrite, Configuration conf) throws IOException, MessageException, ServiceException { StringUtility.debugSpace("FileUtil.copy line 197"); dst = checkDest(src.getName(), dstFS, dst, overwrite); if (srcFS.getFileStatus(src).isDir()) { checkDependencies(srcFS, src, dstFS, dst); if (!dstFS.mkdirs(dst)) { return false; } FileStatus contents[] = srcFS.listStatus(src); for (int i = 0; i < contents.length; i++) { copy(srcFS, contents[i].getPath(), dstFS, new Path(dst, contents[i].getPath().getName()), deleteSource, overwrite, conf); } } else if (srcFS.isFile(src)) { InputStream in=null; OutputStream out = null; try { in = srcFS.open(src); out = dstFS.create(dst, overwrite); IOUtils.copyBytes(in, out, conf, true); } catch (IOException e) { IOUtils.closeStream(out); IOUtils.closeStream(in); throw e; } } else { throw new IOException(src.toString() + ": No such file or directory"); } if (deleteSource) { return srcFS.delete(src, true); } else { return true; } } /** Copy all files in a directory to one output file (merge). * @throws ServiceException * @throws MessageException */ public static boolean copyMerge(FileSystem srcFS, Path srcDir, FileSystem dstFS, Path dstFile, boolean deleteSource, Configuration conf, String addString) throws IOException, MessageException, ServiceException { dstFile = checkDest(srcDir.getName(), dstFS, dstFile, false); if (!srcFS.getFileStatus(srcDir).isDir()) return false; OutputStream out = dstFS.create(dstFile); try { FileStatus contents[] = srcFS.listStatus(srcDir); for (int i = 0; i < contents.length; i++) { if (!contents[i].isDir()) { InputStream in = srcFS.open(contents[i].getPath()); try { IOUtils.copyBytes(in, out, conf, false); if (addString!=null) out.write(addString.getBytes("UTF-8")); } finally { in.close(); } } } } finally { out.close(); } if (deleteSource) { return srcFS.delete(srcDir, true); } else { return true; } } /** Copy local files to a FileSystem. * @throws ServiceException * @throws MessageException */ public static boolean copy(File src, FileSystem dstFS, Path dst, boolean deleteSource, Configuration conf) throws IOException, MessageException, ServiceException { dst = checkDest(src.getName(), dstFS, dst, false); if (src.isDirectory()) { if (!dstFS.mkdirs(dst)) { return false; } File contents[] = src.listFiles(); for (int i = 0; i < contents.length; i++) { copy(contents[i], dstFS, new Path(dst, contents[i].getName()), deleteSource, conf); } } else if (src.isFile()) { InputStream in = null; OutputStream out =null; try { in = new FileInputStream(src); out = dstFS.create(dst); IOUtils.copyBytes(in, out, conf); } catch (IOException e) { IOUtils.closeStream( out ); IOUtils.closeStream( in ); throw e; } } else { throw new IOException(src.toString() + ": No such file or directory"); } if (deleteSource) { return FileUtil.fullyDelete(src); } else { return true; } } /** Copy FileSystem files to local files. */ public static boolean copy(FileSystem srcFS, Path src, File dst, boolean deleteSource, Configuration conf) throws IOException, MessageException { if (srcFS.getFileStatus(src).isDir()) { if (!dst.mkdirs()) { return false; } FileStatus contents[] = srcFS.listStatus(src); for (int i = 0; i < contents.length; i++) { copy(srcFS, contents[i].getPath(), new File(dst, contents[i].getPath().getName()), deleteSource, conf); } } else if (srcFS.isFile(src)) { InputStream in = srcFS.open(src); IOUtils.copyBytes(in, new FileOutputStream(dst), conf); } else { throw new IOException(src.toString() + ": No such file or directory"); } if (deleteSource) { return srcFS.delete(src, true); } else { return true; } } private static Path checkDest(String srcName, FileSystem dstFS, Path dst, boolean overwrite) throws IOException, MessageException { if (dstFS.exists(dst)) { FileStatus sdst = dstFS.getFileStatus(dst); if (sdst.isDir()) { if (null == srcName) { throw new IOException("Target " + dst + " is a directory"); } return checkDest(null, dstFS, new Path(dst, srcName), overwrite); } else if (!overwrite) { throw new IOException("Target " + dst + " already exists"); } } return dst; } /** * This class is only used on windows to invoke the cygpath command. */ private static class CygPathCommand extends Shell { String[] command; String result; CygPathCommand(String path) throws IOException { command = new String[]{"cygpath", "-u", path}; run(); } String getResult() throws IOException { return result; } protected String[] getExecString() { return command; } protected void parseExecResult(BufferedReader lines) throws IOException { String line = lines.readLine(); if (line == null) { throw new IOException("Can't convert '" + command[2] + " to a cygwin path"); } result = line; } } /** * Convert a os-native filename to a path that works for the shell. * @param filename The filename to convert * @return The unix pathname * @throws IOException on windows, there can be problems with the subprocess */ public static String makeShellPath(String filename) throws IOException { if (Path.WINDOWS) { return new CygPathCommand(filename).getResult(); } else { return filename; } } /** * Convert a os-native filename to a path that works for the shell. * @param file The filename to convert * @return The unix pathname * @throws IOException on windows, there can be problems with the subprocess */ public static String makeShellPath(File file) throws IOException { return makeShellPath(file, false); } /** * Convert a os-native filename to a path that works for the shell. * @param file The filename to convert * @param makeCanonicalPath * Whether to make canonical path for the file passed * @return The unix pathname * @throws IOException on windows, there can be problems with the subprocess */ public static String makeShellPath(File file, boolean makeCanonicalPath) throws IOException { if (makeCanonicalPath) { return makeShellPath(file.getCanonicalPath()); } else { return makeShellPath(file.toString()); } } /** * Takes an input dir and returns the du on that local directory. Very basic * implementation. * * @param dir * The input dir to get the disk space of this local dir * @return The total disk space of the input local directory */ public static long getDU(File dir) { long size = 0; if (!dir.exists()) return 0; if (!dir.isDirectory()) { return dir.length(); } else { size = dir.length(); File[] allFiles = dir.listFiles(); for (int i = 0; i < allFiles.length; i++) { size = size + getDU(allFiles[i]); } return size; } } /** * Given a File input it will unzip the file in a the unzip directory * passed as the second parameter * @param inFile The zip file as input * @param unzipDir The unzip directory where to unzip the zip file. * @throws IOException */ public static void unZip(File inFile, File unzipDir) throws IOException { Enumeration<? extends ZipEntry> entries; ZipFile zipFile = new ZipFile(inFile); try { entries = zipFile.entries(); while (entries.hasMoreElements()) { ZipEntry entry = entries.nextElement(); if (!entry.isDirectory()) { InputStream in = zipFile.getInputStream(entry); try { File file = new File(unzipDir, entry.getName()); if (!file.getParentFile().mkdirs()) { if (!file.getParentFile().isDirectory()) { throw new IOException("Mkdirs failed to create " + file.getParentFile().toString()); } } OutputStream out = new FileOutputStream(file); try { byte[] buffer = new byte[8192]; int i; while ((i = in.read(buffer)) != -1) { out.write(buffer, 0, i); } } finally { out.close(); } } finally { in.close(); } } } } finally { zipFile.close(); } } /** * Given a Tar File as input it will untar the file in a the untar directory * passed as the second parameter * * This utility will untar ".tar" files and ".tar.gz","tgz" files. * * @param inFile The tar file as input. * @param untarDir The untar directory where to untar the tar file. * @throws IOException */ public static void unTar(File inFile, File untarDir) throws IOException { if (!untarDir.mkdirs()) { if (!untarDir.isDirectory()) { throw new IOException("Mkdirs failed to create " + untarDir); } } StringBuffer untarCommand = new StringBuffer(); boolean gzipped = inFile.toString().endsWith("gz"); if (gzipped) { untarCommand.append(" gzip -dc '"); untarCommand.append(FileUtil.makeShellPath(inFile)); untarCommand.append("' | ("); } untarCommand.append("cd '"); untarCommand.append(FileUtil.makeShellPath(untarDir)); untarCommand.append("' ; "); untarCommand.append("tar -xf "); if (gzipped) { untarCommand.append(" -)"); } else { untarCommand.append(FileUtil.makeShellPath(inFile)); } String[] shellCmd = { "bash", "-c", untarCommand.toString() }; ShellCommandExecutor shexec = new ShellCommandExecutor(shellCmd); shexec.execute(); int exitcode = shexec.getExitCode(); if (exitcode != 0) { throw new IOException("Error untarring file " + inFile + ". Tar process exited with exit code " + exitcode); } } /** * Class for creating hardlinks. * Supports Unix, Cygwin, WindXP. * */ public static class HardLink { enum OSType { OS_TYPE_UNIX, OS_TYPE_WINXP, OS_TYPE_SOLARIS, OS_TYPE_MAC; } private static String[] hardLinkCommand; private static String[] getLinkCountCommand; private static OSType osType; static { osType = getOSType(); switch(osType) { case OS_TYPE_WINXP: hardLinkCommand = new String[] {"fsutil","hardlink","create", null, null}; getLinkCountCommand = new String[] {"stat","-c%h"}; break; case OS_TYPE_SOLARIS: hardLinkCommand = new String[] {"ln", null, null}; getLinkCountCommand = new String[] {"ls","-l"}; break; case OS_TYPE_MAC: hardLinkCommand = new String[] {"ln", null, null}; getLinkCountCommand = new String[] {"stat","-f%l"}; break; case OS_TYPE_UNIX: default: hardLinkCommand = new String[] {"ln", null, null}; getLinkCountCommand = new String[] {"stat","-c%h"}; } } static private OSType getOSType() { String osName = System.getProperty("os.name"); if (osName.indexOf("Windows") >= 0 && (osName.indexOf("XP") >= 0 || osName.indexOf("2003") >= 0 || osName.indexOf("Vista") >= 0)) return OSType.OS_TYPE_WINXP; else if (osName.indexOf("SunOS") >= 0) return OSType.OS_TYPE_SOLARIS; else if (osName.indexOf("Mac") >= 0) return OSType.OS_TYPE_MAC; else return OSType.OS_TYPE_UNIX; } /** * Creates a hardlink */ public static void createHardLink(File target, File linkName) throws IOException { int len = hardLinkCommand.length; if (osType == OSType.OS_TYPE_WINXP) { hardLinkCommand[len-1] = target.getCanonicalPath(); hardLinkCommand[len-2] = linkName.getCanonicalPath(); } else { hardLinkCommand[len-2] = makeShellPath(target, true); hardLinkCommand[len-1] = makeShellPath(linkName, true); } // execute shell command Process process = Runtime.getRuntime().exec(hardLinkCommand); try { if (process.waitFor() != 0) { String errMsg = new BufferedReader(new InputStreamReader( process.getInputStream())).readLine(); if (errMsg == null) errMsg = ""; String inpMsg = new BufferedReader(new InputStreamReader( process.getErrorStream())).readLine(); if (inpMsg == null) inpMsg = ""; throw new IOException(errMsg + inpMsg); } } catch (InterruptedException e) { throw new IOException(StringUtils.stringifyException(e)); } finally { process.destroy(); } } /** * Retrieves the number of links to the specified file. */ public static int getLinkCount(File fileName) throws IOException { int len = getLinkCountCommand.length; String[] cmd = new String[len + 1]; for (int i = 0; i < len; i++) { cmd[i] = getLinkCountCommand[i]; } cmd[len] = fileName.toString(); String inpMsg = ""; String errMsg = ""; int exitValue = -1; BufferedReader in = null; BufferedReader err = null; // execute shell command Process process = Runtime.getRuntime().exec(cmd); try { exitValue = process.waitFor(); in = new BufferedReader(new InputStreamReader( process.getInputStream())); inpMsg = in.readLine(); if (inpMsg == null) inpMsg = ""; err = new BufferedReader(new InputStreamReader( process.getErrorStream())); errMsg = err.readLine(); if (errMsg == null) errMsg = ""; if (exitValue != 0) { throw new IOException(inpMsg + errMsg); } if (getOSType() == OSType.OS_TYPE_SOLARIS) { String[] result = inpMsg.split("\\s+"); return Integer.parseInt(result[1]); } else { return Integer.parseInt(inpMsg); } } catch (NumberFormatException e) { throw new IOException(StringUtils.stringifyException(e) + inpMsg + errMsg + " on file:" + fileName); } catch (InterruptedException e) { throw new IOException(StringUtils.stringifyException(e) + inpMsg + errMsg + " on file:" + fileName); } finally { process.destroy(); if (in != null) in.close(); if (err != null) err.close(); } } } /** * Create a soft link between a src and destination * only on a local disk. HDFS does not support this * @param target the target for symlink * @param linkname the symlink * @return value returned by the command */ public static int symLink(String target, String linkname) throws IOException{ String cmd = "ln -s " + target + " " + linkname; Process p = Runtime.getRuntime().exec(cmd, null); int returnVal = -1; try{ returnVal = p.waitFor(); } catch(InterruptedException e){ //do nothing as of yet } return returnVal; } /** * Change the permissions on a filename. * @param filename the name of the file to change * @param perm the permission string * @return the exit code from the command * @throws IOException * @throws InterruptedException */ public static int chmod(String filename, String perm ) throws IOException, InterruptedException { String cmd = "chmod " + perm + " " + filename; Process p = Runtime.getRuntime().exec(cmd, null); return p.waitFor(); } /** * Create a tmp file for a base file. * @param basefile the base file of the tmp * @param prefix file name prefix of tmp * @param isDeleteOnExit if true, the tmp will be deleted when the VM exits * @return a newly created tmp file * @exception IOException If a tmp file cannot created * @see java.io.File#createTempFile(String, String, File) * @see java.io.File#deleteOnExit() */ public static final File createLocalTempFile(final File basefile, final String prefix, final boolean isDeleteOnExit) throws IOException { File tmp = File.createTempFile(prefix + basefile.getName(), "", basefile.getParentFile()); if (isDeleteOnExit) { tmp.deleteOnExit(); } return tmp; } /** * Move the src file to the name specified by target. * @param src the source file * @param target the target file * @exception IOException If this operation fails */ public static void replaceFile(File src, File target) throws IOException { /* renameTo() has two limitations on Windows platform. * src.renameTo(target) fails if * 1) If target already exists OR * 2) If target is already open for reading/writing. */ if (!src.renameTo(target)) { int retries = 5; while (target.exists() && !target.delete() && retries-- >= 0) { try { Thread.sleep(1000); } catch (InterruptedException e) { throw new IOException("replaceFile interrupted."); } } if (!src.renameTo(target)) { throw new IOException("Unable to rename " + src + " to " + target); } } } }
apache-2.0
mmmsplay10/QuizUpWinner
quizup/o/ÔÆÇ-1.java
2417
package o; import android.app.Activity; import android.content.res.TypedArray; import android.widget.RelativeLayout; import android.widget.TextView; import com.quizup.core.activities.ProfileActivity; import com.quizup.core.widgets.topicButton.IconAndTextButton; import com.quizup.lib.widgets.textViews.GothamTextViewTranslated; public class ﮂ extends ン { private final IconAndTextButton ˊ; private final IconAndTextButton ˋ; private ﮂ.if ˎ; public ﮂ(ProfileActivity paramProfileActivity, ﮂ.if paramif, int paramInt) { super(paramProfileActivity, 2130903133, 2131493230); TypedArray localTypedArray = paramProfileActivity.obtainStyledAttributes(2131493230, new int[] { 2130772044, 2130772045, 2130772046, 2130772048, 2130772049, 2130772057, 2130772062 }); localTypedArray.getColor(0, -16777216); String str1 = localTypedArray.getString(1); int i = localTypedArray.getResourceId(2, 0); String str2 = localTypedArray.getString(3); int j = localTypedArray.getResourceId(4, 0); float f = localTypedArray.getDimension(5, 0.0F); String str3 = localTypedArray.getString(6); localTypedArray.recycle(); this.ˋ = ((IconAndTextButton)this.ͺ.findViewById(2131296735)); ˊ(paramProfileActivity, this.ˋ, str1, i, f); this.ˊ = ((IconAndTextButton)this.ͺ.findViewById(2131296736)); ˊ(paramProfileActivity, this.ˊ, str2, j, f); ((GothamTextViewTranslated)this.ͺ.findViewById(2131296633)).setText(str3); ч.ˊ(); this.ˎ = paramif; if (paramif != null) { this.ˋ.setOnClickListener(new ﮂ.1(this, paramif)); this.ˊ.setOnClickListener(new ﮂ.2(this, paramif)); } } private static void ˊ(ProfileActivity paramProfileActivity, IconAndTextButton paramIconAndTextButton, String paramString, int paramInt, float paramFloat) { if (paramInt != 0) paramIconAndTextButton.ˊ(paramString, ʌ.ˊ(paramProfileActivity, paramInt, ʌ.ˊ(-16777216)), -16777216); else paramIconAndTextButton.ˊ(paramString, null, -16777216); ((TextView)paramIconAndTextButton.findViewById(2131296825)).setTextSize(0, paramFloat); } public final void ˊ() { if (this.ˎ != null) this.ˎ.onDialogClosed(); } public final void ˋ() { } } /* Location: /Users/vikas/Documents/Mhacks_Real_app/classes-dex2jar.jar * Qualified Name: o.ÔÆÇ * JD-Core Version: 0.6.2 */
apache-2.0
xnull/insight
java/src/main/java/bynull/functional/stream/StreamTips.java
1370
package bynull.functional.stream; import bynull.functional.Common.Tuple2; import java.util.ArrayList; import java.util.List; import java.util.concurrent.atomic.AtomicInteger; import java.util.stream.IntStream; import java.util.stream.Stream; /** * Useful tips and tricks for using streams: how to do some actions using streams in java 8 * Created by bynull on 04.07.16. */ public class StreamTips { /** * How to go through a collection with index using streams */ public Stream<Tuple2<Integer, String>> withIndex(List<String> list) { return Stream.of(list).flatMap(collection -> IntStream.range(0, collection.size()) .boxed() .map(index -> Tuple2.of(index, collection.get(index))) ); } public Stream<Tuple2<Integer, String>> withIndex(Stream<String> input) { AtomicInteger index = new AtomicInteger(); return input.sequential().map(value -> Tuple2.of(index.getAndIncrement(), value)); } public static <T> Stream<T> makeCollectionVisibilityStreamPrivate(List<T> list) { return Stream.of(new ArrayList<>(list)).flatMap(collection -> { System.out.println("Now we are enable to get access or change the collection without affecting original collection"); return collection.stream(); }); } }
apache-2.0
hazendaz/assertj-core
src/main/java/org/assertj/core/error/ShouldHaveSameHourAs.java
1607
/* * 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. * * Copyright 2012-2021 the original author or authors. */ package org.assertj.core.error; import java.time.ZonedDateTime; import java.time.temporal.Temporal; /** * Creates an error message indicating that an assertion that verifies that two {@link ZonedDateTime} have same year, * month, day and hour fields failed. * * @author Joel Costigliola */ public class ShouldHaveSameHourAs extends BasicErrorMessageFactory { /** * Creates a new <code>{@link ShouldHaveSameHourAs}</code>. * * @param actual the actual value in the failed assertion. * @param other the value used in the failed assertion to compare the actual value to. * @return the created {@code ErrorMessageFactory}. */ public static ErrorMessageFactory shouldHaveSameHourAs(Temporal actual, Temporal other) { return new ShouldHaveSameHourAs(actual, other); } private ShouldHaveSameHourAs(Temporal actual, Temporal other) { super("%nExpecting actual:%n %s%nto have same hour as:%n %s%nbut had not.", actual, other); } }
apache-2.0
zhantss/LuceneTool
src/main/java/pro/zhantss/lucene/data/dbimport/MergeConfig.java
643
package pro.zhantss.lucene.data.dbimport; import java.util.List; public class MergeConfig { private AnalyzerType analyzerType; private DirectoryConfig target; private List<DirectoryConfig> dcs; public DirectoryConfig getTarget() { return target; } public void setTarget(DirectoryConfig target) { this.target = target; } public List<DirectoryConfig> getDcs() { return dcs; } public void setDcs(List<DirectoryConfig> dcs) { this.dcs = dcs; } public AnalyzerType getAnalyzerType() { return analyzerType; } public void setAnalyzerType(AnalyzerType analyzerType) { this.analyzerType = analyzerType; } }
apache-2.0
gawkermedia/googleads-java-lib
modules/dfp_axis/src/main/java/com/google/api/ads/dfp/axis/v201511/AdRuleDateError.java
4129
/** * AdRuleDateError.java * * This file was auto-generated from WSDL * by the Apache Axis 1.4 Mar 02, 2009 (07:08:06 PST) WSDL2Java emitter. */ package com.google.api.ads.dfp.axis.v201511; /** * Lists all errors associated with ad rule start and end dates. */ public class AdRuleDateError extends com.google.api.ads.dfp.axis.v201511.ApiError implements java.io.Serializable { private com.google.api.ads.dfp.axis.v201511.AdRuleDateErrorReason reason; public AdRuleDateError() { } public AdRuleDateError( java.lang.String fieldPath, java.lang.String trigger, java.lang.String errorString, com.google.api.ads.dfp.axis.v201511.AdRuleDateErrorReason reason) { super( fieldPath, trigger, errorString); this.reason = reason; } /** * Gets the reason value for this AdRuleDateError. * * @return reason */ public com.google.api.ads.dfp.axis.v201511.AdRuleDateErrorReason getReason() { return reason; } /** * Sets the reason value for this AdRuleDateError. * * @param reason */ public void setReason(com.google.api.ads.dfp.axis.v201511.AdRuleDateErrorReason reason) { this.reason = reason; } private java.lang.Object __equalsCalc = null; public synchronized boolean equals(java.lang.Object obj) { if (!(obj instanceof AdRuleDateError)) return false; AdRuleDateError other = (AdRuleDateError) obj; if (obj == null) return false; if (this == obj) return true; if (__equalsCalc != null) { return (__equalsCalc == obj); } __equalsCalc = obj; boolean _equals; _equals = super.equals(obj) && ((this.reason==null && other.getReason()==null) || (this.reason!=null && this.reason.equals(other.getReason()))); __equalsCalc = null; return _equals; } private boolean __hashCodeCalc = false; public synchronized int hashCode() { if (__hashCodeCalc) { return 0; } __hashCodeCalc = true; int _hashCode = super.hashCode(); if (getReason() != null) { _hashCode += getReason().hashCode(); } __hashCodeCalc = false; return _hashCode; } // Type metadata private static org.apache.axis.description.TypeDesc typeDesc = new org.apache.axis.description.TypeDesc(AdRuleDateError.class, true); static { typeDesc.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201511", "AdRuleDateError")); org.apache.axis.description.ElementDesc elemField = new org.apache.axis.description.ElementDesc(); elemField.setFieldName("reason"); elemField.setXmlName(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201511", "reason")); elemField.setXmlType(new javax.xml.namespace.QName("https://www.google.com/apis/ads/publisher/v201511", "AdRuleDateError.Reason")); elemField.setMinOccurs(0); elemField.setNillable(false); typeDesc.addFieldDesc(elemField); } /** * Return type metadata object */ public static org.apache.axis.description.TypeDesc getTypeDesc() { return typeDesc; } /** * Get Custom Serializer */ public static org.apache.axis.encoding.Serializer getSerializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanSerializer( _javaType, _xmlType, typeDesc); } /** * Get Custom Deserializer */ public static org.apache.axis.encoding.Deserializer getDeserializer( java.lang.String mechType, java.lang.Class _javaType, javax.xml.namespace.QName _xmlType) { return new org.apache.axis.encoding.ser.BeanDeserializer( _javaType, _xmlType, typeDesc); } }
apache-2.0
SSEHUB/spassMeter
Instrumentation.ex/src/test/IndirectTest.java
4853
package test; import test.testing.MonitoringGroupValue; import test.testing.TestEnvironment; import test.threadedTest.Data; import de.uni_hildesheim.sse.codeEraser.annotations.Variability; import de.uni_hildesheim.sse.monitoring.runtime.annotations.EndSystem; import de.uni_hildesheim.sse.monitoring.runtime.annotations.Monitor; import de.uni_hildesheim.sse.monitoring.runtime.annotations.StartSystem; /** * A specific test for direct and indirect monitoring groups in the * same thread. * * @author Holger Eichelberger * @since 1.00 * @version 1.00 */ @Variability(id = AnnotationId.VAR_TESTING) @Monitor(id = AnnotationId.ID_INDIRECT) public class IndirectTest { /** * Defines the maximum allocation count. */ private static final int MAX_ALLOC = 1000; /** * Stores the size of a data object. */ private static long dataSize = -1; /** * Stores the allocated test object. */ private static IndirectTest indirectTest; /** * Stores the allocated sub test object. */ private static SubTest subTest; /** * Stores the data. */ private Data data; /** * Defines the indirect/overlapping resource usage. * * @author Holger Eichelberger * @since 1.00 * @version 1.00 */ @Monitor(id = AnnotationId.ID_INDIRECT_SUB) private class SubTest { /** * Stores the data. */ @SuppressWarnings("unused") private Data data; /** * Executes resource allocation. * * @since 1.00 */ public void execute() { // put another instance of myself onto the internal // instrumenter stack IndirectTest.this.allocateIndirect(this); } /** * Called to allocate the data. * * @since 1.00 */ public void allocate() { for (int i = 0; i < MAX_ALLOC; i++) { data = new Data(); if (i % 50 == 0) { System.gc(); } } } } /** * Prevents this class from being instantiated from outside. * * @since 1.00 */ private IndirectTest() { } /** * Allocates a sub object indirectly in order to cause this element to * occur twice on the internal stack. * * @param test the object to call the allocation method for * * @since 1.00 */ private void allocateIndirect(SubTest test) { test.allocate(); } /** * Executes resource allocation. * * @since 1.00 */ public void execute() { for (int i = 0; i < MAX_ALLOC; i++) { data = new Data(); if (-1 == dataSize) { dataSize = TestEnvironment.getObjectSize(data); } if (i % 50 == 0) { System.gc(); } } } /** * Executes the tests - main is not time-instrumented. * * @since 1.00 */ private static void test() { indirectTest = new IndirectTest(); indirectTest.execute(); subTest = indirectTest.new SubTest(); subTest.execute(); } /** * Starts the test. * * @param args ignored * * @since 1.00 */ @StartSystem @EndSystem(invoke = "asserts") public static void main(String[] args) { dataSize = TestEnvironment.getObjectSize(new Data()); test(); } /** * The automated tests using assert statements. This method is called * by SPASS-meter at end of monitoring upon the <code>EndSystem</code> * annotation. * * @since 1.00 */ public static void asserts() { long onePartDataSize = dataSize * MAX_ALLOC; long totalSize = 2 * onePartDataSize; TestEnvironment.assertEquals(AnnotationId.ID_INDIRECT_SUB, MonitoringGroupValue.ALLOCATED_MEMORY, onePartDataSize); if (TestEnvironment.isIndirectTest()) { // + additionalSize does not work with XML TestEnvironment.assertGreater(AnnotationId.ID_INDIRECT, MonitoringGroupValue.ALLOCATED_MEMORY, totalSize); } else { TestEnvironment.assertGreater(AnnotationId.ID_INDIRECT, MonitoringGroupValue.ALLOCATED_MEMORY, onePartDataSize); } TestEnvironment.assertGreater(TestEnvironment.getProgramId(), MonitoringGroupValue.ALLOCATED_MEMORY, totalSize); TestEnvironment.success(AnnotationId.ID_INDIRECT); } }
apache-2.0
Ardesco/selenium
java/server/src/org/openqa/selenium/grid/config/TomlConfig.java
3230
// Licensed to the Software Freedom Conservancy (SFC) under one // or more contributor license agreements. See the NOTICE file // distributed with this work for additional information // regarding copyright ownership. The SFC 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.openqa.selenium.grid.config; import com.google.common.collect.ImmutableList; import com.google.common.collect.ImmutableSortedSet; import org.openqa.selenium.internal.Require; import io.ous.jtoml.JToml; import io.ous.jtoml.Toml; import io.ous.jtoml.TomlTable; import java.io.IOException; import java.io.Reader; import java.nio.file.Files; import java.nio.file.Path; import java.util.Collection; import java.util.List; import java.util.Optional; import java.util.Set; public class TomlConfig implements Config { private final Toml toml; public TomlConfig(Reader reader) { try { toml = JToml.parse(reader); } catch (IOException e) { throw new ConfigException("Unable to read TOML.", e); } } public static Config from(Path path) { Require.nonNull("Path to read", path); try (Reader reader = Files.newBufferedReader(path)) { return new TomlConfig(reader); } catch (IOException e) { throw new ConfigException(String.format("Unable to parse: %s", path), e); } } @Override public Optional<List<String>> getAll(String section, String option) { Require.nonNull("Section to read", section); Require.nonNull("Option to read", option); if (!toml.containsKey(section)) { return Optional.empty(); } Object raw = toml.get(section); if (!(raw instanceof TomlTable)) { throw new ConfigException(String.format("Section %s is not a section! %s", section, raw)); } TomlTable table = toml.getTomlTable(section); Object value = table.getOrDefault(option, null); if (value == null) { return Optional.empty(); } if (value instanceof Collection) { ImmutableList<String> values = ((Collection<?>) value).stream() .filter(item -> (!(item instanceof Collection))) .map(String::valueOf) .collect(ImmutableList.toImmutableList()); return Optional.of(values); } return Optional.of(ImmutableList.of(String.valueOf(value))); } @Override public Set<String> getSectionNames() { return ImmutableSortedSet.copyOf(toml.keySet()); } @Override public Set<String> getOptions(String section) { Require.nonNull("Section name to get options for", section); Object raw = toml.get(section); if (!(raw instanceof TomlTable)) { return ImmutableSortedSet.of(); } return ImmutableSortedSet.copyOf(((TomlTable) raw).keySet()); } }
apache-2.0
dflemstr/docker-java
src/main/java/com/github/dockerjava/client/command/SearchImagesCmd.java
1594
package com.github.dockerjava.client.command; import java.util.List; import javax.ws.rs.ClientErrorException; import javax.ws.rs.core.GenericType; import javax.ws.rs.core.MediaType; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import com.github.dockerjava.client.DockerException; import com.github.dockerjava.client.model.SearchItem; import com.google.common.base.Preconditions; import javax.ws.rs.client.WebTarget; /** * * * */ public class SearchImagesCmd extends AbstrDockerCmd<SearchImagesCmd, List<SearchItem>> { private static final Logger LOGGER = LoggerFactory.getLogger(SearchImagesCmd.class); private String term; public SearchImagesCmd(String term) { withTerm(term); } public String getTerm() { return term; } public SearchImagesCmd withTerm(String term) { Preconditions.checkNotNull(term, "term was not specified"); this.term = term; return this; } @Override public String toString() { return new StringBuilder("search ") .append(term) .toString(); } protected List<SearchItem> impl() { WebTarget webResource = baseResource.path("/images/search").queryParam("term", term); try { LOGGER.trace("GET: {}", webResource); return webResource.request().accept(MediaType.APPLICATION_JSON).get(new GenericType<List<SearchItem>>() { }); } catch (ClientErrorException exception) { if (exception.getResponse().getStatus() == 500) { throw new DockerException("Server error.", exception); } else { throw new DockerException(exception); } } } }
apache-2.0
gustavoanatoly/hbase
hbase-server/src/main/java/org/apache/hadoop/hbase/security/access/AuthResult.java
9218
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ package org.apache.hadoop.hbase.security.access; import java.util.Collection; import java.util.Map; import org.apache.hadoop.hbase.classification.InterfaceAudience; import org.apache.hadoop.hbase.Cell; import org.apache.hadoop.hbase.TableName; import org.apache.hadoop.hbase.security.User; import org.apache.hadoop.hbase.util.Bytes; import org.apache.hadoop.hbase.shaded.com.google.common.base.Joiner; /** * Represents the result of an authorization check for logging and error * reporting. */ @InterfaceAudience.Private public class AuthResult { private boolean allowed; private final String namespace; private final TableName table; private final Permission.Action action; private final String request; private String reason; private final User user; private AuthResult.Params params; // "family" and "qualifier" should only be used if "families" is null. private final byte[] family; private final byte[] qualifier; private final Map<byte[], ? extends Collection<?>> families; public AuthResult(boolean allowed, String request, String reason, User user, Permission.Action action, TableName table, byte[] family, byte[] qualifier) { this.allowed = allowed; this.request = request; this.reason = reason; this.user = user; this.table = table; this.family = family; this.qualifier = qualifier; this.action = action; this.families = null; this.namespace = null; this.params = new Params().setTableName(table).setFamily(family).setQualifier(qualifier); } public AuthResult(boolean allowed, String request, String reason, User user, Permission.Action action, TableName table, Map<byte[], ? extends Collection<?>> families) { this.allowed = allowed; this.request = request; this.reason = reason; this.user = user; this.table = table; this.family = null; this.qualifier = null; this.action = action; this.families = families; this.namespace = null; this.params = new Params().setTableName(table).setFamilies(families); } public AuthResult(boolean allowed, String request, String reason, User user, Permission.Action action, String namespace) { this.allowed = allowed; this.request = request; this.reason = reason; this.user = user; this.namespace = namespace; this.action = action; this.table = null; this.family = null; this.qualifier = null; this.families = null; this.params = new Params().setNamespace(namespace); } public boolean isAllowed() { return allowed; } public User getUser() { return user; } public String getReason() { return reason; } public TableName getTableName() { return table; } public byte[] getFamily() { return family; } public byte[] getQualifier() { return qualifier; } public Permission.Action getAction() { return action; } public String getRequest() { return request; } public Params getParams() { return this.params;} public void setAllowed(boolean allowed) { this.allowed = allowed; } public void setReason(String reason) { this.reason = reason; } private static String toFamiliesString(Map<byte[], ? extends Collection<?>> families, byte[] family, byte[] qual) { StringBuilder sb = new StringBuilder(); if (families != null) { boolean first = true; for (Map.Entry<byte[], ? extends Collection<?>> entry : families.entrySet()) { String familyName = Bytes.toString(entry.getKey()); if (entry.getValue() != null && !entry.getValue().isEmpty()) { for (Object o : entry.getValue()) { String qualifier; if (o instanceof byte[]) { qualifier = Bytes.toString((byte[])o); } else if (o instanceof Cell) { Cell c = (Cell) o; qualifier = Bytes.toString(c.getQualifierArray(), c.getQualifierOffset(), c.getQualifierLength()); } else { // Shouldn't really reach this? qualifier = o.toString(); } if (!first) { sb.append("|"); } first = false; sb.append(familyName).append(":").append(qualifier); } } else { if (!first) { sb.append("|"); } first = false; sb.append(familyName); } } } else if (family != null) { sb.append(Bytes.toString(family)); if (qual != null) { sb.append(":").append(Bytes.toString(qual)); } } return sb.toString(); } public String toContextString() { StringBuilder sb = new StringBuilder(); String familiesString = toFamiliesString(families, family, qualifier); sb.append("(user=") .append(user != null ? user.getName() : "UNKNOWN") .append(", "); sb.append("scope=") .append(namespace != null ? namespace : table == null ? "GLOBAL" : table.getNameWithNamespaceInclAsString()) .append(", "); if(namespace == null && familiesString.length() > 0) { sb.append("family=") .append(familiesString) .append(", "); } String paramsString = params.toString(); if(paramsString.length() > 0) { sb.append("params=[") .append(paramsString) .append("],"); } sb.append("action=") .append(action != null ? action.toString() : "") .append(")"); return sb.toString(); } public String toString() { return "AuthResult" + toContextString(); } public static AuthResult allow(String request, String reason, User user, Permission.Action action, String namespace) { return new AuthResult(true, request, reason, user, action, namespace); } public static AuthResult allow(String request, String reason, User user, Permission.Action action, TableName table, byte[] family, byte[] qualifier) { return new AuthResult(true, request, reason, user, action, table, family, qualifier); } public static AuthResult allow(String request, String reason, User user, Permission.Action action, TableName table, Map<byte[], ? extends Collection<?>> families) { return new AuthResult(true, request, reason, user, action, table, families); } public static AuthResult deny(String request, String reason, User user, Permission.Action action, String namespace) { return new AuthResult(false, request, reason, user, action, namespace); } public static AuthResult deny(String request, String reason, User user, Permission.Action action, TableName table, byte[] family, byte[] qualifier) { return new AuthResult(false, request, reason, user, action, table, family, qualifier); } public static AuthResult deny(String request, String reason, User user, Permission.Action action, TableName table, Map<byte[], ? extends Collection<?>> families) { return new AuthResult(false, request, reason, user, action, table, families); } public String toFamilyString() { return toFamiliesString(families, family, qualifier); } public static class Params { private String namespace = null; private TableName tableName = null; private Map<byte[], ? extends Collection<?>> families = null; byte[] family = null; byte[] qualifier = null; public Params setNamespace(String namespace) { this.namespace = namespace; return this; } public Params setTableName(TableName table) { this.tableName = table; return this; } public Params setFamilies(Map<byte[], ? extends Collection<?>> families) { this.families = families; return this; } public Params setFamily(byte[] family) { this.family = family; return this; } public Params setQualifier(byte[] qualifier) { this.qualifier = qualifier; return this; } public String toString() { String familiesString = toFamiliesString(families, family, qualifier); String[] params = new String[] { namespace != null ? "namespace=" + namespace : null, tableName != null ? "table=" + tableName.getNameWithNamespaceInclAsString() : null, familiesString.length() > 0 ? "family=" + familiesString : null }; return Joiner.on(",").skipNulls().join(params); } } }
apache-2.0