repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15 values |
|---|---|---|---|---|
berkeleydave/graylog2-server | graylog2-plugin-interfaces/src/test/java/org/graylog2/plugin/MessageTest.java | 12940 | /**
* The MIT License
* Copyright (c) 2012 Graylog, Inc.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package org.graylog2.plugin;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import org.graylog2.plugin.streams.Stream;
import org.joda.time.DateTime;
import org.joda.time.DateTimeZone;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.runners.MockitoJUnitRunner;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
@RunWith(MockitoJUnitRunner.class)
public class MessageTest {
private Message message;
private DateTime originalTimestamp;
@Before
public void setUp() {
originalTimestamp = Tools.iso8601();
message = new Message("foo", "bar", originalTimestamp);
}
@Test
public void testAddFieldDoesOnlyAcceptAlphanumericKeys() throws Exception {
Message m = new Message("foo", "bar", Tools.iso8601());
m.addField("some_thing", "bar");
assertEquals("bar", m.getField("some_thing"));
m = new Message("foo", "bar", Tools.iso8601());
m.addField("some-thing", "bar");
assertEquals("bar", m.getField("some-thing"));
m = new Message("foo", "bar", Tools.iso8601());
m.addField("somethin$g", "bar");
assertNull(m.getField("somethin$g"));
m = new Message("foo", "bar", Tools.iso8601());
m.addField("someäthing", "bar");
assertNull(m.getField("someäthing"));
}
@Test
public void testAddFieldTrimsValue() throws Exception {
Message m = new Message("foo", "bar", Tools.iso8601());
m.addField("something", " bar ");
assertEquals("bar", m.getField("something"));
m.addField("something2", " bar");
assertEquals("bar", m.getField("something2"));
m.addField("something3", "bar ");
assertEquals("bar", m.getField("something3"));
}
@Test
public void testAddFieldWorksWithIntegers() throws Exception {
Message m = new Message("foo", "bar", Tools.iso8601());
m.addField("something", 3);
assertEquals(3, m.getField("something"));
}
@Test
public void testAddFields() throws Exception {
final Map<String, Object> map = Maps.newHashMap();
map.put("field1", "Foo");
map.put("field2", 1);
message.addFields(map);
assertEquals("Foo", message.getField("field1"));
assertEquals(1, message.getField("field2"));
}
@Test
public void testAddStringFields() throws Exception {
final Map<String, String> map = Maps.newHashMap();
map.put("field1", "Foo");
map.put("field2", "Bar");
message.addStringFields(map);
assertEquals("Foo", message.getField("field1"));
assertEquals("Bar", message.getField("field2"));
}
@Test
public void testAddLongFields() throws Exception {
final Map<String, Long> map = Maps.newHashMap();
map.put("field1", 10L);
map.put("field2", 230L);
message.addLongFields(map);
assertEquals(10L, message.getField("field1"));
assertEquals(230L, message.getField("field2"));
}
@Test
public void testAddDoubleFields() throws Exception {
final Map<String, Double> map = Maps.newHashMap();
map.put("field1", 10.0d);
map.put("field2", 230.2d);
message.addDoubleFields(map);
assertEquals(10.0d, message.getField("field1"));
assertEquals(230.2d, message.getField("field2"));
}
@Test
public void testRemoveField() throws Exception {
message.addField("foo", "bar");
message.removeField("foo");
assertNull(message.getField("foo"));
}
@Test
public void testRemoveFieldNotDeletingReservedFields() throws Exception {
message.removeField("message");
message.removeField("source");
message.removeField("timestamp");
assertNotNull(message.getField("message"));
assertNotNull(message.getField("source"));
assertNotNull(message.getField("timestamp"));
}
@Test
public void testGetFieldAs() throws Exception {
message.addField("fields", Lists.newArrayList("hello"));
assertEquals(Lists.newArrayList("hello"), message.getFieldAs(List.class, "fields"));
}
@Test(expected = ClassCastException.class)
public void testGetFieldAsWithIncompatibleCast() throws Exception {
message.addField("fields", Lists.newArrayList("hello"));
message.getFieldAs(Map.class, "fields");
}
@Test
public void testSetAndGetStreams() throws Exception {
final Stream stream1 = mock(Stream.class);
final Stream stream2 = mock(Stream.class);
message.setStreams(Lists.newArrayList(stream1, stream2));
assertEquals(Lists.newArrayList(stream1, stream2), message.getStreams());
}
@Test
public void testGetStreamIds() throws Exception {
message.addField("streams", Lists.newArrayList("stream-id"));
assertEquals(Lists.newArrayList("stream-id"), message.getStreamIds());
}
@Test
public void testGetAndSetFilterOut() throws Exception {
assertFalse(message.getFilterOut());
message.setFilterOut(true);
assertTrue(message.getFilterOut());
message.setFilterOut(false);
assertFalse(message.getFilterOut());
}
@Test
public void testGetId() throws Exception {
final Pattern pattern = Pattern.compile("[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}");
assertTrue(pattern.matcher(message.getId()).matches());
}
@Test
public void testGetTimestamp() {
try {
final DateTime timestamp = message.getTimestamp();
assertNotNull(timestamp);
assertEquals(originalTimestamp.getZone(), timestamp.getZone());
} catch (ClassCastException e) {
fail("timestamp wasn't a DateTime " + e.getMessage());
}
}
@Test
public void testTimestampAsDate() {
final DateTime dateTime = new DateTime(2015, 9, 8, 0, 0, DateTimeZone.UTC);
message.addField(Message.FIELD_TIMESTAMP,
dateTime.toDate());
final Map<String, Object> elasticSearchObject = message.toElasticSearchObject();
final Object esTimestampFormatted = elasticSearchObject.get(Message.FIELD_TIMESTAMP);
assertEquals("Setting message timestamp as java.util.Date results in correct format for elasticsearch",
Tools.buildElasticSearchTimeFormat(dateTime), esTimestampFormatted);
}
@Test
public void testGetMessage() throws Exception {
assertEquals("foo", message.getMessage());
}
@Test
public void testGetSource() throws Exception {
assertEquals("bar", message.getSource());
}
@Test
public void testValidKeys() throws Exception {
assertTrue(Message.validKey("foo123"));
assertTrue(Message.validKey("foo-bar123"));
assertTrue(Message.validKey("foo_bar123"));
assertTrue(Message.validKey("foo.bar123"));
assertTrue(Message.validKey("123"));
assertTrue(Message.validKey(""));
assertFalse(Message.validKey("foo bar"));
assertFalse(Message.validKey("foo+bar"));
assertFalse(Message.validKey("foo$bar"));
assertFalse(Message.validKey(" "));
}
@Test
public void testToElasticSearchObject() throws Exception {
message.addField("field1", "wat");
message.addField("field2", "that");
final Map<String, Object> object = message.toElasticSearchObject();
assertEquals("foo", object.get("message"));
assertEquals("bar", object.get("source"));
assertEquals("wat", object.get("field1"));
assertEquals("that", object.get("field2"));
assertEquals(Tools.buildElasticSearchTimeFormat((DateTime) message.getField("timestamp")), object.get("timestamp"));
assertEquals(Collections.EMPTY_LIST, object.get("streams"));
}
@Test
public void testToElasticSearchObjectWithoutDateTimeTimestamp() throws Exception {
message.addField("timestamp", "time!");
final Map<String, Object> object = message.toElasticSearchObject();
assertEquals("time!", object.get("timestamp"));
}
@Test
public void testToElasticSearchObjectWithStreams() throws Exception {
final Stream stream = mock(Stream.class);
when(stream.getId()).thenReturn("stream-id");
message.setStreams(Lists.newArrayList(stream));
final Map<String, Object> object = message.toElasticSearchObject();
assertEquals(Lists.newArrayList("stream-id"), object.get("streams"));
}
@Test
public void testIsComplete() throws Exception {
Message message = new Message("message", "source", Tools.iso8601());
assertTrue(message.isComplete());
message = new Message("message", "", Tools.iso8601());
assertTrue(message.isComplete());
message = new Message("message", null, Tools.iso8601());
assertTrue(message.isComplete());
message = new Message("", "source", Tools.iso8601());
assertFalse(message.isComplete());
message = new Message(null, "source", Tools.iso8601());
assertFalse(message.isComplete());
}
@Test
public void testGetValidationErrorsWithEmptyMessage() throws Exception {
final Message message = new Message("", "source", Tools.iso8601());
assertEquals("message is empty, ", message.getValidationErrors());
}
@Test
public void testGetValidationErrorsWithNullMessage() throws Exception {
final Message message = new Message(null, "source", Tools.iso8601());
assertEquals("message is missing, ", message.getValidationErrors());
}
@Test
public void testGetFields() throws Exception {
final Map<String, Object> fields = message.getFields();
assertEquals(message.getId(), fields.get("_id"));
assertEquals(message.getMessage(), fields.get("message"));
assertEquals(message.getSource(), fields.get("source"));
assertEquals(message.getField("timestamp"), fields.get("timestamp"));
}
@Test(expected = UnsupportedOperationException.class)
public void testGetFieldsReturnsImmutableMap() throws Exception {
final Map<String, Object> fields = message.getFields();
fields.put("foo", "bar");
}
@Test
public void testGetFieldNames() throws Exception {
assertTrue("Missing fields in set!", Sets.symmetricDifference(message.getFieldNames(), Sets.newHashSet("_id", "timestamp", "source", "message")).isEmpty());
message.addField("testfield", "testvalue");
assertTrue("Missing fields in set!", Sets.symmetricDifference(message.getFieldNames(), Sets.newHashSet("_id", "timestamp", "source", "message", "testfield")).isEmpty());
}
@Test(expected = UnsupportedOperationException.class)
public void testGetFieldNamesReturnsUnmodifiableSet() throws Exception {
final Set<String> fieldNames = message.getFieldNames();
fieldNames.remove("_id");
}
@Test
public void testHasField() throws Exception {
assertFalse(message.hasField("__foo__"));
message.addField("__foo__", "bar");
assertTrue(message.hasField("__foo__"));
}
}
| gpl-3.0 |
obiba/mica2 | mica-search/src/main/java/org/obiba/mica/search/aggregations/PopulationAggregationMetaDataProvider.java | 1342 | package org.obiba.mica.search.aggregations;
import org.obiba.mica.micaConfig.service.helper.AggregationMetaDataProvider;
import org.obiba.mica.micaConfig.service.helper.PopulationIdAggregationMetaDataHelper;
import org.springframework.stereotype.Component;
import javax.inject.Inject;
import java.util.Map;
@Component
public class PopulationAggregationMetaDataProvider implements AggregationMetaDataProvider {
private static final String AGGREGATION_NAME = "populationId";
private final PopulationIdAggregationMetaDataHelper helper;
@Inject
public PopulationAggregationMetaDataProvider(PopulationIdAggregationMetaDataHelper helper) {
this.helper = helper;
}
@Override
public MetaData getMetadata(String aggregation, String termKey, String locale) {
Map<String, LocalizedMetaData> dataMap = helper.getPopulations();
return AGGREGATION_NAME.equals(aggregation) && dataMap.containsKey(termKey) ?
MetaData.newBuilder()
.title(dataMap.get(termKey).getTitle().get(locale))
.description(dataMap.get(termKey).getDescription().get(locale))
.className(dataMap.get(termKey).getClassName())
.build() : null;
}
@Override
public boolean containsAggregation(String aggregation) {
return AGGREGATION_NAME.equals(aggregation);
}
@Override
public void refresh() {
}
}
| gpl-3.0 |
zazi/dswarm-graph-neo4j | src/main/java/org/dswarm/graph/delta/match/model/util/CSEntityUtil.java | 1515 | /**
* This file is part of d:swarm graph extension.
*
* d:swarm graph extension 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.
*
* d:swarm graph extension 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 d:swarm graph extension. If not, see <http://www.gnu.org/licenses/>.
*/
package org.dswarm.graph.delta.match.model.util;
import java.util.Collection;
import java.util.HashSet;
import java.util.Optional;
import java.util.Set;
import org.dswarm.graph.delta.match.model.CSEntity;
import org.dswarm.graph.delta.match.model.ValueEntity;
/**
* @author tgaengler
*/
public final class CSEntityUtil {
public static Optional<? extends Collection<ValueEntity>> getValueEntities(final Optional<? extends Collection<CSEntity>> csEntities) {
if (!csEntities.isPresent() || csEntities.get().isEmpty()) {
return Optional.empty();
}
final Set<ValueEntity> valueEntities = new HashSet<>();
for (final CSEntity csEntity : csEntities.get()) {
valueEntities.addAll(csEntity.getValueEntities());
}
return Optional.of(valueEntities);
}
}
| gpl-3.0 |
dcrissman/lightblue-ldap | lightblue-ldap-hystrix/src/main/java/com/redhat/lightblue/hystrix/ldap/AbstractLdapHystrixCommand.java | 1527 | /*
Copyright 2014 Red Hat, Inc. and/or its affiliates.
This file is part of lightblue.
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.redhat.lightblue.hystrix.ldap;
import com.netflix.hystrix.HystrixCommand;
import com.netflix.hystrix.HystrixCommandGroupKey;
import com.netflix.hystrix.HystrixCommandKey;
import com.unboundid.ldap.sdk.LDAPConnection;
public abstract class AbstractLdapHystrixCommand<T> extends HystrixCommand<T>{
public static final String GROUPKEY = "ldap";
private final LDAPConnection connection;
public LDAPConnection getConnection(){
return connection;
}
public AbstractLdapHystrixCommand(LDAPConnection connection, String commandKey){
super(HystrixCommand.Setter.withGroupKey(HystrixCommandGroupKey.Factory.asKey(GROUPKEY)).
andCommandKey(HystrixCommandKey.Factory.asKey(GROUPKEY + ":" + commandKey)));
this.connection = connection;
}
}
| gpl-3.0 |
pviotti/stacksync-desktop | src/com/stacksync/desktop/watch/local/LocalWatcher.java | 4196 | /*
* Syncany, www.syncany.org
* Copyright (C) 2011 Philipp C. Heckel <philipp.heckel@gmail.com>
*
* 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.stacksync.desktop.watch.local;
import java.io.File;
import org.apache.log4j.Logger;
import com.stacksync.desktop.Environment;
import com.stacksync.desktop.Environment.OperatingSystem;
import com.stacksync.desktop.config.Config;
import com.stacksync.desktop.config.Folder;
import com.stacksync.desktop.config.profile.Profile;
import com.stacksync.desktop.index.Indexer;
import com.stacksync.desktop.util.FileUtil;
/**
*
* @author oubou68, pheckel
*/
public abstract class LocalWatcher {
protected final Logger logger = Logger.getLogger(LocalWatcher.class.getName());
protected static final Environment env = Environment.getInstance();
protected static LocalWatcher instance;
protected Config config;
protected Indexer indexer;
public LocalWatcher() {
initDependencies();
logger.info("Creating watcher ...");
}
private void initDependencies() {
config = Config.getInstance();
indexer = Indexer.getInstance();
}
public void queueCheckFile(Folder root, File file) {
// Exclude ".ignore*" files from everything
if (FileUtil.checkIgnoreFile(root, file)) {
logger.debug("Watcher: Ignoring file "+file.getAbsolutePath());
return;
}
// File vanished!
if (!file.exists()) {
logger.warn("Watcher: File "+file+" vanished. IGNORING.");
return;
}
// Add to queue
logger.info("Watcher: Checking new/modified file "+file);
indexer.queueChecked(root, file);
}
public void queueMoveFile(Folder fromRoot, File fromFile, Folder toRoot, File toFile) {
// Exclude ".ignore*" files from everything
if (FileUtil.checkIgnoreFile(fromRoot, fromFile) || FileUtil.checkIgnoreFile(toRoot, toFile)) {
logger.info("Watcher: Ignoring file "+fromFile.getAbsolutePath());
return;
}
// File vanished!
if (!toFile.exists()) {
logger.warn("Watcher: File "+toFile+" vanished. IGNORING.");
return;
}
// Add to queue
logger.info("Watcher: Moving file "+fromFile+" TO "+toFile+"");
indexer.queueMoved(fromRoot, fromFile, toRoot, toFile);
}
public void queueDeleteFile(Folder root, File file) {
// Exclude ".ignore*" files from everything
if (FileUtil.checkIgnoreFile(root, file)) {
logger.info("Watcher: Ignoring file "+file.getAbsolutePath());
return;
}
// Add to queue
logger.info("Watcher: Deleted file "+file+"");
indexer.queueDeleted(root, file);
}
public static synchronized LocalWatcher getInstance() {
if (instance != null) {
return instance;
}
if (env.getOperatingSystem() == OperatingSystem.Linux
|| env.getOperatingSystem() == OperatingSystem.Windows
|| env.getOperatingSystem() == OperatingSystem.Mac) {
instance = new CommonLocalWatcher();
return instance;
}
throw new RuntimeException("Your operating system is currently not supported: " + System.getProperty("os.name"));
}
public abstract void start();
public abstract void stop();
public abstract void watch(Profile profile);
public abstract void unwatch(Profile profile);
}
| gpl-3.0 |
pslusarz/gnubridge | src/main/java/org/gnubridge/presentation/gui/OneColumnPerColor.java | 1786 | package org.gnubridge.presentation.gui;
import java.awt.Point;
import org.gnubridge.core.Card;
import org.gnubridge.core.Direction;
import org.gnubridge.core.East;
import org.gnubridge.core.Deal;
import org.gnubridge.core.Hand;
import org.gnubridge.core.North;
import org.gnubridge.core.South;
import org.gnubridge.core.West;
import org.gnubridge.core.deck.Suit;
public class OneColumnPerColor extends HandDisplay {
public OneColumnPerColor(Direction human, Direction player, Deal game, CardPanelHost owner) {
super(human, player, game, owner);
}
final static int CARD_OFFSET = 30;
@Override
public void display() {
dispose(cards);
Hand hand = new Hand(game.getPlayer(player).getHand());
Point upperLeft = calculateUpperLeft(human, player);
for (Suit color : Suit.list) {
int j = 0;
for (Card card : hand.getSuitHi2Low(color)) {
CardPanel cardPanel = new CardPanel(card);
cards.add(cardPanel);
if (human.equals(South.i())) {
cardPanel.setPlayable(true);
}
owner.addCard(cardPanel);
cardPanel.setLocation((int) upperLeft.getX(), (int) upperLeft.getY() + CARD_OFFSET * j);
j++;
}
upperLeft.setLocation(upperLeft.getX() + CardPanel.IMAGE_WIDTH + 2, upperLeft.getY());
}
}
private Point calculateUpperLeft(Direction human, Direction player) {
Direction slot = new HumanAlwaysOnBottom(human).mapRelativeTo(player);
if (North.i().equals(slot)) {
return new Point(235, 5);
} else if (West.i().equals(slot)) {
return new Point(3, owner.getTotalHeight() - 500);
} else if (East.i().equals(slot)) {
return new Point(512, owner.getTotalHeight() - 500);
} else if (South.i().equals(slot)) {
return new Point(235, owner.getTableBottom() + 1);
}
throw new RuntimeException("unknown direction");
}
}
| gpl-3.0 |
s20121035/rk3288_android5.1_repo | packages/inputmethods/LatinIME/java/src/com/android/inputmethod/latin/DictionaryWriter.java | 4412 | /*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.inputmethod.latin;
import android.content.Context;
import com.android.inputmethod.keyboard.ProximityInfo;
import com.android.inputmethod.latin.SuggestedWords.SuggestedWordInfo;
import com.android.inputmethod.latin.makedict.DictEncoder;
import com.android.inputmethod.latin.makedict.FormatSpec;
import com.android.inputmethod.latin.makedict.FusionDictionary;
import com.android.inputmethod.latin.makedict.FusionDictionary.PtNodeArray;
import com.android.inputmethod.latin.makedict.FusionDictionary.WeightedString;
import com.android.inputmethod.latin.makedict.UnsupportedFormatException;
import com.android.inputmethod.latin.utils.CollectionUtils;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
/**
* An in memory dictionary for memorizing entries and writing a binary dictionary.
*/
public class DictionaryWriter extends AbstractDictionaryWriter {
private static final int BINARY_DICT_VERSION = 3;
private static final FormatSpec.FormatOptions FORMAT_OPTIONS =
new FormatSpec.FormatOptions(BINARY_DICT_VERSION, true /* supportsDynamicUpdate */);
private FusionDictionary mFusionDictionary;
public DictionaryWriter(final Context context, final String dictType) {
super(context, dictType);
clear();
}
@Override
public void clear() {
final HashMap<String, String> attributes = CollectionUtils.newHashMap();
mFusionDictionary = new FusionDictionary(new PtNodeArray(),
new FusionDictionary.DictionaryOptions(attributes, false, false));
}
/**
* Adds a word unigram to the fusion dictionary.
*/
// TODO: Create "cache dictionary" to cache fresh words for frequently updated dictionaries,
// considering performance regression.
@Override
public void addUnigramWord(final String word, final String shortcutTarget, final int frequency,
final int shortcutFreq, final boolean isNotAWord) {
if (shortcutTarget == null) {
mFusionDictionary.add(word, frequency, null, isNotAWord);
} else {
// TODO: Do this in the subclass, with this class taking an arraylist.
final ArrayList<WeightedString> shortcutTargets = CollectionUtils.newArrayList();
shortcutTargets.add(new WeightedString(shortcutTarget, shortcutFreq));
mFusionDictionary.add(word, frequency, shortcutTargets, isNotAWord);
}
}
@Override
public void addBigramWords(final String word0, final String word1, final int frequency,
final boolean isValid, final long lastModifiedTime) {
mFusionDictionary.setBigram(word0, word1, frequency);
}
@Override
public void removeBigramWords(final String word0, final String word1) {
// This class don't support removing bigram words.
}
@Override
protected void writeDictionary(final DictEncoder dictEncoder,
final Map<String, String> attributeMap) throws IOException, UnsupportedFormatException {
for (final Map.Entry<String, String> entry : attributeMap.entrySet()) {
mFusionDictionary.addOptionAttribute(entry.getKey(), entry.getValue());
}
dictEncoder.writeDictionary(mFusionDictionary, FORMAT_OPTIONS);
}
@Override
public ArrayList<SuggestedWordInfo> getSuggestions(final WordComposer composer,
final String prevWord, final ProximityInfo proximityInfo,
boolean blockOffensiveWords, final int[] additionalFeaturesOptions) {
// This class doesn't support suggestion.
return null;
}
@Override
public boolean isValidWord(String word) {
// This class doesn't support dictionary retrieval.
return false;
}
}
| gpl-3.0 |
RahulDadoriya/MathSolverApp | src/com/example/mathsolver/AreaFragmentRight.java | 580 | package com.example.mathsolver;
import android.annotation.TargetApi;
import android.app.Fragment;
import android.os.Build;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public class AreaFragmentRight extends Fragment {
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
return inflater.inflate(R.layout.area_right, container, false);
}
}
| gpl-3.0 |
mlohbihler/BACnet4J | src/main/java/com/serotonin/bacnet4j/type/notificationParameters/CommandFailure.java | 4277 | /*
* ============================================================================
* GNU General Public License
* ============================================================================
*
* Copyright (C) 2015 Infinite Automation Software. All rights reserved.
*
* 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/>.
*
* When signing a commercial license with Infinite Automation Software,
* the following extension to GPL is made. A special exception to the GPL is
* included to allow you to distribute a combined work that includes BAcnet4J
* without being obliged to provide the source code for any proprietary components.
*
* See www.infiniteautomation.com for commercial license options.
*
* @author Matthew Lohbihler
*/
package com.serotonin.bacnet4j.type.notificationParameters;
import com.serotonin.bacnet4j.exception.BACnetException;
import com.serotonin.bacnet4j.type.AmbiguousValue;
import com.serotonin.bacnet4j.type.Encodable;
import com.serotonin.bacnet4j.type.constructed.StatusFlags;
import com.serotonin.bacnet4j.util.sero.ByteQueue;
public class CommandFailure extends NotificationParameters {
private static final long serialVersionUID = 5727410398456093753L;
public static final byte TYPE_ID = 3;
private final Encodable commandValue;
private final StatusFlags statusFlags;
private final Encodable feedbackValue;
public CommandFailure(Encodable commandValue, StatusFlags statusFlags, Encodable feedbackValue) {
this.commandValue = commandValue;
this.statusFlags = statusFlags;
this.feedbackValue = feedbackValue;
}
@Override
protected void writeImpl(ByteQueue queue) {
writeEncodable(queue, commandValue, 0);
write(queue, statusFlags, 1);
writeEncodable(queue, feedbackValue, 2);
}
public CommandFailure(ByteQueue queue) throws BACnetException {
commandValue = new AmbiguousValue(queue, 0);
statusFlags = read(queue, StatusFlags.class, 1);
feedbackValue = new AmbiguousValue(queue, 2);
}
@Override
protected int getTypeId() {
return TYPE_ID;
}
public Encodable getCommandValue() {
return commandValue;
}
public StatusFlags getStatusFlags() {
return statusFlags;
}
public Encodable getFeedbackValue() {
return feedbackValue;
}
@Override
public int hashCode() {
final int PRIME = 31;
int result = 1;
result = PRIME * result + ((commandValue == null) ? 0 : commandValue.hashCode());
result = PRIME * result + ((feedbackValue == null) ? 0 : feedbackValue.hashCode());
result = PRIME * result + ((statusFlags == null) ? 0 : statusFlags.hashCode());
return result;
}
@Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
final CommandFailure other = (CommandFailure) obj;
if (commandValue == null) {
if (other.commandValue != null)
return false;
}
else if (!commandValue.equals(other.commandValue))
return false;
if (feedbackValue == null) {
if (other.feedbackValue != null)
return false;
}
else if (!feedbackValue.equals(other.feedbackValue))
return false;
if (statusFlags == null) {
if (other.statusFlags != null)
return false;
}
else if (!statusFlags.equals(other.statusFlags))
return false;
return true;
}
}
| gpl-3.0 |
ufoe/Deskera-CRM | bpm-app/modulebuilder/src/main/java/com/krawler/portal/util/ListUtil.java | 8286 | /*
* Copyright (C) 2012 Krawler Information Systems Pvt Ltd
* All rights reserved.
*
* 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 2
* 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, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package com.krawler.portal.util;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Comparator;
import java.util.Enumeration;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;
/**
* <a href="ListUtil.java.html"><b><i>View Source</i></b></a>
*
* @author Brian Wing Shun Chan
*
*/
public class ListUtil {
public static List copy(List master) {
if (master == null) {
return null;
}
return new ArrayList(master);
}
public static void copy(List master, List copy) {
if ((master == null) || (copy == null)) {
return;
}
copy.clear();
Iterator itr = master.iterator();
while (itr.hasNext()) {
Object obj = itr.next();
copy.add(obj);
}
}
public static void distinct(List list) {
distinct(list, null);
}
public static void distinct(List list, Comparator comparator) {
if ((list == null) || (list.size() == 0)) {
return;
}
Set<Object> set = null;
if (comparator == null) {
set = new TreeSet<Object>();
}
else {
set = new TreeSet<Object>(comparator);
}
Iterator<Object> itr = list.iterator();
while (itr.hasNext()) {
Object obj = itr.next();
if (set.contains(obj)) {
itr.remove();
}
else {
set.add(obj);
}
}
}
public static List fromArray(Object[] array) {
if ((array == null) || (array.length == 0)) {
return new ArrayList();
}
List list = new ArrayList(array.length);
for (int i = 0; i < array.length; i++) {
list.add(array[i]);
}
return list;
}
public static List fromCollection(Collection c) {
if ((c != null) && (c instanceof List)) {
return (List)c;
}
if ((c == null) || (c.size() == 0)) {
return new ArrayList();
}
List list = new ArrayList(c.size());
Iterator itr = c.iterator();
while (itr.hasNext()) {
list.add(itr.next());
}
return list;
}
public static List fromEnumeration(Enumeration enu) {
List list = new ArrayList();
while (enu.hasMoreElements()) {
Object obj = enu.nextElement();
list.add(obj);
}
return list;
}
public static List fromFile(String fileName) throws IOException {
return fromFile(new File(fileName));
}
public static List fromFile(File file) throws IOException {
List list = new ArrayList();
BufferedReader br = new BufferedReader(new FileReader(file));
String s = StringPool.BLANK;
while ((s = br.readLine()) != null) {
list.add(s);
}
br.close();
return list;
}
public static List fromString(String s) {
return fromArray(StringUtil.split(s, StringPool.NEW_LINE));
}
public static List sort(List list) {
return sort(list, null);
}
public static List sort(List list, Comparator comparator) {
// if (list instanceof UnmodifiableList) {
// list = copy(list);
// }
//
// Collections.sort(list, comparator);
return list;
}
public static List subList(List list, int start, int end) {
List newList = new ArrayList();
int normalizedSize = list.size() - 1;
if ((start < 0) || (start > normalizedSize) || (end < 0) ||
(start > end)) {
return newList;
}
for (int i = start; i < end && i <= normalizedSize; i++) {
newList.add(list.get(i));
}
return newList;
}
public static List<Boolean> toList(boolean[] array) {
if ((array == null) || (array.length == 0)) {
return Collections.EMPTY_LIST;
}
List<Boolean> list = new ArrayList<Boolean>(array.length);
for (boolean value : array) {
list.add(value);
}
return list;
}
public static List<Double> toList(double[] array) {
if ((array == null) || (array.length == 0)) {
return Collections.EMPTY_LIST;
}
List<Double> list = new ArrayList<Double>(array.length);
for (double value : array) {
list.add(value);
}
return list;
}
public static List<Float> toList(float[] array) {
if ((array == null) || (array.length == 0)) {
return Collections.EMPTY_LIST;
}
List<Float> list = new ArrayList<Float>(array.length);
for (float value : array) {
list.add(value);
}
return list;
}
public static List<Integer> toList(int[] array) {
if ((array == null) || (array.length == 0)) {
return Collections.EMPTY_LIST;
}
List<Integer> list = new ArrayList<Integer>(array.length);
for (int value : array) {
list.add(value);
}
return list;
}
public static List<Long> toList(long[] array) {
if ((array == null) || (array.length == 0)) {
return Collections.EMPTY_LIST;
}
List<Long> list = new ArrayList<Long>(array.length);
for (long value : array) {
list.add(value);
}
return list;
}
public static List<Short> toList(short[] array) {
if ((array == null) || (array.length == 0)) {
return Collections.EMPTY_LIST;
}
List<Short> list = new ArrayList<Short>(array.length);
for (short value : array) {
list.add(value);
}
return list;
}
public static List<Boolean> toList(Boolean[] array) {
if ((array == null) || (array.length == 0)) {
return Collections.EMPTY_LIST;
}
List<Boolean> list = new ArrayList<Boolean>(array.length);
for (Boolean value : array) {
list.add(value);
}
return list;
}
public static List<Double> toList(Double[] array) {
if ((array == null) || (array.length == 0)) {
return Collections.EMPTY_LIST;
}
List<Double> list = new ArrayList<Double>(array.length);
for (Double value : array) {
list.add(value);
}
return list;
}
public static List<Float> toList(Float[] array) {
if ((array == null) || (array.length == 0)) {
return Collections.EMPTY_LIST;
}
List<Float> list = new ArrayList<Float>(array.length);
for (Float value : array) {
list.add(value);
}
return list;
}
public static List<Integer> toList(Integer[] array) {
if ((array == null) || (array.length == 0)) {
return Collections.EMPTY_LIST;
}
List<Integer> list = new ArrayList<Integer>(array.length);
for (Integer value : array) {
list.add(value);
}
return list;
}
public static List<Long> toList(Long[] array) {
if ((array == null) || (array.length == 0)) {
return Collections.EMPTY_LIST;
}
List<Long> list = new ArrayList<Long>(array.length);
for (Long value : array) {
list.add(value);
}
return list;
}
public static List<Short> toList(Short[] array) {
if ((array == null) || (array.length == 0)) {
return Collections.EMPTY_LIST;
}
List<Short> list = new ArrayList<Short>(array.length);
for (Short value : array) {
list.add(value);
}
return list;
}
public static List<String> toList(String[] array) {
if ((array == null) || (array.length == 0)) {
return Collections.EMPTY_LIST;
}
List<String> list = new ArrayList<String>(array.length);
for (String value : array) {
list.add(value);
}
return list;
}
public static String toString(List list, String param) {
return toString(list, param, StringPool.COMMA);
}
public static String toString(List list, String param, String delimiter) {
StringBuilder sb = new StringBuilder();
for (int i = 0; i < list.size(); i++) {
Object bean = list.get(i);
// Object value = BeanPropertiesUtil.getObject(bean, param);
//
// if (value == null) {
// value = StringPool.BLANK;
// }
//
// sb.append(value.toString());
if ((i + 1) != list.size()) {
sb.append(delimiter);
}
}
return sb.toString();
}
}
| gpl-3.0 |
s20121035/rk3288_android5.1_repo | packages/apps/UnifiedEmail/src/com/android/mail/compose/FromAddressSpinner.java | 6076 | /**
* Copyright (c) 2012, Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.mail.compose;
import android.content.Context;
import android.text.TextUtils;
import android.util.AttributeSet;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemSelectedListener;
import android.widget.Spinner;
import com.android.mail.providers.Account;
import com.android.mail.providers.Message;
import com.android.mail.providers.ReplyFromAccount;
import com.android.mail.utils.AccountUtils;
import com.google.common.annotations.VisibleForTesting;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.Lists;
import java.util.List;
public class FromAddressSpinner extends Spinner implements OnItemSelectedListener {
private List<Account> mAccounts;
private ReplyFromAccount mAccount;
private final List<ReplyFromAccount> mReplyFromAccounts = Lists.newArrayList();
private OnAccountChangedListener mAccountChangedListener;
public FromAddressSpinner(Context context) {
this(context, null);
}
public FromAddressSpinner(Context context, AttributeSet set) {
super(context, set);
}
public void setCurrentAccount(ReplyFromAccount account) {
mAccount = account;
selectCurrentAccount();
}
private void selectCurrentAccount() {
if (mAccount == null) {
return;
}
int currentIndex = 0;
for (ReplyFromAccount acct : mReplyFromAccounts) {
if (TextUtils.equals(mAccount.name, acct.name)
&& TextUtils.equals(mAccount.address, acct.address)) {
setSelection(currentIndex, true);
break;
}
currentIndex++;
}
}
public ReplyFromAccount getMatchingReplyFromAccount(String accountString) {
if (!TextUtils.isEmpty(accountString)) {
for (ReplyFromAccount acct : mReplyFromAccounts) {
if (accountString.equals(acct.address)) {
return acct;
}
}
}
return null;
}
public ReplyFromAccount getCurrentAccount() {
return mAccount;
}
/**
* @param action Action being performed; if this is COMPOSE, show all
* accounts. Otherwise, show just the account this was launched
* with.
* @param currentAccount Account used to launch activity.
* @param syncingAccounts
*/
public void initialize(int action, Account currentAccount, Account[] syncingAccounts,
Message refMessage) {
final List<Account> accounts = AccountUtils.mergeAccountLists(mAccounts,
syncingAccounts, true /* prioritizeAccountList */);
if (action == ComposeActivity.COMPOSE) {
mAccounts = accounts;
} else {
// First assume that we are going to use the current account as the reply account
Account replyAccount = currentAccount;
if (refMessage != null && refMessage.accountUri != null) {
// This is a reply or forward of a message access through the "combined" account.
// We want to make sure that the real account is in the spinner
for (Account account : accounts) {
if (account.uri.equals(refMessage.accountUri)) {
replyAccount = account;
break;
}
}
}
mAccounts = ImmutableList.of(replyAccount);
}
initFromSpinner();
}
@VisibleForTesting
protected void initFromSpinner() {
// If there are not yet any accounts in the cached synced accounts
// because this is the first time mail was opened, and it was opened
// directly to the compose activity, don't bother populating the reply
// from spinner yet.
if (mAccounts == null || mAccounts.size() == 0) {
return;
}
FromAddressSpinnerAdapter adapter =
new FromAddressSpinnerAdapter(getContext());
mReplyFromAccounts.clear();
for (Account account : mAccounts) {
mReplyFromAccounts.addAll(account.getReplyFroms());
}
adapter.addAccounts(mReplyFromAccounts);
setAdapter(adapter);
selectCurrentAccount();
setOnItemSelectedListener(this);
}
public List<ReplyFromAccount> getReplyFromAccounts() {
return mReplyFromAccounts;
}
public void setOnAccountChangedListener(OnAccountChangedListener listener) {
mAccountChangedListener = listener;
}
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
ReplyFromAccount selection = (ReplyFromAccount) getItemAtPosition(position);
if (!selection.address.equals(mAccount.address)) {
mAccount = selection;
mAccountChangedListener.onAccountChanged();
}
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
// Do nothing.
}
/**
* Classes that want to know when a different account in the
* FromAddressSpinner has been selected should implement this interface.
* Note: if the user chooses the same account as the one that has already
* been selected, this method will not be called.
*/
public static interface OnAccountChangedListener {
public void onAccountChanged();
}
}
| gpl-3.0 |
nishanttotla/predator | cpachecker/src/org/sosy_lab/cpachecker/cfa/model/ADeclarationEdge.java | 1757 | /*
* CPAchecker is a tool for configurable software verification.
* This file is part of CPAchecker.
*
* Copyright (C) 2007-2014 Dirk Beyer
* 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.
* 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.
*
*
* CPAchecker web page:
* http://cpachecker.sosy-lab.org
*/
package org.sosy_lab.cpachecker.cfa.model;
import org.sosy_lab.cpachecker.cfa.ast.FileLocation;
import org.sosy_lab.cpachecker.cfa.ast.ADeclaration;
import com.google.common.base.Optional;
public class ADeclarationEdge extends AbstractCFAEdge {
protected final ADeclaration declaration;
protected ADeclarationEdge(final String pRawSignature, final FileLocation pFileLocation,
final CFANode pPredecessor, final CFANode pSuccessor, final ADeclaration pDeclaration) {
super(pRawSignature, pFileLocation, pPredecessor, pSuccessor);
declaration = pDeclaration;
}
@Override
public CFAEdgeType getEdgeType() {
return CFAEdgeType.DeclarationEdge;
}
public ADeclaration getDeclaration() {
return declaration;
}
@Override
public Optional<? extends ADeclaration> getRawAST() {
return Optional.of(declaration);
}
@Override
public String getCode() {
return declaration.toASTString();
}
}
| gpl-3.0 |
AIT-JEVis/JECommons | src/main/java/org/jevis/commons/dataprocessing/v2/Task.java | 1111 | /**
* Copyright (C) 2015 Envidatec GmbH <info@envidatec.com>
*
* This file is part of JECommons.
*
* JECommons 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 in version 3.
*
* JECommons 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
* JECommons. If not, see <http://www.gnu.org/licenses/>.
*
* JECommons is part of the OpenJEVis project, further project information are
* published at <http://www.OpenJEVis.org/>.
*/
package org.jevis.commons.dataprocessing.v2;
import java.util.List;
/**
*
* @author Florian Simon
*/
public interface Task {
void setDataProcessor(Function dp);
Function getDataProcessor();
void setDependency(List<Task> dps);
List<Task> getDependency();
Result getResult();
}
| gpl-3.0 |
jtux270/translate | ovirt/backend/manager/modules/bll/src/main/java/org/ovirt/engine/core/bll/transport/ProtocolDetector.java | 3963 | package org.ovirt.engine.core.bll.transport;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import org.ovirt.engine.core.bll.Backend;
import org.ovirt.engine.core.common.businessentities.VDS;
import org.ovirt.engine.core.common.businessentities.VdsProtocol;
import org.ovirt.engine.core.common.businessentities.VdsStatic;
import org.ovirt.engine.core.common.config.Config;
import org.ovirt.engine.core.common.config.ConfigValues;
import org.ovirt.engine.core.common.interfaces.FutureVDSCall;
import org.ovirt.engine.core.common.vdscommands.FutureVDSCommandType;
import org.ovirt.engine.core.common.vdscommands.TimeBoundPollVDSCommandParameters;
import org.ovirt.engine.core.common.vdscommands.VDSReturnValue;
import org.ovirt.engine.core.dal.dbbroker.DbFacade;
import org.ovirt.engine.core.utils.transaction.TransactionMethod;
import org.ovirt.engine.core.utils.transaction.TransactionSupport;
import org.ovirt.engine.core.vdsbroker.ResourceManager;
/**
* We need to detect whether vdsm supports jsonrpc or only xmlrpc. It is confusing to users
* when they have cluster 3.5+ and connect to vdsm <3.5 which supports only xmlrpc.
* In order to present version information in such situation we need fallback to xmlrpc.
*
*/
public class ProtocolDetector {
private Integer connectionTimeout = null;
private Integer retryAttempts = null;
private VDS vds;
public ProtocolDetector(VDS vds) {
this.vds = vds;
this.retryAttempts = Config.<Integer> getValue(ConfigValues.ProtocolFallbackRetries);
this.connectionTimeout = Config.<Integer> getValue(ConfigValues.ProtocolFallbackTimeoutInMilliSeconds);
}
/**
* Attempts to connect to vdsm using a proxy from {@code VdsManager} for a host.
* There are 3 attempts to connect.
*
* @return <code>true</code> if connected or <code>false</code> if connection failed.
*/
public boolean attemptConnection() {
boolean connected = false;
try {
for (int i = 0; i < this.retryAttempts; i++) {
long timeout = Config.<Integer> getValue(ConfigValues.SetupNetworksPollingTimeout);
FutureVDSCall<VDSReturnValue> task =
Backend.getInstance().getResourceManager().runFutureVdsCommand(FutureVDSCommandType.TimeBoundPoll,
new TimeBoundPollVDSCommandParameters(vds.getId(), timeout, TimeUnit.SECONDS));
VDSReturnValue returnValue =
task.get(timeout, TimeUnit.SECONDS);
connected = returnValue.getSucceeded();
if (connected) {
break;
}
Thread.sleep(this.connectionTimeout);
}
} catch (TimeoutException | InterruptedException ignored) {
}
return connected;
}
/**
* Stops {@code VdsManager} for a host.
*/
public void stopConnection() {
ResourceManager.getInstance().RemoveVds(this.vds.getId());
}
/**
* Fall back the protocol and attempts the connection {@link ProtocolDetector#attemptConnection()}.
*
* @return <code>true</code> if connected or <code>false</code> if connection failed.
*/
public boolean attemptFallbackProtocol() {
vds.setProtocol(VdsProtocol.XML);
ResourceManager.getInstance().AddVds(vds, false);
return attemptConnection();
}
/**
* Updates DB with fall back protocol (xmlrpc).
*/
public void setFallbackProtocol() {
final VdsStatic vdsStatic = this.vds.getStaticData();
vdsStatic.setProtocol(VdsProtocol.XML);
TransactionSupport.executeInNewTransaction(new TransactionMethod<Void>() {
@Override
public Void runInTransaction() {
DbFacade.getInstance().getVdsStaticDao().update(vdsStatic);
return null;
}
});
}
}
| gpl-3.0 |
dzolnai/android | app/src/main/java/nl/eduvpn/app/adapter/MessagesAdapter.java | 3444 | /*
* This file is part of eduVPN.
*
* eduVPN 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.
*
* eduVPN 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 eduVPN. If not, see <http://www.gnu.org/licenses/>.
*/
package nl.eduvpn.app.adapter;
import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import nl.eduvpn.app.R;
import nl.eduvpn.app.adapter.viewholder.MessageViewHolder;
import nl.eduvpn.app.entity.message.Maintenance;
import nl.eduvpn.app.entity.message.Message;
import nl.eduvpn.app.entity.message.Notification;
import nl.eduvpn.app.utils.FormattingUtils;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Adapter for serving the message views inside a list.
* Created by Daniel Zolnai on 2016-10-19.
*/
public class MessagesAdapter extends RecyclerView.Adapter<MessageViewHolder> {
private List<Message> _userMessages;
private List<Message> _systemMessages;
private List<Message> _mergedList = new ArrayList<>();
private LayoutInflater _layoutInflater;
public void setUserMessages(List<Message> userMessages) {
_userMessages = userMessages;
_regenerateList();
}
public void setSystemMessages(List<Message> systemMessages) {
_systemMessages = systemMessages;
_regenerateList();
}
private void _regenerateList() {
_mergedList.clear();
if (_userMessages != null) {
_mergedList.addAll(_userMessages);
}
if (_systemMessages != null) {
_mergedList.addAll(_systemMessages);
}
Collections.sort(_mergedList);
notifyDataSetChanged();
}
@Override
public MessageViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
if (_layoutInflater == null) {
_layoutInflater = LayoutInflater.from(parent.getContext());
}
return new MessageViewHolder(_layoutInflater.inflate(R.layout.list_item_message, parent, false));
}
@Override
public void onBindViewHolder(MessageViewHolder holder, int position) {
Message message = _mergedList.get(position);
if (message instanceof Maintenance) {
holder.messageIcon.setVisibility(View.VISIBLE);
Context context = holder.messageText.getContext();
String maintenanceText = FormattingUtils.getMaintenanceText(context, (Maintenance)message);
holder.messageText.setText(maintenanceText);
} else if (message instanceof Notification) {
holder.messageIcon.setVisibility(View.GONE);
holder.messageText.setText(((Notification)message).getContent());
} else {
throw new RuntimeException("Unexpected message type!");
}
}
@Override
public int getItemCount() {
return _mergedList.size();
}
}
| gpl-3.0 |
faustedition/text | text-core/src/main/java/eu/interedition/text/xml/WhitespaceCompressor.java | 3002 | /*
* Copyright (c) 2013 The Interedition Development Group.
*
* This file is part of CollateX.
*
* CollateX 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.
*
* CollateX 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 CollateX. If not, see <http://www.gnu.org/licenses/>.
*/
package eu.interedition.text.xml;
import com.google.common.base.Objects;
import javax.xml.XMLConstants;
import javax.xml.stream.XMLStreamReader;
import java.util.Stack;
/**
* @author <a href="http://gregor.middell.net/" title="Homepage">Gregor Middell</a>
*/
public class WhitespaceCompressor extends ConversionFilter {
private final Stack<Boolean> spacePreservationContext = new Stack<Boolean>();
private final WhitespaceStrippingContext whitespaceStrippingContext;
private char lastChar = ' ';
public WhitespaceCompressor(WhitespaceStrippingContext whitespaceStrippingContext) {
this.whitespaceStrippingContext = whitespaceStrippingContext;
}
@Override
public void start() {
spacePreservationContext.clear();
whitespaceStrippingContext.reset();
lastChar = ' ';
}
@Override
protected void onXMLEvent(XMLStreamReader reader) {
whitespaceStrippingContext.onXMLEvent(reader);
if (reader.isStartElement()) {
spacePreservationContext.push(spacePreservationContext.isEmpty() ? false : spacePreservationContext.peek());
final Object xmlSpace = reader.getAttributeValue(XMLConstants.XML_NS_URI, "space");
if (xmlSpace != null) {
spacePreservationContext.pop();
spacePreservationContext.push("preserve".equalsIgnoreCase(xmlSpace.toString()));
}
} else if (reader.isEndElement()) {
spacePreservationContext.pop();
}
}
String compress(String text) {
final StringBuilder compressed = new StringBuilder();
final boolean preserveSpace = Objects.firstNonNull(spacePreservationContext.peek(), false);
for (int cc = 0, length = text.length(); cc < length; cc++) {
char currentChar = text.charAt(cc);
if (!preserveSpace && Character.isWhitespace(currentChar) && (Character.isWhitespace(lastChar) || whitespaceStrippingContext.isInContainerElement())) {
continue;
}
if (currentChar == '\n' || currentChar == '\r') {
currentChar = ' ';
}
compressed.append(lastChar = currentChar);
}
return compressed.toString();
}
}
| gpl-3.0 |
Mantaro/MantaroBot | src/main/java/net/kodehawa/mantarobot/commands/currency/profile/BadgeUtils.java | 2976 | /*
* Copyright (C) 2016-2021 David Rubio Escares / Kodehawa
*
* Mantaro 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.
* Mantaro 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 Mantaro. If not, see http://www.gnu.org/licenses/
*/
package net.kodehawa.mantarobot.commands.currency.profile;
import javax.imageio.ImageIO;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.image.BufferedImage;
import java.awt.image.WritableRaster;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
public class BadgeUtils {
public static byte[] applyBadge(byte[] avatarBytes, byte[] badgeBytes, int startX, int startY, boolean allWhite) {
BufferedImage avatar;
BufferedImage badge;
try {
avatar = ImageIO.read(new ByteArrayInputStream(avatarBytes));
badge = ImageIO.read(new ByteArrayInputStream(badgeBytes));
} catch (IOException impossible) {
throw new AssertionError(impossible);
}
WritableRaster raster = badge.getRaster();
if (allWhite) {
for (int xx = 0, width = badge.getWidth(); xx < width; xx++) {
for (int yy = 0, height = badge.getHeight(); yy < height; yy++) {
int[] pixels = raster.getPixel(xx, yy, (int[]) null);
pixels[0] = 255;
pixels[1] = 255;
pixels[2] = 255;
pixels[3] = pixels[3] == 255 ? 165 : 0;
raster.setPixel(xx, yy, pixels);
}
}
}
BufferedImage res = new BufferedImage(128, 128, BufferedImage.TYPE_INT_ARGB);
int circleCenterX = 88, circleCenterY = 88;
int width = 32, height = 32;
int circleRadius = 40;
Graphics2D g2d = res.createGraphics();
g2d.drawImage(avatar, 0, 0, 128, 128, null);
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
g2d.setColor(new Color(0, 0, 165, 165));
g2d.fillOval(circleCenterX, circleCenterY, circleRadius, circleRadius);
g2d.drawImage(badge, startX, startY, width, height, null);
g2d.dispose();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
ImageIO.write(res, "png", baos);
} catch (IOException e) {
throw new AssertionError(e);
}
return baos.toByteArray();
}
}
| gpl-3.0 |
TeamAmeriFrance/Electro-Magic-Tools | src/main/java/tombenpotter/emt/common/util/ResearchAspects.java | 6842 | /*******************************************************************************
* Copyright (c) 2014 Tombenpotter.
* All rights reserved.
*
* This program and the accompanying materials are made available under the terms of the GNU Public License v3.0
* which accompanies this distribution, and is available at http://www.gnu.org/licenses/gpl.html
*
* This class was made by Tombenpotter and is distributed as a part of the Electro-Magic Tools mod.
* Electro-Magic Tools is a derivative work on Thaumcraft 4 (c) Azanor 2012.
* http://www.minecraftforum.net/topic/1585216-
******************************************************************************/
package tombenpotter.emt.common.util;
import thaumcraft.api.aspects.Aspect;
import thaumcraft.api.aspects.AspectList;
public class ResearchAspects {
public static AspectList thaumiumDrillResearch = new AspectList().add(Aspect.ENERGY, 5).add(Aspect.TOOL, 6).add(Aspect.MINE, 4);
public static AspectList thaumiumChainsawResearch = new AspectList().add(Aspect.ENERGY, 5).add(Aspect.WEAPON, 6).add(Aspect.TOOL, 4);
public static AspectList thaumicQuantumHelmet = new AspectList().add(Aspect.ARMOR, 8).add(Aspect.ENERGY, 4).add(Aspect.SENSES, 6);
public static AspectList diamondOmnitoolResearch = new AspectList().add(Aspect.ENERGY, 2).add(Aspect.TOOL, 3).add(Aspect.MINE, 2).add(Aspect.WEAPON, 2);
public static AspectList thaumiumOmnitoolResearch = new AspectList().add(Aspect.ENERGY, 5).add(Aspect.TOOL, 6).add(Aspect.MINE, 4).add(Aspect.WEAPON, 6);
public static AspectList thaumicNanoHelmet = new AspectList().add(Aspect.ENERGY, 5).add(Aspect.SENSES, 8).add(Aspect.ARMOR, 6);
public static AspectList laserFocusResearch = new AspectList().add(Aspect.FIRE, 3).add(Aspect.DEATH, 2).add(Aspect.WEAPON, 3);
public static AspectList christmasFocusResearch = new AspectList().add(Aspect.COLD, 2).add(Aspect.BEAST, 5).add(Aspect.LIFE, 6);
public static AspectList shieldFocusResearch = new AspectList().add(Aspect.ARMOR, 5).add(Aspect.AIR, 2).add(Aspect.CRYSTAL, 3).add(Aspect.TRAP, 2);
public static AspectList electricGogglesResearch = new AspectList().add(Aspect.ARMOR, 8).add(Aspect.ENERGY, 5).add(Aspect.SENSES, 6);
public static AspectList potentiaGeneratorResearch = new AspectList().add(Aspect.ENERGY, 4).add(Aspect.EXCHANGE, 4).add(Aspect.METAL, 3);
public static AspectList ignisGeneratorResearch = new AspectList().add(Aspect.EXCHANGE, 4).add(Aspect.FIRE, 3);
public static AspectList auramGeneratorResearch = new AspectList().add(Aspect.EXCHANGE, 4).add(Aspect.AURA, 3);
public static AspectList arborGeneratorResearch = new AspectList().add(Aspect.EXCHANGE, 4).add(Aspect.TREE, 3);
public static AspectList streamChainsawResearch = new AspectList().add(Aspect.TOOL, 3).add(Aspect.TREE, 3).add(Aspect.WATER, 6).add(Aspect.ENERGY, 4);
public static AspectList rockbreakerDrillResearch = new AspectList().add(Aspect.ENERGY, 3).add(Aspect.FIRE, 2).add(Aspect.MINE, 3);
public static AspectList shieldBlockResearch = new AspectList().add(Aspect.ARMOR, 3).add(Aspect.TRAP, 2);
public static AspectList tinyUraniumResearch = new AspectList().add(Aspect.POISON, 4).add(Aspect.DEATH, 3).add(Aspect.EXCHANGE, 3);
public static AspectList thorHammerResearch = new AspectList().add(Aspect.WEAPON, 3).add(Aspect.WEATHER, 4).add(Aspect.ELDRITCH, 3);
public static AspectList superchargedThorHammerResearch = new AspectList().add(Aspect.WEAPON, 4).add(Aspect.ENERGY, 6).add(Aspect.BEAST, 4);
public static AspectList wandCharger = new AspectList().add(Aspect.ENERGY, 4).add(Aspect.CRAFT, 2).add(Aspect.EXCHANGE, 3).add(Aspect.GREED, 5);
public static AspectList compressedSolars = new AspectList().add(Aspect.ENERGY, 4).add(Aspect.LIGHT, 3).add(Aspect.METAL, 2);
public static AspectList solarHelmetRevealing = new AspectList().add(Aspect.ENERGY, 5).add(Aspect.AIR, 2).add(Aspect.LIGHT, 4);
public static AspectList electricBootsTravel = new AspectList().add(Aspect.ENERGY, 2).add(Aspect.ARMOR, 5).add(Aspect.MOTION, 2);
public static AspectList nanoBootsTravel = new AspectList().add(Aspect.ENERGY, 3).add(Aspect.ARMOR, 5).add(Aspect.MOTION, 3);
public static AspectList quantumBootsTravel = new AspectList().add(Aspect.ENERGY, 4).add(Aspect.ARMOR, 5).add(Aspect.MOTION, 4);
public static AspectList electricScribingTools = new AspectList().add(Aspect.ENERGY, 5).add(Aspect.DARKNESS, 3).add(Aspect.CRAFT, 1);
public static AspectList etherealProcessor = new AspectList().add(Aspect.MECHANISM, 3).add(Aspect.MAGIC, 4).add(Aspect.CRAFT, 5);
public static AspectList waterSolars = new AspectList().add(Aspect.WATER, 4).add(Aspect.MAGIC, 3).add(Aspect.ENERGY, 4);
public static AspectList darkSolars = new AspectList().add(Aspect.ENTROPY, 4).add(Aspect.MAGIC, 3).add(Aspect.ENERGY, 4);
public static AspectList orderSolars = new AspectList().add(Aspect.ORDER, 4).add(Aspect.MAGIC, 3).add(Aspect.ENERGY, 4);
public static AspectList fireSolars = new AspectList().add(Aspect.FIRE, 4).add(Aspect.MAGIC, 3).add(Aspect.ENERGY, 4);
public static AspectList airSolars = new AspectList().add(Aspect.AIR, 4).add(Aspect.MAGIC, 3).add(Aspect.ENERGY, 4);
public static AspectList earthSolars = new AspectList().add(Aspect.EARTH, 4).add(Aspect.MAGIC, 3).add(Aspect.ENERGY, 4);
public static AspectList uuMInfusion = new AspectList().add(Aspect.ELDRITCH, 4).add(Aspect.MAGIC, 4).add(Aspect.CRAFT, 5);
public static AspectList portableNode = new AspectList().add(Aspect.MAGIC, 5).add(Aspect.AURA, 5).add(Aspect.GREED, 5);
public static AspectList electricHoeGrowth = new AspectList().add(Aspect.ENERGY, 4).add(Aspect.PLANT, 4).add(Aspect.CROP, 5).add(Aspect.MAGIC, 4);
public static AspectList chargeFocus = new AspectList().add(Aspect.EXCHANGE, 4).add(Aspect.ENERGY, 5).add(Aspect.MECHANISM, 4);
public static AspectList wandChargeFocus = new AspectList().add(Aspect.ENERGY, 5).add(Aspect.AURA, 4).add(Aspect.EXCHANGE, 4).add(Aspect.GREED, 5);
public static AspectList inventoryChargingRing = new AspectList().add(Aspect.ENERGY, 4).add(Aspect.CRYSTAL, 4).add(Aspect.MAGIC, 4);
public static AspectList armorChargingRing = new AspectList().add(Aspect.ENERGY, 4).add(Aspect.ARMOR, 4).add(Aspect.MAGIC, 4);
public static AspectList thaumiumWing = new AspectList().add(Aspect.FLIGHT, 5).add(Aspect.AIR, 5).add(Aspect.MECHANISM, 8);
public static AspectList nanoWing = new AspectList().add(Aspect.FLIGHT, 5).add(Aspect.AIR, 5).add(Aspect.MECHANISM, 8).add(Aspect.ENERGY, 4);
public static AspectList quantumWing = new AspectList().add(Aspect.FLIGHT, 5).add(Aspect.AIR, 5).add(Aspect.MECHANISM, 8).add(Aspect.ENERGY, 4);
public static AspectList aerGenerator = new AspectList().add(Aspect.EXCHANGE, 4).add(Aspect.AIR, 3);
}
| gpl-3.0 |
erseco/ugr_sistemas_concurrentes_distribuidos | Practica_02_monitores/monitor/RunnableWithResult.java | 84 | package monitor;
public interface RunnableWithResult<T> {
public T run() ;
}
| gpl-3.0 |
Shappiro/GEOFRAME | PROJECTS/oms3.proj.richards1d/src/JAVA/parallelcolt-code/test/cern/colt/matrix/tlong/impl/SparseRCMLongMatrix2DViewTest.java | 483 | package cern.colt.matrix.tlong.impl;
public class SparseRCMLongMatrix2DViewTest extends SparseRCMLongMatrix2DTest {
public SparseRCMLongMatrix2DViewTest(String arg0) {
super(arg0);
}
protected void createMatrices() throws Exception {
A = new SparseRCMLongMatrix2D(NCOLUMNS, NROWS).viewDice();
B = new SparseRCMLongMatrix2D(NCOLUMNS, NROWS).viewDice();
Bt = new SparseRCMLongMatrix2D(NROWS, NCOLUMNS).viewDice();
}
}
| gpl-3.0 |
Maxcloud/Mushy | src/handling/handlers/UseInnerPortalHandler.java | 1090 | package handling.handlers;
import java.awt.Point;
import client.MapleClient;
import handling.PacketHandler;
import handling.RecvPacketOpcode;
import server.MaplePortal;
import tools.data.LittleEndianAccessor;
public class UseInnerPortalHandler {
@PacketHandler(opcode = RecvPacketOpcode.USE_INNER_PORTAL)
public static void handle(MapleClient c, LittleEndianAccessor lea) {
lea.skip(1);
if (c.getPlayer() == null || c.getPlayer().getMap() == null) {
return;
}
String portalName = lea.readMapleAsciiString();
MaplePortal portal = c.getPlayer().getMap().getPortal(portalName);
if (portal == null) {
return;
}
//That "22500" should not be hard coded in this manner
if (portal.getPosition().distanceSq(c.getPlayer().getTruePosition()) > 22500.0D && !c.getPlayer().isGM()) {
return;
}
int toX = lea.readShort();
int toY = lea.readShort();
//Are there not suppose to be checks here? Can players not just PE any x and y value they want?
c.getPlayer().getMap().movePlayer(c.getPlayer(), new Point(toX, toY));
c.getPlayer().checkFollow();
}
}
| gpl-3.0 |
Scrik/Cauldron-1 | eclipse/cauldron/src/main/java/net/minecraft/inventory/ContainerPlayer.java | 7916 | package net.minecraft.inventory;
import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.entity.player.InventoryPlayer;
import net.minecraft.init.Blocks;
import net.minecraft.init.Items;
import net.minecraft.item.Item;
import net.minecraft.item.ItemArmor;
import net.minecraft.item.ItemStack;
import net.minecraft.item.crafting.CraftingManager;
import net.minecraft.util.IIcon;
// CraftBukkit start
import net.minecraft.entity.player.EntityPlayerMP;
import net.minecraft.network.play.server.S2FPacketSetSlot;
import org.bukkit.craftbukkit.inventory.CraftInventoryCrafting;
import org.bukkit.craftbukkit.inventory.CraftInventoryView;
// CraftBukkit end
public class ContainerPlayer extends Container
{
public InventoryCrafting craftMatrix = new InventoryCrafting(this, 2, 2);
public IInventory craftResult = new InventoryCraftResult();
public boolean isLocalWorld;
private final EntityPlayer thePlayer;
// CraftBukkit start
private CraftInventoryView bukkitEntity = null;
private InventoryPlayer player;
// CraftBukkit end
private static final String __OBFID = "CL_00001754";
public ContainerPlayer(final InventoryPlayer p_i1819_1_, boolean p_i1819_2_, EntityPlayer p_i1819_3_)
{
this.isLocalWorld = p_i1819_2_;
this.thePlayer = p_i1819_3_;
this.craftResult = new InventoryCraftResult(); // CraftBukkit - moved to before InventoryCrafting construction
this.craftMatrix = new InventoryCrafting(this, 2, 2, p_i1819_1_.player); // CraftBukkit - pass player
this.craftMatrix.resultInventory = this.craftResult; // CraftBukkit - let InventoryCrafting know about its result slot
this.player = p_i1819_1_; // CraftBukkit - save player
this.addSlotToContainer(new SlotCrafting(p_i1819_1_.player, this.craftMatrix, this.craftResult, 0, 144, 36));
int i;
int j;
for (i = 0; i < 2; ++i)
{
for (j = 0; j < 2; ++j)
{
this.addSlotToContainer(new Slot(this.craftMatrix, j + i * 2, 88 + j * 18, 26 + i * 18));
}
}
for (i = 0; i < 4; ++i)
{
final int k = i;
this.addSlotToContainer(new Slot(p_i1819_1_, p_i1819_1_.getSizeInventory() - 1 - i, 8, 8 + i * 18)
{
private static final String __OBFID = "CL_00001755";
public int getSlotStackLimit()
{
return 1;
}
public boolean isItemValid(ItemStack p_75214_1_)
{
if (p_75214_1_ == null) return false;
return p_75214_1_.getItem().isValidArmor(p_75214_1_, k, thePlayer);
}
@SideOnly(Side.CLIENT)
public IIcon getBackgroundIconIndex()
{
return ItemArmor.func_94602_b(k);
}
});
}
for (i = 0; i < 3; ++i)
{
for (j = 0; j < 9; ++j)
{
this.addSlotToContainer(new Slot(p_i1819_1_, j + (i + 1) * 9, 8 + j * 18, 84 + i * 18));
}
}
for (i = 0; i < 9; ++i)
{
this.addSlotToContainer(new Slot(p_i1819_1_, i, 8 + i * 18, 142));
}
// this.onCraftMatrixChanged(this.craftMatrix); // CraftBukkit - unneeded since it just sets result slot to empty
}
public void onCraftMatrixChanged(IInventory p_75130_1_)
{
// CraftBukkit start (Note: the following line would cause an error if called during construction)
CraftingManager.getInstance().lastCraftView = getBukkitView();
ItemStack craftResult = CraftingManager.getInstance().findMatchingRecipe(this.craftMatrix, this.thePlayer.worldObj);
this.craftResult.setInventorySlotContents(0, craftResult);
if (super.crafters.size() < 1)
{
return;
}
EntityPlayerMP player = (EntityPlayerMP) super.crafters.get(0); // TODO: Is this _always_ correct? Seems like it.
player.playerNetServerHandler.sendPacket(new S2FPacketSetSlot(player.openContainer.windowId, 0, craftResult));
// CraftBukkit end
}
public void onContainerClosed(EntityPlayer p_75134_1_)
{
super.onContainerClosed(p_75134_1_);
for (int i = 0; i < 4; ++i)
{
ItemStack itemstack = this.craftMatrix.getStackInSlotOnClosing(i);
if (itemstack != null)
{
p_75134_1_.dropPlayerItemWithRandomChoice(itemstack, false);
}
}
this.craftResult.setInventorySlotContents(0, (ItemStack)null);
}
public boolean canInteractWith(EntityPlayer p_75145_1_)
{
return true;
}
public ItemStack transferStackInSlot(EntityPlayer p_82846_1_, int p_82846_2_)
{
ItemStack itemstack = null;
Slot slot = (Slot)this.inventorySlots.get(p_82846_2_);
if (slot != null && slot.getHasStack())
{
ItemStack itemstack1 = slot.getStack();
itemstack = itemstack1.copy();
if (p_82846_2_ == 0)
{
if (!this.mergeItemStack(itemstack1, 9, 45, true))
{
return null;
}
slot.onSlotChange(itemstack1, itemstack);
}
else if (p_82846_2_ >= 1 && p_82846_2_ < 5)
{
if (!this.mergeItemStack(itemstack1, 9, 45, false))
{
return null;
}
}
else if (p_82846_2_ >= 5 && p_82846_2_ < 9)
{
if (!this.mergeItemStack(itemstack1, 9, 45, false))
{
return null;
}
}
else if (itemstack.getItem() instanceof ItemArmor && !((Slot)this.inventorySlots.get(5 + ((ItemArmor)itemstack.getItem()).armorType)).getHasStack())
{
int j = 5 + ((ItemArmor)itemstack.getItem()).armorType;
if (!this.mergeItemStack(itemstack1, j, j + 1, false))
{
return null;
}
}
else if (p_82846_2_ >= 9 && p_82846_2_ < 36)
{
if (!this.mergeItemStack(itemstack1, 36, 45, false))
{
return null;
}
}
else if (p_82846_2_ >= 36 && p_82846_2_ < 45)
{
if (!this.mergeItemStack(itemstack1, 9, 36, false))
{
return null;
}
}
else if (!this.mergeItemStack(itemstack1, 9, 45, false))
{
return null;
}
if (itemstack1.stackSize == 0)
{
slot.putStack((ItemStack)null);
}
else
{
slot.onSlotChanged();
}
if (itemstack1.stackSize == itemstack.stackSize)
{
return null;
}
slot.onPickupFromSlot(p_82846_1_, itemstack1);
}
return itemstack;
}
public boolean func_94530_a(ItemStack p_94530_1_, Slot p_94530_2_)
{
return p_94530_2_.inventory != this.craftResult && super.func_94530_a(p_94530_1_, p_94530_2_);
}
// CraftBukkit start
public CraftInventoryView getBukkitView()
{
if (bukkitEntity != null)
{
return bukkitEntity;
}
CraftInventoryCrafting inventory = new CraftInventoryCrafting(this.craftMatrix, this.craftResult);
bukkitEntity = new CraftInventoryView(this.player.player.getBukkitEntity(), inventory, this);
return bukkitEntity;
}
// CraftBukkit end
} | gpl-3.0 |
applifireAlgo/appDemoApps201115 | bloodbank/src/main/java/com/app/server/repository/TitleRepository.java | 1156 | package com.app.server.repository;
import com.athena.server.repository.SearchInterface;
import com.athena.annotation.Complexity;
import com.athena.annotation.SourceCodeAuthorClass;
import com.athena.framework.server.exception.repository.SpartanPersistenceException;
import java.util.List;
import com.athena.framework.server.exception.biz.SpartanConstraintViolationException;
@SourceCodeAuthorClass(createdBy = "john.doe", updatedBy = "", versionNumber = "1", comments = "Repository for Title Master table Entity", complexity = Complexity.LOW)
public interface TitleRepository<T> extends SearchInterface {
public List<T> findAll() throws SpartanPersistenceException;
public T save(T entity) throws SpartanPersistenceException;
public List<T> save(List<T> entity) throws SpartanPersistenceException;
public void delete(String id) throws SpartanPersistenceException;
public void update(T entity) throws SpartanConstraintViolationException, SpartanPersistenceException;
public void update(List<T> entity) throws SpartanPersistenceException;
public T findById(String titleId) throws Exception, SpartanPersistenceException;
}
| gpl-3.0 |
JupiterDevelopmentTeam/JupiterDevelopmentTeam | src/main/java/cn/nukkit/math/Vector3.java | 9009 | package cn.nukkit.math;
/**
* author: MagicDroidX
* Nukkit Project
*/
public class Vector3 implements Cloneable {
public double x;
public double y;
public double z;
public Vector3() {
this(0, 0, 0);
}
public Vector3(double x) {
this(x, 0, 0);
}
public Vector3(double x, double y) {
this(x, y, 0);
}
public Vector3(double x, double y, double z) {
this.x = x;
this.y = y;
this.z = z;
}
public double getX() {
return this.x;
}
public double getY() {
return this.y;
}
public double getZ() {
return this.z;
}
public int getFloorX() {
return (int) Math.floor(this.x);
}
public int getFloorY() {
return (int) Math.floor(this.y);
}
public int getFloorZ() {
return (int) Math.floor(this.z);
}
public double getRight() {
return this.x;
}
public double getUp() {
return this.y;
}
public double getForward() {
return this.z;
}
public double getSouth() {
return this.x;
}
public double getWest() {
return this.z;
}
public Vector3 add(double x) {
return this.add(x, 0, 0);
}
public Vector3 add(double x, double y) {
return this.add(x, y, 0);
}
public Vector3 add(double x, double y, double z) {
return new Vector3(this.x + x, this.y + y, this.z + z);
}
public Vector3 add(Vector3 x) {
return new Vector3(this.x + x.getX(), this.y + x.getY(), this.z + x.getZ());
}
public Vector3 subtract() {
return this.subtract(0, 0, 0);
}
public Vector3 subtract(double x) {
return this.subtract(x, 0, 0);
}
public Vector3 subtract(double x, double y) {
return this.subtract(x, y, 0);
}
public Vector3 subtract(double x, double y, double z) {
return this.add(-x, -y, -z);
}
public Vector3 subtract(Vector3 x) {
return this.add(-x.getX(), -x.getY(), -x.getZ());
}
public Vector3 multiply(double number) {
return new Vector3(this.x * number, this.y * number, this.z * number);
}
public Vector3 divide(double number) {
return new Vector3(this.x / number, this.y / number, this.z / number);
}
public Vector3 ceil() {
return new Vector3((int) Math.ceil(this.x), (int) Math.ceil(this.y), (int) Math.ceil(this.z));
}
public Vector3 floor() {
return new Vector3(this.getFloorX(), this.getFloorY(), this.getFloorZ());
}
public Vector3 round() {
return new Vector3(Math.round(this.x), Math.round(this.y), Math.round(this.z));
}
public Vector3 abs() {
return new Vector3((int) Math.abs(this.x), (int) Math.abs(this.y), (int) Math.abs(this.z));
}
public Vector3 getSide(BlockFace face) {
return this.getSide(face, 1);
}
public Vector3 getSide(BlockFace face, int step) {
return new Vector3(this.getX() + face.getXOffset() * step, this.getY() + face.getYOffset() * step, this.getZ() + face.getZOffset() * step);
}
public Vector3 up() {
return up(1);
}
public Vector3 up(int step) {
return getSide(BlockFace.UP, step);
}
public Vector3 down() {
return down(1);
}
public Vector3 down(int step) {
return getSide(BlockFace.DOWN, step);
}
public Vector3 north() {
return north(1);
}
public Vector3 north(int step) {
return getSide(BlockFace.NORTH, step);
}
public Vector3 south() {
return south(1);
}
public Vector3 south(int step) {
return getSide(BlockFace.SOUTH, step);
}
public Vector3 east() {
return east(1);
}
public Vector3 east(int step) {
return getSide(BlockFace.EAST, step);
}
public Vector3 west() {
return west(1);
}
public Vector3 west(int step) {
return getSide(BlockFace.WEST, step);
}
public double distance(Vector3 pos) {
return Math.sqrt(this.distanceSquared(pos));
}
public double distanceSquared(Vector3 pos) {
return Math.pow(this.x - pos.x, 2) + Math.pow(this.y - pos.y, 2) + Math.pow(this.z - pos.z, 2);
}
public double maxPlainDistance() {
return this.maxPlainDistance(0, 0);
}
public double maxPlainDistance(double x) {
return this.maxPlainDistance(x, 0);
}
public double maxPlainDistance(double x, double z) {
return Math.max(Math.abs(this.x - x), Math.abs(this.z - z));
}
public double maxPlainDistance(Vector2 vector) {
return this.maxPlainDistance(vector.x, vector.y);
}
public double maxPlainDistance(Vector3 x) {
return this.maxPlainDistance(x.x, x.z);
}
public double length() {
return Math.sqrt(this.lengthSquared());
}
public double lengthSquared() {
return this.x * this.x + this.y * this.y + this.z * this.z;
}
public Vector3 normalize() {
double len = this.lengthSquared();
if (len > 0) {
return this.divide(Math.sqrt(len));
}
return new Vector3(0, 0, 0);
}
public double dot(Vector3 v) {
return this.x * v.x + this.y * v.y + this.z * v.z;
}
public Vector3 cross(Vector3 v) {
return new Vector3(
this.y * v.z - this.z * v.y,
this.z * v.x - this.x * v.z,
this.x * v.y - this.y * v.x
);
}
/**
* Returns a new vector with x value equal to the second parameter, along the line between this vector and the
* passed in vector, or null if not possible.
*/
public Vector3 getIntermediateWithXValue(Vector3 v, double x) {
double xDiff = v.x - this.x;
double yDiff = v.y - this.y;
double zDiff = v.z - this.z;
if (xDiff * xDiff < 0.0000001) {
return null;
}
double f = (x - this.x) / xDiff;
if (f < 0 || f > 1) {
return null;
} else {
return new Vector3(this.x + xDiff * f, this.y + yDiff * f, this.z + zDiff * f);
}
}
/**
* Returns a new vector with y value equal to the second parameter, along the line between this vector and the
* passed in vector, or null if not possible.
*/
public Vector3 getIntermediateWithYValue(Vector3 v, double y) {
double xDiff = v.x - this.x;
double yDiff = v.y - this.y;
double zDiff = v.z - this.z;
if (yDiff * yDiff < 0.0000001) {
return null;
}
double f = (y - this.y) / yDiff;
if (f < 0 || f > 1) {
return null;
} else {
return new Vector3(this.x + xDiff * f, this.y + yDiff * f, this.z + zDiff * f);
}
}
/**
* Returns a new vector with z value equal to the second parameter, along the line between this vector and the
* passed in vector, or null if not possible.
*/
public Vector3 getIntermediateWithZValue(Vector3 v, double z) {
double xDiff = v.x - this.x;
double yDiff = v.y - this.y;
double zDiff = v.z - this.z;
if (zDiff * zDiff < 0.0000001) {
return null;
}
double f = (z - this.z) / zDiff;
if (f < 0 || f > 1) {
return null;
} else {
return new Vector3(this.x + xDiff * f, this.y + yDiff * f, this.z + zDiff * f);
}
}
public Vector3 setComponents(double x, double y, double z) {
this.x = x;
this.y = y;
this.z = z;
return this;
}
@Override
public String toString() {
return "Vector3(x=" + this.x + ",y=" + this.y + ",z=" + this.z + ")";
}
@Override
public boolean equals(Object obj) {
if (!(obj instanceof Vector3)) {
return false;
}
Vector3 other = (Vector3) obj;
return this.x == other.x && this.y == other.y && this.z == other.z;
}
@Override
public int hashCode() {
int hash = 7;
hash = 79 * hash + (int) (Double.doubleToLongBits(this.x) ^ Double.doubleToLongBits(this.x) >>> 32);
hash = 79 * hash + (int) (Double.doubleToLongBits(this.y) ^ Double.doubleToLongBits(this.y) >>> 32);
hash = 79 * hash + (int) (Double.doubleToLongBits(this.z) ^ Double.doubleToLongBits(this.z) >>> 32);
return hash;
}
public int rawHashCode() {
return super.hashCode();
}
@Override
public Vector3 clone() {
try {
return (Vector3) super.clone();
} catch (CloneNotSupportedException e) {
return null;
}
}
public Vector3f asVector3f() {
return new Vector3f((float) this.x, (float) this.y, (float) this.z);
}
public BlockVector3 asBlockVector3() {
return new BlockVector3(this.getFloorX(), this.getFloorY(), this.getFloorZ());
}
} | gpl-3.0 |
CastellarFrank/ArchSim | src/VerilogCompiler/SyntacticTree/Range.java | 1723 | /*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package VerilogCompiler.SyntacticTree;
import VerilogCompiler.SemanticCheck.ErrorHandler;
import VerilogCompiler.SemanticCheck.ExpressionType;
import VerilogCompiler.SyntacticTree.Expressions.Expression;
/**
*
* @author Néstor A. Bermúdez < nestor.bermudezs@gmail.com >
*/
public class Range extends VNode {
Expression minValue;
Expression maxValue;
public Range(Expression minValue, Expression maxValue, int line, int column) {
super(line, column);
this.minValue = minValue;
this.maxValue = maxValue;
}
public Expression getMinValue() {
return minValue;
}
public void setMinValue(Expression minValue) {
this.minValue = minValue;
}
public Expression getMaxValue() {
return maxValue;
}
public void setMaxValue(Expression maxValue) {
this.maxValue = maxValue;
}
@Override
public String toString() {
return String.format("[%s:%s]", this.minValue, this.maxValue);
}
@Override
public ExpressionType validateSemantics() {
ExpressionType minReturnType = minValue.validateSemantics();
ExpressionType maxReturnType = maxValue.validateSemantics();
if (minReturnType != ExpressionType.INTEGER || maxReturnType != ExpressionType.INTEGER)
{
ErrorHandler.getInstance().handleError(line, column, "range min and max value must be integer");
}
return null;
}
@Override
public VNode getCopy() {
return new Range((Expression)minValue.getCopy(), (Expression)maxValue.getCopy(), line, column);
}
}
| gpl-3.0 |
s20121035/rk3288_android5.1_repo | cts/tests/tests/renderscript/src/android/renderscript/cts/TestAsin.java | 13539 | /*
* Copyright (C) 2014 The Android Open Source Project
*
* 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.
*/
// Don't edit this file! It is auto-generated by frameworks/rs/api/gen_runtime.
package android.renderscript.cts;
import android.renderscript.Allocation;
import android.renderscript.RSRuntimeException;
import android.renderscript.Element;
public class TestAsin extends RSBaseCompute {
private ScriptC_TestAsin script;
private ScriptC_TestAsinRelaxed scriptRelaxed;
@Override
protected void setUp() throws Exception {
super.setUp();
script = new ScriptC_TestAsin(mRS);
scriptRelaxed = new ScriptC_TestAsinRelaxed(mRS);
}
public class ArgumentsFloatFloat {
public float inV;
public Target.Floaty out;
}
private void checkAsinFloatFloat() {
Allocation inV = createRandomFloatAllocation(mRS, Element.DataType.FLOAT_32, 1, 0x80b5674ff98b5a12l, -1, 1);
try {
Allocation out = Allocation.createSized(mRS, getElement(mRS, Element.DataType.FLOAT_32, 1), INPUTSIZE);
script.forEach_testAsinFloatFloat(inV, out);
verifyResultsAsinFloatFloat(inV, out, false);
} catch (Exception e) {
throw new RSRuntimeException("RenderScript. Can't invoke forEach_testAsinFloatFloat: " + e.toString());
}
try {
Allocation out = Allocation.createSized(mRS, getElement(mRS, Element.DataType.FLOAT_32, 1), INPUTSIZE);
scriptRelaxed.forEach_testAsinFloatFloat(inV, out);
verifyResultsAsinFloatFloat(inV, out, true);
} catch (Exception e) {
throw new RSRuntimeException("RenderScript. Can't invoke forEach_testAsinFloatFloat: " + e.toString());
}
}
private void verifyResultsAsinFloatFloat(Allocation inV, Allocation out, boolean relaxed) {
float[] arrayInV = new float[INPUTSIZE * 1];
inV.copyTo(arrayInV);
float[] arrayOut = new float[INPUTSIZE * 1];
out.copyTo(arrayOut);
for (int i = 0; i < INPUTSIZE; i++) {
for (int j = 0; j < 1 ; j++) {
// Extract the inputs.
ArgumentsFloatFloat args = new ArgumentsFloatFloat();
args.inV = arrayInV[i];
// Figure out what the outputs should have been.
Target target = new Target(relaxed);
CoreMathVerifier.computeAsin(args, target);
// Validate the outputs.
boolean valid = true;
if (!args.out.couldBe(arrayOut[i * 1 + j])) {
valid = false;
}
if (!valid) {
StringBuilder message = new StringBuilder();
message.append("Input inV: ");
message.append(String.format("%14.8g {%8x} %15a",
args.inV, Float.floatToRawIntBits(args.inV), args.inV));
message.append("\n");
message.append("Expected output out: ");
message.append(args.out.toString());
message.append("\n");
message.append("Actual output out: ");
message.append(String.format("%14.8g {%8x} %15a",
arrayOut[i * 1 + j], Float.floatToRawIntBits(arrayOut[i * 1 + j]), arrayOut[i * 1 + j]));
if (!args.out.couldBe(arrayOut[i * 1 + j])) {
message.append(" FAIL");
}
message.append("\n");
assertTrue("Incorrect output for checkAsinFloatFloat" +
(relaxed ? "_relaxed" : "") + ":\n" + message.toString(), valid);
}
}
}
}
private void checkAsinFloat2Float2() {
Allocation inV = createRandomFloatAllocation(mRS, Element.DataType.FLOAT_32, 2, 0x9e11e5e823f7cce6l, -1, 1);
try {
Allocation out = Allocation.createSized(mRS, getElement(mRS, Element.DataType.FLOAT_32, 2), INPUTSIZE);
script.forEach_testAsinFloat2Float2(inV, out);
verifyResultsAsinFloat2Float2(inV, out, false);
} catch (Exception e) {
throw new RSRuntimeException("RenderScript. Can't invoke forEach_testAsinFloat2Float2: " + e.toString());
}
try {
Allocation out = Allocation.createSized(mRS, getElement(mRS, Element.DataType.FLOAT_32, 2), INPUTSIZE);
scriptRelaxed.forEach_testAsinFloat2Float2(inV, out);
verifyResultsAsinFloat2Float2(inV, out, true);
} catch (Exception e) {
throw new RSRuntimeException("RenderScript. Can't invoke forEach_testAsinFloat2Float2: " + e.toString());
}
}
private void verifyResultsAsinFloat2Float2(Allocation inV, Allocation out, boolean relaxed) {
float[] arrayInV = new float[INPUTSIZE * 2];
inV.copyTo(arrayInV);
float[] arrayOut = new float[INPUTSIZE * 2];
out.copyTo(arrayOut);
for (int i = 0; i < INPUTSIZE; i++) {
for (int j = 0; j < 2 ; j++) {
// Extract the inputs.
ArgumentsFloatFloat args = new ArgumentsFloatFloat();
args.inV = arrayInV[i * 2 + j];
// Figure out what the outputs should have been.
Target target = new Target(relaxed);
CoreMathVerifier.computeAsin(args, target);
// Validate the outputs.
boolean valid = true;
if (!args.out.couldBe(arrayOut[i * 2 + j])) {
valid = false;
}
if (!valid) {
StringBuilder message = new StringBuilder();
message.append("Input inV: ");
message.append(String.format("%14.8g {%8x} %15a",
args.inV, Float.floatToRawIntBits(args.inV), args.inV));
message.append("\n");
message.append("Expected output out: ");
message.append(args.out.toString());
message.append("\n");
message.append("Actual output out: ");
message.append(String.format("%14.8g {%8x} %15a",
arrayOut[i * 2 + j], Float.floatToRawIntBits(arrayOut[i * 2 + j]), arrayOut[i * 2 + j]));
if (!args.out.couldBe(arrayOut[i * 2 + j])) {
message.append(" FAIL");
}
message.append("\n");
assertTrue("Incorrect output for checkAsinFloat2Float2" +
(relaxed ? "_relaxed" : "") + ":\n" + message.toString(), valid);
}
}
}
}
private void checkAsinFloat3Float3() {
Allocation inV = createRandomFloatAllocation(mRS, Element.DataType.FLOAT_32, 3, 0x9e13af031a12edc4l, -1, 1);
try {
Allocation out = Allocation.createSized(mRS, getElement(mRS, Element.DataType.FLOAT_32, 3), INPUTSIZE);
script.forEach_testAsinFloat3Float3(inV, out);
verifyResultsAsinFloat3Float3(inV, out, false);
} catch (Exception e) {
throw new RSRuntimeException("RenderScript. Can't invoke forEach_testAsinFloat3Float3: " + e.toString());
}
try {
Allocation out = Allocation.createSized(mRS, getElement(mRS, Element.DataType.FLOAT_32, 3), INPUTSIZE);
scriptRelaxed.forEach_testAsinFloat3Float3(inV, out);
verifyResultsAsinFloat3Float3(inV, out, true);
} catch (Exception e) {
throw new RSRuntimeException("RenderScript. Can't invoke forEach_testAsinFloat3Float3: " + e.toString());
}
}
private void verifyResultsAsinFloat3Float3(Allocation inV, Allocation out, boolean relaxed) {
float[] arrayInV = new float[INPUTSIZE * 4];
inV.copyTo(arrayInV);
float[] arrayOut = new float[INPUTSIZE * 4];
out.copyTo(arrayOut);
for (int i = 0; i < INPUTSIZE; i++) {
for (int j = 0; j < 3 ; j++) {
// Extract the inputs.
ArgumentsFloatFloat args = new ArgumentsFloatFloat();
args.inV = arrayInV[i * 4 + j];
// Figure out what the outputs should have been.
Target target = new Target(relaxed);
CoreMathVerifier.computeAsin(args, target);
// Validate the outputs.
boolean valid = true;
if (!args.out.couldBe(arrayOut[i * 4 + j])) {
valid = false;
}
if (!valid) {
StringBuilder message = new StringBuilder();
message.append("Input inV: ");
message.append(String.format("%14.8g {%8x} %15a",
args.inV, Float.floatToRawIntBits(args.inV), args.inV));
message.append("\n");
message.append("Expected output out: ");
message.append(args.out.toString());
message.append("\n");
message.append("Actual output out: ");
message.append(String.format("%14.8g {%8x} %15a",
arrayOut[i * 4 + j], Float.floatToRawIntBits(arrayOut[i * 4 + j]), arrayOut[i * 4 + j]));
if (!args.out.couldBe(arrayOut[i * 4 + j])) {
message.append(" FAIL");
}
message.append("\n");
assertTrue("Incorrect output for checkAsinFloat3Float3" +
(relaxed ? "_relaxed" : "") + ":\n" + message.toString(), valid);
}
}
}
}
private void checkAsinFloat4Float4() {
Allocation inV = createRandomFloatAllocation(mRS, Element.DataType.FLOAT_32, 4, 0x9e15781e102e0ea2l, -1, 1);
try {
Allocation out = Allocation.createSized(mRS, getElement(mRS, Element.DataType.FLOAT_32, 4), INPUTSIZE);
script.forEach_testAsinFloat4Float4(inV, out);
verifyResultsAsinFloat4Float4(inV, out, false);
} catch (Exception e) {
throw new RSRuntimeException("RenderScript. Can't invoke forEach_testAsinFloat4Float4: " + e.toString());
}
try {
Allocation out = Allocation.createSized(mRS, getElement(mRS, Element.DataType.FLOAT_32, 4), INPUTSIZE);
scriptRelaxed.forEach_testAsinFloat4Float4(inV, out);
verifyResultsAsinFloat4Float4(inV, out, true);
} catch (Exception e) {
throw new RSRuntimeException("RenderScript. Can't invoke forEach_testAsinFloat4Float4: " + e.toString());
}
}
private void verifyResultsAsinFloat4Float4(Allocation inV, Allocation out, boolean relaxed) {
float[] arrayInV = new float[INPUTSIZE * 4];
inV.copyTo(arrayInV);
float[] arrayOut = new float[INPUTSIZE * 4];
out.copyTo(arrayOut);
for (int i = 0; i < INPUTSIZE; i++) {
for (int j = 0; j < 4 ; j++) {
// Extract the inputs.
ArgumentsFloatFloat args = new ArgumentsFloatFloat();
args.inV = arrayInV[i * 4 + j];
// Figure out what the outputs should have been.
Target target = new Target(relaxed);
CoreMathVerifier.computeAsin(args, target);
// Validate the outputs.
boolean valid = true;
if (!args.out.couldBe(arrayOut[i * 4 + j])) {
valid = false;
}
if (!valid) {
StringBuilder message = new StringBuilder();
message.append("Input inV: ");
message.append(String.format("%14.8g {%8x} %15a",
args.inV, Float.floatToRawIntBits(args.inV), args.inV));
message.append("\n");
message.append("Expected output out: ");
message.append(args.out.toString());
message.append("\n");
message.append("Actual output out: ");
message.append(String.format("%14.8g {%8x} %15a",
arrayOut[i * 4 + j], Float.floatToRawIntBits(arrayOut[i * 4 + j]), arrayOut[i * 4 + j]));
if (!args.out.couldBe(arrayOut[i * 4 + j])) {
message.append(" FAIL");
}
message.append("\n");
assertTrue("Incorrect output for checkAsinFloat4Float4" +
(relaxed ? "_relaxed" : "") + ":\n" + message.toString(), valid);
}
}
}
}
public void testAsin() {
checkAsinFloatFloat();
checkAsinFloat2Float2();
checkAsinFloat3Float3();
checkAsinFloat4Float4();
}
}
| gpl-3.0 |
ckaestne/LEADT | workspace/argouml_critics/argouml-app/src/org/argouml/uml/ui/foundation/core/ActionAddClientDependencyAction.java | 4569 | // $Id: ActionAddClientDependencyAction.java 41 2010-04-03 20:04:12Z marcusvnac $
// Copyright (c) 2007 The Regents of the University of California. All
// Rights Reserved. Permission to use, copy, modify, and distribute this
// software and its documentation without fee, and without a written
// agreement is hereby granted, provided that the above copyright notice
// and this paragraph appear in all copies. This software program and
// documentation are copyrighted by The Regents of the University of
// California. The software program and documentation are supplied "AS
// IS", without any accompanying services from The Regents. The Regents
// does not warrant that the operation of the program will be
// uninterrupted or error-free. The end-user understands that the program
// was developed for research purposes and is advised not to rely
// exclusively on the program for any reason. IN NO EVENT SHALL THE
// UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR DIRECT, INDIRECT,
// SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,
// ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF
// THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE POSSIBILITY OF
// SUCH DAMAGE. THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY
// WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
// MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE SOFTWARE
// PROVIDED HEREUNDER IS ON AN "AS IS" BASIS, AND THE UNIVERSITY OF
// CALIFORNIA HAS NO OBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT,
// UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
package org.argouml.uml.ui.foundation.core;
import java.util.ArrayList;
import java.util.Collection;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import org.argouml.i18n.Translator;
import org.argouml.kernel.ProjectManager;
import org.argouml.model.Model;
import org.argouml.uml.ui.AbstractActionAddModelElement2;
/**
* An Action to add client dependencies to some modelelement.
*
* @author Michiel
*/
public class ActionAddClientDependencyAction extends
AbstractActionAddModelElement2 {
/**
* The constructor.
*/
public ActionAddClientDependencyAction() {
super();
setMultiSelect(true);
}
/*
* Constraint: This code only deals with 1 supplier per dependency!
* TODO: How to support more?
*
* @see org.argouml.uml.ui.AbstractActionAddModelElement#doIt(java.util.List)
*/
protected void doIt(Collection selected) {
Set oldSet = new HashSet(getSelected());
for (Object client : selected) {
if (oldSet.contains(client)) {
oldSet.remove(client); //to be able to remove dependencies later
} else {
Model.getCoreFactory().buildDependency(getTarget(), client);
}
}
Collection toBeDeleted = new ArrayList();
Collection dependencies = Model.getFacade().getClientDependencies(
getTarget());
for (Object dependency : dependencies) {
if (oldSet.containsAll(Model.getFacade().getSuppliers(dependency))) {
toBeDeleted.add(dependency);
}
}
ProjectManager.getManager().getCurrentProject()
.moveToTrash(toBeDeleted);
}
/*
* @see org.argouml.uml.ui.AbstractActionAddModelElement#getChoices()
*/
protected List getChoices() {
List ret = new ArrayList();
Object model =
ProjectManager.getManager().getCurrentProject().getModel();
if (getTarget() != null) {
ret.addAll(Model.getModelManagementHelper()
.getAllModelElementsOfKind(model,
"org.omg.uml.foundation.core.ModelElement"));
ret.remove(getTarget());
}
return ret;
}
/*
* @see org.argouml.uml.ui.AbstractActionAddModelElement#getDialogTitle()
*/
protected String getDialogTitle() {
return Translator.localize("dialog.title.add-client-dependency");
}
/*
* @see org.argouml.uml.ui.AbstractActionAddModelElement#getSelected()
*/
protected List getSelected() {
List v = new ArrayList();
Collection c = Model.getFacade().getClientDependencies(getTarget());
for (Object cd : c) {
v.addAll(Model.getFacade().getSuppliers(cd));
}
return v;
}
}
| gpl-3.0 |
ybonnel/TransportsRennes | TransportsCommun/src/fr/ybo/transportscommun/activity/commun/ChangeIconActionBar.java | 188 | package fr.ybo.transportscommun.activity.commun;
import android.widget.ImageButton;
public interface ChangeIconActionBar {
public void changeIconActionBar(ImageButton imageButton);
}
| gpl-3.0 |
Leviathan143/betterbeginnings | src/main/java/net/einsteinsci/betterbeginnings/items/ItemKnife.java | 1851 | package net.einsteinsci.betterbeginnings.items;
import net.einsteinsci.betterbeginnings.register.IBBName;
import net.minecraft.block.Block;
import net.minecraft.init.Blocks;
import net.minecraft.item.ItemStack;
import net.minecraft.item.ItemTool;
import java.util.HashSet;
import java.util.Set;
public abstract class ItemKnife extends ItemTool implements IBBName
{
public static final float DAMAGE = 3.0f;
public ItemKnife(ToolMaterial material)
{
super(DAMAGE, material, getBreakable());
}
public static Set getBreakable()
{
Set<Block> s = new HashSet<>();
// s.add(Blocks.log);
// s.add(Blocks.log2);
// s.add(Blocks.planks);
s.add(Blocks.pumpkin);
s.add(Blocks.lit_pumpkin);
s.add(Blocks.melon_block);
s.add(Blocks.clay);
s.add(Blocks.grass);
s.add(Blocks.mycelium);
s.add(Blocks.leaves);
s.add(Blocks.leaves2);
s.add(Blocks.brown_mushroom_block);
s.add(Blocks.red_mushroom_block);
s.add(Blocks.glass);
s.add(Blocks.glass_pane);
s.add(Blocks.soul_sand);
s.add(Blocks.stained_glass);
s.add(Blocks.stained_glass_pane);
s.add(Blocks.cactus);
return s;
}
@Override
public boolean shouldRotateAroundWhenRendering()
{
return true;
}
@Override
public int getHarvestLevel(ItemStack stack, String toolClass)
{
return toolMaterial.getHarvestLevel();
}
@Override
public Set<String> getToolClasses(ItemStack stack)
{
Set<String> res = new HashSet<>();
res.add("knife");
return res;
}
// ...which also requires this...
@Override
public ItemStack getContainerItem(ItemStack itemStack)
{
ItemStack result = itemStack.copy();
result.setItemDamage(itemStack.getItemDamage() + 1);
return result;
}
// Allows durability-based crafting.
@Override
public boolean hasContainerItem(ItemStack stack)
{
return true;
}
@Override
public abstract String getName();
}
| gpl-3.0 |
RubenM13/E-EDD-2.0 | es.ucm.fdi.ed2.emf.diagram/src/es/ucm/fdi/emf/model/ed2/diagram/sheet/Ed2SheetLabelProvider.java | 2246 | package es.ucm.fdi.emf.model.ed2.diagram.sheet;
import org.eclipse.core.runtime.IAdaptable;
import org.eclipse.gmf.runtime.emf.type.core.IElementType;
import org.eclipse.gmf.runtime.notation.View;
import org.eclipse.jface.viewers.BaseLabelProvider;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.swt.graphics.Image;
import es.ucm.fdi.emf.model.ed2.diagram.navigator.Ed2NavigatorGroup;
import es.ucm.fdi.emf.model.ed2.diagram.part.Ed2VisualIDRegistry;
import es.ucm.fdi.emf.model.ed2.diagram.providers.Ed2ElementTypes;
/**
* @generated
*/
public class Ed2SheetLabelProvider extends BaseLabelProvider implements
ILabelProvider {
/**
* @generated
*/
public String getText(Object element) {
element = unwrap(element);
if (element instanceof Ed2NavigatorGroup) {
return ((Ed2NavigatorGroup) element).getGroupName();
}
IElementType etype = getElementType(getView(element));
return etype == null ? "" : etype.getDisplayName();
}
/**
* @generated
*/
public Image getImage(Object element) {
IElementType etype = getElementType(getView(unwrap(element)));
return etype == null ? null : Ed2ElementTypes.getImage(etype);
}
/**
* @generated
*/
private Object unwrap(Object element) {
if (element instanceof IStructuredSelection) {
return ((IStructuredSelection) element).getFirstElement();
}
return element;
}
/**
* @generated
*/
private View getView(Object element) {
if (element instanceof View) {
return (View) element;
}
if (element instanceof IAdaptable) {
return (View) ((IAdaptable) element).getAdapter(View.class);
}
return null;
}
/**
* @generated
*/
private IElementType getElementType(View view) {
// For intermediate views climb up the containment hierarchy to find the one associated with an element type.
while (view != null) {
int vid = Ed2VisualIDRegistry.getVisualID(view);
IElementType etype = Ed2ElementTypes.getElementType(vid);
if (etype != null) {
return etype;
}
view = view.eContainer() instanceof View ? (View) view.eContainer()
: null;
}
return null;
}
}
| gpl-3.0 |
seedstack/i18n-function | rest/src/main/java/org/seedstack/i18n/rest/internal/infrastructure/csv/I18nCSVTemplateLoader.java | 2205 | /*
* Copyright © 2013-2020, The SeedStack authors <http://seedstack.org>
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
package org.seedstack.i18n.rest.internal.infrastructure.csv;
import com.google.common.collect.Sets;
import org.seedstack.i18n.rest.internal.locale.LocaleFinder;
import org.seedstack.i18n.rest.internal.locale.LocaleRepresentation;
import org.seedstack.io.spi.Template;
import org.seedstack.io.spi.TemplateLoader;
import org.seedstack.io.supercsv.Column;
import org.seedstack.io.supercsv.SuperCsvTemplate;
import org.seedstack.jpa.JpaUnit;
import org.seedstack.seed.transaction.Transactional;
import org.supercsv.cellprocessor.Optional;
import javax.inject.Inject;
import java.util.List;
import java.util.Set;
/**
* @author pierre.thirouin@ext.mpsa.com
*/
public class I18nCSVTemplateLoader implements TemplateLoader {
public static final String I18N_CSV_TEMPLATE = "i18nTranslations";
public static final String KEY = "key";
@Inject
private LocaleFinder localeFinder;
@JpaUnit("seed-i18n-domain")
@Transactional
@Override
public Template load(String name) {
List<LocaleRepresentation> availableLocales = localeFinder.findAvailableLocales();
SuperCsvTemplate superCsvTemplate = new SuperCsvTemplate(name);
superCsvTemplate.addColumn(new Column(KEY, KEY, new Optional(), new Optional()));
for (LocaleRepresentation availableLocale : availableLocales) {
superCsvTemplate.addColumn(new Column(availableLocale.getCode(), availableLocale.getCode(), new Optional(), new Optional()));
}
return superCsvTemplate;
}
@Override
public Set<String> names() {
return Sets.newHashSet(I18N_CSV_TEMPLATE);
}
@Override
public boolean contains(String name) {
return names().contains(name);
}
@Override
public String templateRenderer() {
return I18nCSVRenderer.I18N_RENDERER;
}
@Override
public String templateParser() {
return CSVParser.I18N_PARSER;
}
}
| mpl-2.0 |
jembi/openhim-encounter-orchestrator | src/main/java/org/hl7/v3/ResponseMode.java | 754 |
package org.hl7.v3;
import javax.xml.bind.annotation.XmlEnum;
import javax.xml.bind.annotation.XmlType;
/**
* <p>Java class for ResponseMode.
*
* <p>The following schema fragment specifies the expected content contained within this class.
* <p>
* <pre>
* <simpleType name="ResponseMode">
* <restriction base="{urn:hl7-org:v3}cs">
* <enumeration value="D"/>
* <enumeration value="I"/>
* <enumeration value="Q"/>
* </restriction>
* </simpleType>
* </pre>
*
*/
@XmlType(name = "ResponseMode")
@XmlEnum
public enum ResponseMode {
D,
I,
Q;
public String value() {
return name();
}
public static ResponseMode fromValue(String v) {
return valueOf(v);
}
}
| mpl-2.0 |
IMS-MAXIMS/openMAXIMS | Source Library/openmaxims_workspace/DomainObjects/src/ims/core/clinical/domain/objects/NonUniqueTaxonomyMap.java | 14623 | //#############################################################################
//# #
//# Copyright (C) <2015> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of #
//# this program. Users of this software do so entirely at their own risk. #
//# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time #
//# software that it builds, deploys and maintains. #
//# #
//#############################################################################
//#EOH
/*
* This code was generated
* Copyright (C) 1995-2004 IMS MAXIMS plc. All rights reserved.
* IMS Development Environment (version 1.80 build 5589.25814)
* WARNING: DO NOT MODIFY the content of this file
* Generated: 12/10/2015, 13:28
*
*/
package ims.core.clinical.domain.objects;
/**
*
* @author John MacEnri
* Generated.
*/
public class NonUniqueTaxonomyMap extends ims.domain.DomainObject implements ims.domain.SystemInformationRetainer, java.io.Serializable {
public static final int CLASSID = 1003100071;
private static final long serialVersionUID = 1003100071L;
public static final String CLASSVERSION = "${ClassVersion}";
@Override
public boolean shouldCapQuery()
{
return true;
}
private ims.domain.lookups.LookupInstance taxonomyName;
private String taxonomyCode;
private java.util.Date effectiveFrom;
private java.util.Date effectiveTo;
/** SystemInformation */
private ims.domain.SystemInformation systemInformation = new ims.domain.SystemInformation();
public NonUniqueTaxonomyMap (Integer id, int ver)
{
super(id, ver);
isComponentClass=true;
}
public NonUniqueTaxonomyMap ()
{
super();
isComponentClass=true;
}
public NonUniqueTaxonomyMap (Integer id, int ver, Boolean includeRecord)
{
super(id, ver, includeRecord);
isComponentClass=true;
}
public Class getRealDomainClass()
{
return ims.core.clinical.domain.objects.NonUniqueTaxonomyMap.class;
}
public ims.domain.lookups.LookupInstance getTaxonomyName() {
return taxonomyName;
}
public void setTaxonomyName(ims.domain.lookups.LookupInstance taxonomyName) {
this.taxonomyName = taxonomyName;
}
public String getTaxonomyCode() {
return taxonomyCode;
}
public void setTaxonomyCode(String taxonomyCode) {
if ( null != taxonomyCode && taxonomyCode.length() > 30 ) {
throw new ims.domain.exceptions.DomainRuntimeException("MaxLength ($MaxLength) exceeded for taxonomyCode. Tried to set value: "+
taxonomyCode);
}
this.taxonomyCode = taxonomyCode;
}
public java.util.Date getEffectiveFrom() {
return effectiveFrom;
}
public void setEffectiveFrom(java.util.Date effectiveFrom) {
this.effectiveFrom = effectiveFrom;
}
public java.util.Date getEffectiveTo() {
return effectiveTo;
}
public void setEffectiveTo(java.util.Date effectiveTo) {
this.effectiveTo = effectiveTo;
}
public ims.domain.SystemInformation getSystemInformation() {
if (systemInformation == null) systemInformation = new ims.domain.SystemInformation();
return systemInformation;
}
/**
* isConfigurationObject
* Taken from the Usage property of the business object, this method will return
* a boolean indicating whether this is a configuration object or not
* Configuration = true, Instantiation = false
*/
public static boolean isConfigurationObject()
{
if ( "Instantiation".equals("Configuration") )
return true;
else
return false;
}
public int getClassId() {
return CLASSID;
}
public String getClassVersion()
{
return CLASSVERSION;
}
public String toAuditString()
{
StringBuffer auditStr = new StringBuffer();
auditStr.append("\r\n*taxonomyName* :");
if (taxonomyName != null)
auditStr.append(taxonomyName.getText());
auditStr.append("; ");
auditStr.append("\r\n*taxonomyCode* :");
auditStr.append(taxonomyCode);
auditStr.append("; ");
auditStr.append("\r\n*effectiveFrom* :");
auditStr.append(effectiveFrom);
auditStr.append("; ");
auditStr.append("\r\n*effectiveTo* :");
auditStr.append(effectiveTo);
auditStr.append("; ");
return auditStr.toString();
}
public String toXMLString()
{
return toXMLString(new java.util.HashMap());
}
public String toXMLString(java.util.HashMap domMap)
{
StringBuffer sb = new StringBuffer();
sb.append("<class type=\"" + this.getClass().getName() + "\" ");
sb.append(" source=\"" + ims.configuration.EnvironmentConfig.getImportExportSourceName() + "\" ");
sb.append(" classVersion=\"" + this.getClassVersion() + "\" ");
sb.append(" component=\"" + this.getIsComponentClass() + "\" >");
if (domMap.get(this) == null)
{
domMap.put(this, this);
sb.append(this.fieldsToXMLString(domMap));
}
sb.append("</class>");
return sb.toString();
}
public String fieldsToXMLString(java.util.HashMap domMap)
{
StringBuffer sb = new StringBuffer();
if (this.getTaxonomyName() != null)
{
sb.append("<taxonomyName>");
sb.append(this.getTaxonomyName().toXMLString());
sb.append("</taxonomyName>");
}
if (this.getTaxonomyCode() != null)
{
sb.append("<taxonomyCode>");
sb.append(ims.framework.utils.StringUtils.encodeXML(this.getTaxonomyCode().toString()));
sb.append("</taxonomyCode>");
}
if (this.getEffectiveFrom() != null)
{
sb.append("<effectiveFrom>");
sb.append(new ims.framework.utils.DateTime(this.getEffectiveFrom()).toString(ims.framework.utils.DateTimeFormat.MILLI));
sb.append("</effectiveFrom>");
}
if (this.getEffectiveTo() != null)
{
sb.append("<effectiveTo>");
sb.append(new ims.framework.utils.DateTime(this.getEffectiveTo()).toString(ims.framework.utils.DateTimeFormat.MILLI));
sb.append("</effectiveTo>");
}
return sb.toString();
}
public static java.util.List fromListXMLString(org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.List list, java.util.HashMap domMap) throws Exception
{
if (list == null)
list = new java.util.ArrayList();
fillListFromXMLString(list, el, factory, domMap);
return list;
}
public static java.util.Set fromSetXMLString(org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.Set set, java.util.HashMap domMap) throws Exception
{
if (set == null)
set = new java.util.HashSet();
fillSetFromXMLString(set, el, factory, domMap);
return set;
}
private static void fillSetFromXMLString(java.util.Set set, org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception
{
if (el == null)
return;
java.util.List cl = el.elements("class");
int size = cl.size();
java.util.Set newSet = new java.util.HashSet();
for(int i=0; i<size; i++)
{
org.dom4j.Element itemEl = (org.dom4j.Element)cl.get(i);
NonUniqueTaxonomyMap domainObject = getNonUniqueTaxonomyMapfromXML(itemEl, factory, domMap);
if (domainObject == null)
{
continue;
}
//Trying to avoid the hibernate collection being marked as dirty via its public interface methods. (like add)
if (!set.contains(domainObject))
set.add(domainObject);
newSet.add(domainObject);
}
java.util.Set removedSet = new java.util.HashSet();
java.util.Iterator iter = set.iterator();
//Find out which objects need to be removed
while (iter.hasNext())
{
ims.domain.DomainObject o = (ims.domain.DomainObject)iter.next();
if ((o == null || o.getIsRIE() == null || !o.getIsRIE().booleanValue()) && !newSet.contains(o))
{
removedSet.add(o);
}
}
iter = removedSet.iterator();
//Remove the unwanted objects
while (iter.hasNext())
{
set.remove(iter.next());
}
}
private static void fillListFromXMLString(java.util.List list, org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception
{
if (el == null)
return;
java.util.List cl = el.elements("class");
int size = cl.size();
for(int i=0; i<size; i++)
{
org.dom4j.Element itemEl = (org.dom4j.Element)cl.get(i);
NonUniqueTaxonomyMap domainObject = getNonUniqueTaxonomyMapfromXML(itemEl, factory, domMap);
if (domainObject == null)
{
continue;
}
int domIdx = list.indexOf(domainObject);
if (domIdx == -1)
{
list.add(i, domainObject);
}
else if (i != domIdx && i < list.size())
{
Object tmp = list.get(i);
list.set(i, list.get(domIdx));
list.set(domIdx, tmp);
}
}
//Remove all ones in domList where index > voCollection.size() as these should
//now represent the ones removed from the VO collection. No longer referenced.
int i1=list.size();
while (i1 > size)
{
list.remove(i1-1);
i1=list.size();
}
}
public static NonUniqueTaxonomyMap getNonUniqueTaxonomyMapfromXML(String xml, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception
{
org.dom4j.Document doc = new org.dom4j.io.SAXReader().read(new org.xml.sax.InputSource(xml));
return getNonUniqueTaxonomyMapfromXML(doc.getRootElement(), factory, domMap);
}
public static NonUniqueTaxonomyMap getNonUniqueTaxonomyMapfromXML(org.dom4j.Element el, ims.domain.DomainFactory factory, java.util.HashMap domMap) throws Exception
{
if (el == null)
return null;
String className = el.attributeValue("type");
if (!NonUniqueTaxonomyMap.class.getName().equals(className))
{
Class clz = Class.forName(className);
if (!NonUniqueTaxonomyMap.class.isAssignableFrom(clz))
throw new Exception("Element of type = " + className + " cannot be imported using the NonUniqueTaxonomyMap class");
String shortClassName = className.substring(className.lastIndexOf(".")+1);
String methodName = "get" + shortClassName + "fromXML";
java.lang.reflect.Method m = clz.getMethod(methodName, new Class[]{org.dom4j.Element.class, ims.domain.DomainFactory.class, java.util.HashMap.class});
return (NonUniqueTaxonomyMap)m.invoke(null, new Object[]{el, factory, domMap});
}
String impVersion = el.attributeValue("classVersion");
if(!impVersion.equals(NonUniqueTaxonomyMap.CLASSVERSION))
{
throw new Exception("Incompatible class structure found. Cannot import instance.");
}
NonUniqueTaxonomyMap ret = null;
if (ret == null)
{
ret = new NonUniqueTaxonomyMap();
}
fillFieldsfromXML(el, factory, ret, domMap);
return ret;
}
public static void fillFieldsfromXML(org.dom4j.Element el, ims.domain.DomainFactory factory, NonUniqueTaxonomyMap obj, java.util.HashMap domMap) throws Exception
{
org.dom4j.Element fldEl;
fldEl = el.element("taxonomyName");
if(fldEl != null)
{
fldEl = fldEl.element("lki");
obj.setTaxonomyName(ims.domain.lookups.LookupInstance.fromXMLString(fldEl, factory));
}
fldEl = el.element("taxonomyCode");
if(fldEl != null)
{
obj.setTaxonomyCode(new String(fldEl.getTextTrim()));
}
fldEl = el.element("effectiveFrom");
if(fldEl != null)
{
obj.setEffectiveFrom(new java.text.SimpleDateFormat("yyyyMMddHHmmssSSS").parse(fldEl.getTextTrim()));
}
fldEl = el.element("effectiveTo");
if(fldEl != null)
{
obj.setEffectiveTo(new java.text.SimpleDateFormat("yyyyMMddHHmmssSSS").parse(fldEl.getTextTrim()));
}
}
public static String[] getCollectionFields()
{
return new String[]{
};
}
/**
equals
*/
public boolean equals(Object obj)
{
if (null == obj)
{
return false;
}
if(!(obj instanceof NonUniqueTaxonomyMap))
{
return false;
}
NonUniqueTaxonomyMap compareObj=(NonUniqueTaxonomyMap)obj;
if((taxonomyCode==null ? compareObj.taxonomyCode == null : taxonomyCode.equals(compareObj.taxonomyCode))&&
(taxonomyName==null ? compareObj.taxonomyName==null : taxonomyName.equals(compareObj.taxonomyName))&&
(effectiveFrom==null? compareObj.effectiveFrom==null : effectiveFrom.equals(compareObj.effectiveFrom))&&
(effectiveTo==null? compareObj.effectiveTo==null : effectiveTo.equals(compareObj.effectiveTo)))
return true;
return super.equals(obj);
}
/**
toString
*/
public String toString()
{
StringBuffer objStr = new StringBuffer();
if (taxonomyName != null)
objStr.append(taxonomyName.getText() + "-");
objStr.append(taxonomyCode);
return objStr.toString();
}
/**
hashcode
*/
public int hashCode()
{
int hash = 0;
if (taxonomyName!= null) hash += taxonomyName.hashCode()* 10011;
if (taxonomyCode!= null) hash += taxonomyCode.hashCode();
if (effectiveFrom!= null) hash += effectiveFrom.hashCode();
if (effectiveTo!= null) hash += effectiveTo.hashCode();
return hash;
}
public static class FieldNames
{
public static final String ID = "id";
public static final String TaxonomyName = "taxonomyName";
public static final String TaxonomyCode = "taxonomyCode";
public static final String EffectiveFrom = "effectiveFrom";
public static final String EffectiveTo = "effectiveTo";
}
}
| agpl-3.0 |
rapidminer/rapidminer-5 | src/com/rapidminer/gui/plotter/mathplot/JMathPlotter3D.java | 1676 | /*
* RapidMiner
*
* Copyright (C) 2001-2014 by RapidMiner and the contributors
*
* Complete list of developers available at our web site:
*
* http://rapidminer.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*/
package com.rapidminer.gui.plotter.mathplot;
import org.math.plot.Plot3DPanel;
import org.math.plot.PlotPanel;
import com.rapidminer.datatable.DataTable;
import com.rapidminer.gui.plotter.PlotterConfigurationModel;
/** The abstract super class for all 3D plotters using the JMathPlot library.
*
* @author Ingo Mierswa
*/
public abstract class JMathPlotter3D extends JMathPlotter {
private static final long serialVersionUID = -8695197842788069313L;
public JMathPlotter3D(PlotterConfigurationModel settings) {
super(settings);
}
public JMathPlotter3D(PlotterConfigurationModel settings, DataTable dataTable) {
super(settings, dataTable);
}
@Override
public PlotPanel createPlotPanel() { return new Plot3DPanel(); }
@Override
public int getNumberOfOptionIcons() {
return 5;
}
}
| agpl-3.0 |
exercitussolus/yolo | src/main/java/org/elasticsearch/index/analysis/AnalysisService.java | 14624 | /*
* Licensed to ElasticSearch and Shay Banon under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. ElasticSearch 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.elasticsearch.index.analysis;
import com.google.common.collect.ImmutableMap;
import org.apache.lucene.analysis.Analyzer;
import org.elasticsearch.ElasticSearchIllegalArgumentException;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.Strings;
import org.elasticsearch.common.component.CloseableComponent;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.settings.ImmutableSettings;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.index.AbstractIndexComponent;
import org.elasticsearch.index.Index;
import org.elasticsearch.index.settings.IndexSettings;
import org.elasticsearch.indices.analysis.IndicesAnalysisService;
import java.util.Map;
import static com.google.common.collect.Maps.newHashMap;
/**
*
*/
public class AnalysisService extends AbstractIndexComponent implements CloseableComponent {
private final ImmutableMap<String, NamedAnalyzer> analyzers;
private final ImmutableMap<String, TokenizerFactory> tokenizers;
private final ImmutableMap<String, CharFilterFactory> charFilters;
private final ImmutableMap<String, TokenFilterFactory> tokenFilters;
private final NamedAnalyzer defaultAnalyzer;
private final NamedAnalyzer defaultIndexAnalyzer;
private final NamedAnalyzer defaultSearchAnalyzer;
private final NamedAnalyzer defaultSearchQuoteAnalyzer;
public AnalysisService(Index index) {
this(index, ImmutableSettings.Builder.EMPTY_SETTINGS, null, null, null, null, null);
}
@Inject
public AnalysisService(Index index, @IndexSettings Settings indexSettings, @Nullable IndicesAnalysisService indicesAnalysisService,
@Nullable Map<String, AnalyzerProviderFactory> analyzerFactoryFactories,
@Nullable Map<String, TokenizerFactoryFactory> tokenizerFactoryFactories,
@Nullable Map<String, CharFilterFactoryFactory> charFilterFactoryFactories,
@Nullable Map<String, TokenFilterFactoryFactory> tokenFilterFactoryFactories) {
super(index, indexSettings);
Map<String, TokenizerFactory> tokenizers = newHashMap();
if (tokenizerFactoryFactories != null) {
Map<String, Settings> tokenizersSettings = indexSettings.getGroups("index.analysis.tokenizer");
for (Map.Entry<String, TokenizerFactoryFactory> entry : tokenizerFactoryFactories.entrySet()) {
String tokenizerName = entry.getKey();
TokenizerFactoryFactory tokenizerFactoryFactory = entry.getValue();
Settings tokenizerSettings = tokenizersSettings.get(tokenizerName);
if (tokenizerSettings == null) {
tokenizerSettings = ImmutableSettings.Builder.EMPTY_SETTINGS;
}
TokenizerFactory tokenizerFactory = tokenizerFactoryFactory.create(tokenizerName, tokenizerSettings);
tokenizers.put(tokenizerName, tokenizerFactory);
tokenizers.put(Strings.toCamelCase(tokenizerName), tokenizerFactory);
}
}
if (indicesAnalysisService != null) {
for (Map.Entry<String, PreBuiltTokenizerFactoryFactory> entry : indicesAnalysisService.tokenizerFactories().entrySet()) {
String name = entry.getKey();
if (!tokenizers.containsKey(name)) {
tokenizers.put(name, entry.getValue().create(name, ImmutableSettings.Builder.EMPTY_SETTINGS));
}
name = Strings.toCamelCase(entry.getKey());
if (!name.equals(entry.getKey())) {
if (!tokenizers.containsKey(name)) {
tokenizers.put(name, entry.getValue().create(name, ImmutableSettings.Builder.EMPTY_SETTINGS));
}
}
}
}
this.tokenizers = ImmutableMap.copyOf(tokenizers);
Map<String, CharFilterFactory> charFilters = newHashMap();
if (charFilterFactoryFactories != null) {
Map<String, Settings> charFiltersSettings = indexSettings.getGroups("index.analysis.char_filter");
for (Map.Entry<String, CharFilterFactoryFactory> entry : charFilterFactoryFactories.entrySet()) {
String charFilterName = entry.getKey();
CharFilterFactoryFactory charFilterFactoryFactory = entry.getValue();
Settings charFilterSettings = charFiltersSettings.get(charFilterName);
if (charFilterSettings == null) {
charFilterSettings = ImmutableSettings.Builder.EMPTY_SETTINGS;
}
CharFilterFactory tokenFilterFactory = charFilterFactoryFactory.create(charFilterName, charFilterSettings);
charFilters.put(charFilterName, tokenFilterFactory);
charFilters.put(Strings.toCamelCase(charFilterName), tokenFilterFactory);
}
}
if (indicesAnalysisService != null) {
for (Map.Entry<String, PreBuiltCharFilterFactoryFactory> entry : indicesAnalysisService.charFilterFactories().entrySet()) {
String name = entry.getKey();
if (!charFilters.containsKey(name)) {
charFilters.put(name, entry.getValue().create(name, ImmutableSettings.Builder.EMPTY_SETTINGS));
}
name = Strings.toCamelCase(entry.getKey());
if (!name.equals(entry.getKey())) {
if (!charFilters.containsKey(name)) {
charFilters.put(name, entry.getValue().create(name, ImmutableSettings.Builder.EMPTY_SETTINGS));
}
}
}
}
this.charFilters = ImmutableMap.copyOf(charFilters);
Map<String, TokenFilterFactory> tokenFilters = newHashMap();
if (tokenFilterFactoryFactories != null) {
Map<String, Settings> tokenFiltersSettings = indexSettings.getGroups("index.analysis.filter");
for (Map.Entry<String, TokenFilterFactoryFactory> entry : tokenFilterFactoryFactories.entrySet()) {
String tokenFilterName = entry.getKey();
TokenFilterFactoryFactory tokenFilterFactoryFactory = entry.getValue();
Settings tokenFilterSettings = tokenFiltersSettings.get(tokenFilterName);
if (tokenFilterSettings == null) {
tokenFilterSettings = ImmutableSettings.Builder.EMPTY_SETTINGS;
}
TokenFilterFactory tokenFilterFactory = tokenFilterFactoryFactory.create(tokenFilterName, tokenFilterSettings);
tokenFilters.put(tokenFilterName, tokenFilterFactory);
tokenFilters.put(Strings.toCamelCase(tokenFilterName), tokenFilterFactory);
}
}
// pre initialize the globally registered ones into the map
if (indicesAnalysisService != null) {
for (Map.Entry<String, PreBuiltTokenFilterFactoryFactory> entry : indicesAnalysisService.tokenFilterFactories().entrySet()) {
String name = entry.getKey();
if (!tokenFilters.containsKey(name)) {
tokenFilters.put(name, entry.getValue().create(name, ImmutableSettings.Builder.EMPTY_SETTINGS));
}
name = Strings.toCamelCase(entry.getKey());
if (!name.equals(entry.getKey())) {
if (!tokenFilters.containsKey(name)) {
tokenFilters.put(name, entry.getValue().create(name, ImmutableSettings.Builder.EMPTY_SETTINGS));
}
}
}
}
this.tokenFilters = ImmutableMap.copyOf(tokenFilters);
Map<String, AnalyzerProvider> analyzerProviders = newHashMap();
if (analyzerFactoryFactories != null) {
Map<String, Settings> analyzersSettings = indexSettings.getGroups("index.analysis.analyzer");
for (Map.Entry<String, AnalyzerProviderFactory> entry : analyzerFactoryFactories.entrySet()) {
String analyzerName = entry.getKey();
AnalyzerProviderFactory analyzerFactoryFactory = entry.getValue();
Settings analyzerSettings = analyzersSettings.get(analyzerName);
if (analyzerSettings == null) {
analyzerSettings = ImmutableSettings.Builder.EMPTY_SETTINGS;
}
AnalyzerProvider analyzerFactory = analyzerFactoryFactory.create(analyzerName, analyzerSettings);
analyzerProviders.put(analyzerName, analyzerFactory);
}
}
if (indicesAnalysisService != null) {
for (Map.Entry<String, PreBuiltAnalyzerProviderFactory> entry : indicesAnalysisService.analyzerProviderFactories().entrySet()) {
String name = entry.getKey();
if (!analyzerProviders.containsKey(name)) {
analyzerProviders.put(name, entry.getValue().create(name, ImmutableSettings.Builder.EMPTY_SETTINGS));
}
name = Strings.toCamelCase(entry.getKey());
if (!name.equals(entry.getKey())) {
if (!analyzerProviders.containsKey(name)) {
analyzerProviders.put(name, entry.getValue().create(name, ImmutableSettings.Builder.EMPTY_SETTINGS));
}
}
}
}
if (!analyzerProviders.containsKey("default")) {
analyzerProviders.put("default", new StandardAnalyzerProvider(index, indexSettings, null, "default", ImmutableSettings.Builder.EMPTY_SETTINGS));
}
if (!analyzerProviders.containsKey("default_index")) {
analyzerProviders.put("default_index", analyzerProviders.get("default"));
}
if (!analyzerProviders.containsKey("default_search")) {
analyzerProviders.put("default_search", analyzerProviders.get("default"));
}
if (!analyzerProviders.containsKey("default_search_quoted")) {
analyzerProviders.put("default_search_quoted", analyzerProviders.get("default_search"));
}
Map<String, NamedAnalyzer> analyzers = newHashMap();
for (AnalyzerProvider analyzerFactory : analyzerProviders.values()) {
if (analyzerFactory instanceof CustomAnalyzerProvider) {
((CustomAnalyzerProvider) analyzerFactory).build(this);
}
Analyzer analyzerF = analyzerFactory.get();
if (analyzerF == null) {
throw new ElasticSearchIllegalArgumentException("analyzer [" + analyzerFactory.name() + "] created null analyzer");
}
NamedAnalyzer analyzer;
// if we got a named analyzer back, use it...
if (analyzerF instanceof NamedAnalyzer) {
analyzer = (NamedAnalyzer) analyzerF;
} else {
analyzer = new NamedAnalyzer(analyzerFactory.name(), analyzerFactory.scope(), analyzerF);
}
analyzers.put(analyzerFactory.name(), analyzer);
analyzers.put(Strings.toCamelCase(analyzerFactory.name()), analyzer);
String strAliases = indexSettings.get("index.analysis.analyzer." + analyzerFactory.name() + ".alias");
if (strAliases != null) {
for (String alias : Strings.commaDelimitedListToStringArray(strAliases)) {
analyzers.put(alias, analyzer);
}
}
String[] aliases = indexSettings.getAsArray("index.analysis.analyzer." + analyzerFactory.name() + ".alias");
for (String alias : aliases) {
analyzers.put(alias, analyzer);
}
}
defaultAnalyzer = analyzers.get("default");
if (defaultAnalyzer == null) {
throw new ElasticSearchIllegalArgumentException("no default analyzer configured");
}
defaultIndexAnalyzer = analyzers.containsKey("default_index") ? analyzers.get("default_index") : analyzers.get("default");
defaultSearchAnalyzer = analyzers.containsKey("default_search") ? analyzers.get("default_search") : analyzers.get("default");
defaultSearchQuoteAnalyzer = analyzers.containsKey("default_search_quote") ? analyzers.get("default_search_quote") : defaultSearchAnalyzer;
this.analyzers = ImmutableMap.copyOf(analyzers);
}
public void close() {
for (NamedAnalyzer analyzer : analyzers.values()) {
if (analyzer.scope() == AnalyzerScope.INDEX) {
try {
analyzer.close();
} catch (NullPointerException e) {
// because analyzers are aliased, they might be closed several times
// an NPE is thrown in this case, so ignore....
} catch (Exception e) {
logger.debug("failed to close analyzer " + analyzer);
}
}
}
}
public NamedAnalyzer analyzer(String name) {
return analyzers.get(name);
}
public NamedAnalyzer defaultAnalyzer() {
return defaultAnalyzer;
}
public NamedAnalyzer defaultIndexAnalyzer() {
return defaultIndexAnalyzer;
}
public NamedAnalyzer defaultSearchAnalyzer() {
return defaultSearchAnalyzer;
}
public NamedAnalyzer defaultSearchQuoteAnalyzer() {
return defaultSearchQuoteAnalyzer;
}
public TokenizerFactory tokenizer(String name) {
return tokenizers.get(name);
}
public CharFilterFactory charFilter(String name) {
return charFilters.get(name);
}
public TokenFilterFactory tokenFilter(String name) {
return tokenFilters.get(name);
}
}
| agpl-3.0 |
erdincay/ejb | src/com/lp/server/schema/opentrans/cc/orderresponse/XMLXMLCOSTCATEGORYID.java | 5991 | /*******************************************************************************
* HELIUM V, Open Source ERP software for sustained success
* at small and medium-sized enterprises.
* Copyright (C) 2004 - 2015 HELIUM V IT-Solutions GmbH
*
* 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 theLicense, or
* (at your option) any later version.
*
* According to sec. 7 of the GNU Affero General Public License, version 3,
* the terms of the AGPL are supplemented with the following terms:
*
* "HELIUM V" and "HELIUM 5" are registered trademarks of
* HELIUM V IT-Solutions GmbH. The licensing of the program under the
* AGPL does not imply a trademark license. Therefore any rights, title and
* interest in our trademarks remain entirely with us. If you want to propagate
* modified versions of the Program under the name "HELIUM V" or "HELIUM 5",
* you may only do so if you have a written permission by HELIUM V IT-Solutions
* GmbH (to acquire a permission please contact HELIUM V IT-Solutions
* at trademark@heliumv.com).
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*
* Contact: developers@heliumv.com
******************************************************************************/
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, vJAXB 2.1.10 in JDK 6
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2012.12.03 at 10:12:07 AM MEZ
//
package com.lp.server.schema.opentrans.cc.orderresponse;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlValue;
import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
/**
* <p>Java class for _XML_XML_COST_CATEGORY_ID complex type.
*
* <p>The following schema fragment specifies the expected content contained within this class.
*
* <pre>
* <complexType name="_XML_XML_COST_CATEGORY_ID">
* <simpleContent>
* <extension base="<http://www.opentrans.org/XMLSchema/1.0>typeCOST_CATEGORY_ID">
* <attGroup ref="{http://www.opentrans.org/XMLSchema/1.0}ComIbmMrmNamespaceInfo154"/>
* <attribute name="type">
* <simpleType>
* <restriction base="{http://www.w3.org/2001/XMLSchema}NMTOKEN">
* <minLength value="1"/>
* <maxLength value="32"/>
* <enumeration value="cost_center"/>
* <enumeration value="project"/>
* </restriction>
* </simpleType>
* </attribute>
* </extension>
* </simpleContent>
* </complexType>
* </pre>
*
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "_XML_XML_COST_CATEGORY_ID", propOrder = {
"value"
})
public class XMLXMLCOSTCATEGORYID {
@XmlValue
protected String value;
@XmlAttribute
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
protected String type;
@XmlAttribute(name = "xsi_schemaLocation")
protected String xsiSchemaLocation;
@XmlAttribute(name = "xmlns_xsd")
protected String xmlnsXsd;
/**
* Gets the value of the value property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getValue() {
return value;
}
/**
* Sets the value of the value property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setValue(String value) {
this.value = value;
}
/**
* Gets the value of the type property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getType() {
return type;
}
/**
* Sets the value of the type property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setType(String value) {
this.type = value;
}
/**
* Gets the value of the xsiSchemaLocation property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getXsiSchemaLocation() {
if (xsiSchemaLocation == null) {
return "openbase_1_0.mxsd";
} else {
return xsiSchemaLocation;
}
}
/**
* Sets the value of the xsiSchemaLocation property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setXsiSchemaLocation(String value) {
this.xsiSchemaLocation = value;
}
/**
* Gets the value of the xmlnsXsd property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getXmlnsXsd() {
if (xmlnsXsd == null) {
return "http://www.w3.org/2001/XMLSchema";
} else {
return xmlnsXsd;
}
}
/**
* Sets the value of the xmlnsXsd property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setXmlnsXsd(String value) {
this.xmlnsXsd = value;
}
}
| agpl-3.0 |
at88mph/web | cadc-web-util/src/test/java/org/opencadc/proxy/ProxyServletTest.java | 9512 |
/*
************************************************************************
******************* CANADIAN ASTRONOMY DATA CENTRE *******************
************** CENTRE CANADIEN DE DONNÉES ASTRONOMIQUES **************
*
* (c) 2019. (c) 2019.
* Government of Canada Gouvernement du Canada
* National Research Council Conseil national de recherches
* Ottawa, Canada, K1A 0R6 Ottawa, Canada, K1A 0R6
* All rights reserved Tous droits réservés
*
* NRC disclaims any warranties, Le CNRC dénie toute garantie
* expressed, implied, or énoncée, implicite ou légale,
* statutory, of any kind with de quelque nature que ce
* respect to the software, soit, concernant le logiciel,
* including without limitation y compris sans restriction
* any warranty of merchantability toute garantie de valeur
* or fitness for a particular marchande ou de pertinence
* purpose. NRC shall not be pour un usage particulier.
* liable in any event for any Le CNRC ne pourra en aucun cas
* damages, whether direct or être tenu responsable de tout
* indirect, special or general, dommage, direct ou indirect,
* consequential or incidental, particulier ou général,
* arising from the use of the accessoire ou fortuit, résultant
* software. Neither the name de l'utilisation du logiciel. Ni
* of the National Research le nom du Conseil National de
* Council of Canada nor the Recherches du Canada ni les noms
* names of its contributors may de ses participants ne peuvent
* be used to endorse or promote être utilisés pour approuver ou
* products derived from this promouvoir les produits dérivés
* software without specific prior de ce logiciel sans autorisation
* written permission. préalable et particulière
* par écrit.
*
* This file is part of the Ce fichier fait partie du projet
* OpenCADC project. OpenCADC.
*
* OpenCADC is free software: OpenCADC est un logiciel libre ;
* you can redistribute it and/or vous pouvez le redistribuer ou le
* modify it under the terms of modifier suivant les termes de
* the GNU Affero General Public la “GNU Affero General Public
* License as published by the License” telle que publiée
* Free Software Foundation, par la Free Software Foundation
* either version 3 of the : soit la version 3 de cette
* License, or (at your option) licence, soit (à votre gré)
* any later version. toute version ultérieure.
*
* OpenCADC is distributed in the OpenCADC est distribué
* hope that it will be useful, dans l’espoir qu’il vous
* but WITHOUT ANY WARRANTY; sera utile, mais SANS AUCUNE
* without even the implied GARANTIE : sans même la garantie
* warranty of MERCHANTABILITY implicite de COMMERCIALISABILITÉ
* or FITNESS FOR A PARTICULAR ni d’ADÉQUATION À UN OBJECTIF
* PURPOSE. See the GNU Affero PARTICULIER. Consultez la Licence
* General Public License for Générale Publique GNU Affero
* more details. pour plus de détails.
*
* You should have received Vous devriez avoir reçu une
* a copy of the GNU Affero copie de la Licence Générale
* General Public License along Publique GNU Affero avec
* with OpenCADC. If not, see OpenCADC ; si ce n’est
* <http://www.gnu.org/licenses/>. pas le cas, consultez :
* <http://www.gnu.org/licenses/>.
*
*
************************************************************************
*/
package org.opencadc.proxy;
import ca.nrc.cadc.auth.AuthMethod;
import ca.nrc.cadc.reg.client.RegistryClient;
import java.net.URI;
import java.net.URL;
import org.junit.Test;
import org.junit.Assert;
import static org.mockito.Mockito.*;
public class ProxyServletTest {
@Test
public void lookupServiceURL() throws Exception {
final RegistryClient mockRegistryClient = mock(RegistryClient.class);
final ProxyServlet testSubject = new ProxyServlet() {
/**
* Useful for overriding in tests.
*
* @return RegistryClient instance. Never null.
*/
@Override
RegistryClient getRegistryClient() {
return mockRegistryClient;
}
};
final URL lookedUpServiceURL = new URL("https://www.services.com/myservice");
final ServiceParameterMap serviceParameterMap = new ServiceParameterMap();
serviceParameterMap.put(ServiceParameterName.RESOURCE_ID, "ivo://cadc.nrc.ca/resource");
serviceParameterMap.put(ServiceParameterName.STANDARD_ID, "ivo://cadc.nrc.ca/mystandard");
serviceParameterMap.put(ServiceParameterName.INTERFACE_TYPE_ID, "ivo://cadc.nrc.ca/interface#https");
serviceParameterMap.put(ServiceParameterName.AUTH_TYPE, "cookie");
when(mockRegistryClient.getServiceURL(URI.create("ivo://cadc.nrc.ca/resource"),
URI.create("ivo://cadc.nrc.ca/mystandard"),
AuthMethod.COOKIE,
URI.create("ivo://cadc.nrc.ca/interface#https"))).thenReturn(
lookedUpServiceURL);
final URL result = testSubject.lookupServiceURL(serviceParameterMap);
Assert.assertEquals("URLs do not match.", lookedUpServiceURL, result);
}
@Test
public void lookupServiceURLWithPath() throws Exception {
final RegistryClient mockRegistryClient = mock(RegistryClient.class);
final ProxyServlet testSubject = new ProxyServlet() {
/**
* Useful for overriding in tests.
*
* @return RegistryClient instance. Never null.
*/
@Override
RegistryClient getRegistryClient() {
return mockRegistryClient;
}
};
final URL lookedUpServiceURL = new URL("https://www.services.com/myservice");
final ServiceParameterMap serviceParameterMap = new ServiceParameterMap();
serviceParameterMap.put(ServiceParameterName.RESOURCE_ID, "ivo://cadc.nrc.ca/resource");
serviceParameterMap.put(ServiceParameterName.STANDARD_ID, "ivo://cadc.nrc.ca/mystandard");
serviceParameterMap.put(ServiceParameterName.INTERFACE_TYPE_ID, "ivo://cadc.nrc.ca/interface#https");
serviceParameterMap.put(ServiceParameterName.AUTH_TYPE, "anon");
serviceParameterMap.put(ServiceParameterName.EXTRA_PATH, "alt-site");
when(mockRegistryClient.getServiceURL(URI.create("ivo://cadc.nrc.ca/resource"),
URI.create("ivo://cadc.nrc.ca/mystandard"),
AuthMethod.ANON,
URI.create("ivo://cadc.nrc.ca/interface#https"))).thenReturn(
lookedUpServiceURL);
final URL result = testSubject.lookupServiceURL(serviceParameterMap);
final URL expected = new URL("https://www.services.com/myservice/alt-site");
Assert.assertEquals("URLs do not match.", expected, result);
}
@Test
public void lookupServiceURLWithPathQuery() throws Exception {
final RegistryClient mockRegistryClient = mock(RegistryClient.class);
final ProxyServlet testSubject = new ProxyServlet() {
/**
* Useful for overriding in tests.
*
* @return RegistryClient instance. Never null.
*/
@Override
RegistryClient getRegistryClient() {
return mockRegistryClient;
}
};
final URL lookedUpServiceURL = new URL("https://www.services.com/myservice");
final ServiceParameterMap serviceParameterMap = new ServiceParameterMap();
serviceParameterMap.put(ServiceParameterName.RESOURCE_ID, "ivo://cadc.nrc.ca/resource");
serviceParameterMap.put(ServiceParameterName.STANDARD_ID, "ivo://cadc.nrc.ca/mystandard");
serviceParameterMap.put(ServiceParameterName.INTERFACE_TYPE_ID, "ivo://cadc.nrc.ca/interface#https");
serviceParameterMap.put(ServiceParameterName.AUTH_TYPE, "anon");
serviceParameterMap.put(ServiceParameterName.EXTRA_PATH, "alt-site");
serviceParameterMap.put(ServiceParameterName.EXTRA_QUERY, "myquery=a&g=j");
when(mockRegistryClient.getServiceURL(URI.create("ivo://cadc.nrc.ca/resource"),
URI.create("ivo://cadc.nrc.ca/mystandard"),
AuthMethod.ANON,
URI.create("ivo://cadc.nrc.ca/interface#https"))).thenReturn(
lookedUpServiceURL);
final URL result = testSubject.lookupServiceURL(serviceParameterMap);
final URL expected = new URL("https://www.services.com/myservice/alt-site?myquery=a&g=j");
Assert.assertEquals("URLs do not match.", expected, result);
}
}
| agpl-3.0 |
shook2012/focus-sns | connect-service/src/main/java/org/osforce/connect/service/system/ProjectFeatureService.java | 562 | package org.osforce.connect.service.system;
import org.osforce.connect.entity.system.ProjectFeature;
/**
*
* @author gavin
* @since 1.0.0
* @create Feb 12, 2011 - 9:23:35 PM
* <a href="http://www.opensourceforce.org">开源力量</a>
*/
public interface ProjectFeatureService {
ProjectFeature getProjectFeature(Long featureId);
ProjectFeature getProjectFeature(String code, Long projectId);
void createProjectFeature(ProjectFeature feature);
void updateProjectFeature(ProjectFeature feature);
void deleteProjectFeature(Long featureId);
}
| agpl-3.0 |
sandrineBeauche/scheduling | scheduler/scheduler-server/src/test/java/functionaltests/job/TestTaskNotRestarted.java | 2532 | package functionaltests.job;
import java.io.Serializable;
import org.ow2.proactive.scheduler.common.Scheduler;
import org.ow2.proactive.scheduler.common.job.JobId;
import org.ow2.proactive.scheduler.common.job.JobState;
import org.ow2.proactive.scheduler.common.job.TaskFlowJob;
import org.ow2.proactive.scheduler.common.task.JavaTask;
import org.ow2.proactive.scheduler.common.task.TaskResult;
import org.ow2.proactive.scheduler.common.task.TaskStatus;
import org.ow2.proactive.scheduler.common.task.executable.JavaExecutable;
import org.junit.Test;
import functionaltests.utils.SchedulerFunctionalTest;
import static org.junit.Assert.*;
/**
* Test provokes scenario when task gets 'NOT_RESTARTED' status:
* - task is submitted and starts execution
* - user requests to restart task with some delay
* - before task was restarted job is killed
*
*/
public class TestTaskNotRestarted extends SchedulerFunctionalTest {
public static class TestJavaTask extends JavaExecutable {
@Override
public Serializable execute(TaskResult... results) throws Throwable {
Thread.sleep(Long.MAX_VALUE);
return "OK";
}
}
@Test
public void test() throws Exception {
Scheduler scheduler = schedulerHelper.getSchedulerInterface();
JobId jobId = scheduler.submit(createJob());
JobState jobState;
schedulerHelper.waitForEventTaskRunning(jobId, "task1");
jobState = scheduler.getJobState(jobId);
assertEquals(1, jobState.getTasks().size());
assertEquals(TaskStatus.RUNNING, jobState.getTasks().get(0).getStatus());
scheduler.restartTask(jobId, "task1", Integer.MAX_VALUE);
jobState = scheduler.getJobState(jobId);
assertEquals(1, jobState.getTasks().size());
assertEquals(TaskStatus.WAITING_ON_ERROR, jobState.getTasks().get(0).getStatus());
scheduler.killJob(jobId);
jobState = scheduler.getJobState(jobId);
assertEquals(1, jobState.getTasks().size());
assertEquals(TaskStatus.NOT_RESTARTED, jobState.getTasks().get(0).getStatus());
}
private TaskFlowJob createJob() throws Exception {
TaskFlowJob job = new TaskFlowJob();
job.setName(this.getClass().getSimpleName());
JavaTask javaTask = new JavaTask();
javaTask.setExecutableClassName(TestJavaTask.class.getName());
javaTask.setName("task1");
javaTask.setMaxNumberOfExecution(10);
job.addTask(javaTask);
return job;
}
}
| agpl-3.0 |
migue/voltdb | src/frontend/org/voltdb/VLog.java | 1623 | /* This file is part of VoltDB.
* Copyright (C) 2008-2017 VoltDB Inc.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with VoltDB. If not, see <http://www.gnu.org/licenses/>.
*/
package org.voltdb;
import java.io.File;
/**
* This file isn't long for this world. It's just something I've been using
* to debug multi-process rejoin stuff.
*
*/
public class VLog {
static File m_logfile = new File("vlog.txt");
public synchronized static void setPortNo(int portNo) {
m_logfile = new File(String.format("vlog-%d.txt", portNo));
}
public synchronized static void log(String str) {
// turn off this stupid thing for now
/*try {
FileWriter log = new FileWriter(m_logfile, true);
log.write(str + "\n");
log.flush();
log.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}*/
}
public static void log(String format, Object... args) {
log(String.format(format, args));
}
}
| agpl-3.0 |
kaltura/KalturaGeneratedAPIClientsJava | src/main/java/com/kaltura/client/enums/BeaconIndexType.java | 2312 | // ===================================================================================================
// _ __ _ _
// | |/ /__ _| | |_ _ _ _ _ __ _
// | ' </ _` | | _| || | '_/ _` |
// |_|\_\__,_|_|\__|\_,_|_| \__,_|
//
// This file is part of the Kaltura Collaborative Media Suite which allows users
// to do with audio, video, and animation what Wiki platforms allow them to do with
// text.
//
// Copyright (C) 2006-2022 Kaltura Inc.
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU Affero General Public License as
// published by the Free Software Foundation, either version 3 of the
// License, or (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU Affero General Public License for more details.
//
// You should have received a copy of the GNU Affero General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
//
// @ignore
// ===================================================================================================
package com.kaltura.client.enums;
/**
* This class was generated using generate.php
* against an XML schema provided by Kaltura.
*
* MANUAL CHANGES TO THIS CLASS WILL BE OVERWRITTEN.
*/
public enum BeaconIndexType implements EnumAsString {
LOG("Log"),
STATE("State");
private String value;
BeaconIndexType(String value) {
this.value = value;
}
@Override
public String getValue() {
return this.value;
}
public void setValue(String value) {
this.value = value;
}
public static BeaconIndexType get(String value) {
if(value == null)
{
return null;
}
// goes over BeaconIndexType defined values and compare the inner value with the given one:
for(BeaconIndexType item: values()) {
if(item.getValue().equals(value)) {
return item;
}
}
// in case the requested value was not found in the enum values, we return the first item as default.
return BeaconIndexType.values().length > 0 ? BeaconIndexType.values()[0]: null;
}
}
| agpl-3.0 |
FreudianNM/openMAXIMS | Source Library/openmaxims_workspace/ValueObjects/src/ims/admin/vo/domain/ConfigLocationLiteVoAssembler.java | 19428 | //#############################################################################
//# #
//# Copyright (C) <2015> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of #
//# this program. Users of this software do so entirely at their own risk. #
//# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time #
//# software that it builds, deploys and maintains. #
//# #
//#############################################################################
//#EOH
/*
* This code was generated
* Copyright (C) 1995-2004 IMS MAXIMS plc. All rights reserved.
* IMS Development Environment (version 1.80 build 5589.25814)
* WARNING: DO NOT MODIFY the content of this file
* Generated on 12/10/2015, 13:24
*
*/
package ims.admin.vo.domain;
import ims.vo.domain.DomainObjectMap;
import java.util.HashMap;
import org.hibernate.proxy.HibernateProxy;
/**
* @author Cornel Ventuneac
*/
public class ConfigLocationLiteVoAssembler
{
/**
* Copy one ValueObject to another
* @param valueObjectDest to be updated
* @param valueObjectSrc to copy values from
*/
public static ims.admin.vo.ConfigLocationLiteVo copy(ims.admin.vo.ConfigLocationLiteVo valueObjectDest, ims.admin.vo.ConfigLocationLiteVo valueObjectSrc)
{
if (null == valueObjectSrc)
{
return valueObjectSrc;
}
valueObjectDest.setID_Location(valueObjectSrc.getID_Location());
valueObjectDest.setIsRIE(valueObjectSrc.getIsRIE());
// Name
valueObjectDest.setName(valueObjectSrc.getName());
// Type
valueObjectDest.setType(valueObjectSrc.getType());
// isActive
valueObjectDest.setIsActive(valueObjectSrc.getIsActive());
// Address
valueObjectDest.setAddress(valueObjectSrc.getAddress());
// IsVirtual
valueObjectDest.setIsVirtual(valueObjectSrc.getIsVirtual());
return valueObjectDest;
}
/**
* Create the ValueObject collection to hold the set of DomainObjects.
* This is a convenience method only.
* It is intended to be used when one called to an Assembler is made.
* If more than one call to an Assembler is made then #createConfigLocationLiteVoCollectionFromLocation(DomainObjectMap, Set) should be used.
* @param domainObjectSet - Set of ims.core.resource.place.domain.objects.Location objects.
*/
public static ims.admin.vo.ConfigLocationLiteVoCollection createConfigLocationLiteVoCollectionFromLocation(java.util.Set domainObjectSet)
{
return createConfigLocationLiteVoCollectionFromLocation(new DomainObjectMap(), domainObjectSet);
}
/**
* Create the ValueObject collection to hold the set of DomainObjects.
* @param map - maps DomainObjects to created ValueObjects
* @param domainObjectSet - Set of ims.core.resource.place.domain.objects.Location objects.
*/
public static ims.admin.vo.ConfigLocationLiteVoCollection createConfigLocationLiteVoCollectionFromLocation(DomainObjectMap map, java.util.Set domainObjectSet)
{
ims.admin.vo.ConfigLocationLiteVoCollection voList = new ims.admin.vo.ConfigLocationLiteVoCollection();
if ( null == domainObjectSet )
{
return voList;
}
int rieCount=0;
int activeCount=0;
java.util.Iterator iterator = domainObjectSet.iterator();
while( iterator.hasNext() )
{
ims.core.resource.place.domain.objects.Location domainObject = (ims.core.resource.place.domain.objects.Location) iterator.next();
ims.admin.vo.ConfigLocationLiteVo vo = create(map, domainObject);
if (vo != null)
voList.add(vo);
if (domainObject != null)
{
if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true)
rieCount++;
else
activeCount++;
}
}
voList.setRieCount(rieCount);
voList.setActiveCount(activeCount);
return voList;
}
/**
* Create the ValueObject collection to hold the list of DomainObjects.
* @param domainObjectList - List of ims.core.resource.place.domain.objects.Location objects.
*/
public static ims.admin.vo.ConfigLocationLiteVoCollection createConfigLocationLiteVoCollectionFromLocation(java.util.List domainObjectList)
{
return createConfigLocationLiteVoCollectionFromLocation(new DomainObjectMap(), domainObjectList);
}
/**
* Create the ValueObject collection to hold the list of DomainObjects.
* @param map - maps DomainObjects to created ValueObjects
* @param domainObjectList - List of ims.core.resource.place.domain.objects.Location objects.
*/
public static ims.admin.vo.ConfigLocationLiteVoCollection createConfigLocationLiteVoCollectionFromLocation(DomainObjectMap map, java.util.List domainObjectList)
{
ims.admin.vo.ConfigLocationLiteVoCollection voList = new ims.admin.vo.ConfigLocationLiteVoCollection();
if ( null == domainObjectList )
{
return voList;
}
int rieCount=0;
int activeCount=0;
for (int i = 0; i < domainObjectList.size(); i++)
{
ims.core.resource.place.domain.objects.Location domainObject = (ims.core.resource.place.domain.objects.Location) domainObjectList.get(i);
ims.admin.vo.ConfigLocationLiteVo vo = create(map, domainObject);
if (vo != null)
voList.add(vo);
if (domainObject != null)
{
if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true)
rieCount++;
else
activeCount++;
}
}
voList.setRieCount(rieCount);
voList.setActiveCount(activeCount);
return voList;
}
/**
* Create the ims.core.resource.place.domain.objects.Location set from the value object collection.
* @param domainFactory - used to create existing (persistent) domain objects.
* @param voCollection - the collection of value objects
*/
public static java.util.Set extractLocationSet(ims.domain.ILightweightDomainFactory domainFactory, ims.admin.vo.ConfigLocationLiteVoCollection voCollection)
{
return extractLocationSet(domainFactory, voCollection, null, new HashMap());
}
public static java.util.Set extractLocationSet(ims.domain.ILightweightDomainFactory domainFactory, ims.admin.vo.ConfigLocationLiteVoCollection voCollection, java.util.Set domainObjectSet, HashMap domMap)
{
int size = (null == voCollection) ? 0 : voCollection.size();
if (domainObjectSet == null)
{
domainObjectSet = new java.util.HashSet();
}
java.util.Set newSet = new java.util.HashSet();
for(int i=0; i<size; i++)
{
ims.admin.vo.ConfigLocationLiteVo vo = voCollection.get(i);
ims.core.resource.place.domain.objects.Location domainObject = ConfigLocationLiteVoAssembler.extractLocation(domainFactory, vo, domMap);
//TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it.
if (domainObject == null)
{
continue;
}
//Trying to avoid the hibernate collection being marked as dirty via its public interface methods. (like add)
if (!domainObjectSet.contains(domainObject)) domainObjectSet.add(domainObject);
newSet.add(domainObject);
}
java.util.Set removedSet = new java.util.HashSet();
java.util.Iterator iter = domainObjectSet.iterator();
//Find out which objects need to be removed
while (iter.hasNext())
{
ims.domain.DomainObject o = (ims.domain.DomainObject)iter.next();
if ((o == null || o.getIsRIE() == null || !o.getIsRIE().booleanValue()) && !newSet.contains(o))
{
removedSet.add(o);
}
}
iter = removedSet.iterator();
//Remove the unwanted objects
while (iter.hasNext())
{
domainObjectSet.remove(iter.next());
}
return domainObjectSet;
}
/**
* Create the ims.core.resource.place.domain.objects.Location list from the value object collection.
* @param domainFactory - used to create existing (persistent) domain objects.
* @param voCollection - the collection of value objects
*/
public static java.util.List extractLocationList(ims.domain.ILightweightDomainFactory domainFactory, ims.admin.vo.ConfigLocationLiteVoCollection voCollection)
{
return extractLocationList(domainFactory, voCollection, null, new HashMap());
}
public static java.util.List extractLocationList(ims.domain.ILightweightDomainFactory domainFactory, ims.admin.vo.ConfigLocationLiteVoCollection voCollection, java.util.List domainObjectList, HashMap domMap)
{
int size = (null == voCollection) ? 0 : voCollection.size();
if (domainObjectList == null)
{
domainObjectList = new java.util.ArrayList();
}
for(int i=0; i<size; i++)
{
ims.admin.vo.ConfigLocationLiteVo vo = voCollection.get(i);
ims.core.resource.place.domain.objects.Location domainObject = ConfigLocationLiteVoAssembler.extractLocation(domainFactory, vo, domMap);
//TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it.
if (domainObject == null)
{
continue;
}
int domIdx = domainObjectList.indexOf(domainObject);
if (domIdx == -1)
{
domainObjectList.add(i, domainObject);
}
else if (i != domIdx && i < domainObjectList.size())
{
Object tmp = domainObjectList.get(i);
domainObjectList.set(i, domainObjectList.get(domIdx));
domainObjectList.set(domIdx, tmp);
}
}
//Remove all ones in domList where index > voCollection.size() as these should
//now represent the ones removed from the VO collection. No longer referenced.
int i1=domainObjectList.size();
while (i1 > size)
{
domainObjectList.remove(i1-1);
i1=domainObjectList.size();
}
return domainObjectList;
}
/**
* Create the ValueObject from the ims.core.resource.place.domain.objects.Location object.
* @param domainObject ims.core.resource.place.domain.objects.Location
*/
public static ims.admin.vo.ConfigLocationLiteVo create(ims.core.resource.place.domain.objects.Location domainObject)
{
if (null == domainObject)
{
return null;
}
DomainObjectMap map = new DomainObjectMap();
return create(map, domainObject);
}
/**
* Create the ValueObject from the ims.core.resource.place.domain.objects.Location object.
* @param map DomainObjectMap of DomainObjects to already created ValueObjects.
* @param domainObject
*/
public static ims.admin.vo.ConfigLocationLiteVo create(DomainObjectMap map, ims.core.resource.place.domain.objects.Location domainObject)
{
if (null == domainObject)
{
return null;
}
// check if the domainObject already has a valueObject created for it
ims.admin.vo.ConfigLocationLiteVo valueObject = (ims.admin.vo.ConfigLocationLiteVo) map.getValueObject(domainObject, ims.admin.vo.ConfigLocationLiteVo.class);
if ( null == valueObject )
{
valueObject = new ims.admin.vo.ConfigLocationLiteVo(domainObject.getId(), domainObject.getVersion());
map.addValueObject(domainObject, valueObject);
valueObject = insert(map, valueObject, domainObject);
}
return valueObject;
}
/**
* Update the ValueObject with the Domain Object.
* @param valueObject to be updated
* @param domainObject ims.core.resource.place.domain.objects.Location
*/
public static ims.admin.vo.ConfigLocationLiteVo insert(ims.admin.vo.ConfigLocationLiteVo valueObject, ims.core.resource.place.domain.objects.Location domainObject)
{
if (null == domainObject)
{
return valueObject;
}
DomainObjectMap map = new DomainObjectMap();
return insert(map, valueObject, domainObject);
}
/**
* Update the ValueObject with the Domain Object.
* @param map DomainObjectMap of DomainObjects to already created ValueObjects.
* @param valueObject to be updated
* @param domainObject ims.core.resource.place.domain.objects.Location
*/
public static ims.admin.vo.ConfigLocationLiteVo insert(DomainObjectMap map, ims.admin.vo.ConfigLocationLiteVo valueObject, ims.core.resource.place.domain.objects.Location domainObject)
{
if (null == domainObject)
{
return valueObject;
}
if (null == map)
{
map = new DomainObjectMap();
}
valueObject.setID_Location(domainObject.getId());
valueObject.setIsRIE(domainObject.getIsRIE());
// If this is a recordedInError record, and the domainObject
// value isIncludeRecord has not been set, then we return null and
// not the value object
if (valueObject.getIsRIE() != null && valueObject.getIsRIE().booleanValue() == true && !domainObject.isIncludeRecord())
return null;
// If this is not a recordedInError record, and the domainObject
// value isIncludeRecord has been set, then we return null and
// not the value object
if ((valueObject.getIsRIE() == null || valueObject.getIsRIE().booleanValue() == false) && domainObject.isIncludeRecord())
return null;
// Name
valueObject.setName(domainObject.getName());
// Type
ims.domain.lookups.LookupInstance instance2 = domainObject.getType();
if ( null != instance2 ) {
ims.framework.utils.ImagePath img = null;
ims.framework.utils.Color color = null;
img = null;
if (instance2.getImage() != null)
{
img = new ims.framework.utils.ImagePath(instance2.getImage().getImageId(), instance2.getImage().getImagePath());
}
color = instance2.getColor();
if (color != null)
color.getValue();
ims.core.vo.lookups.LocationType voLookup2 = new ims.core.vo.lookups.LocationType(instance2.getId(),instance2.getText(), instance2.isActive(), null, img, color);
ims.core.vo.lookups.LocationType parentVoLookup2 = voLookup2;
ims.domain.lookups.LookupInstance parent2 = instance2.getParent();
while (parent2 != null)
{
if (parent2.getImage() != null)
{
img = new ims.framework.utils.ImagePath(parent2.getImage().getImageId(), parent2.getImage().getImagePath() );
}
else
{
img = null;
}
color = parent2.getColor();
if (color != null)
color.getValue();
parentVoLookup2.setParent(new ims.core.vo.lookups.LocationType(parent2.getId(),parent2.getText(), parent2.isActive(), null, img, color));
parentVoLookup2 = parentVoLookup2.getParent();
parent2 = parent2.getParent();
}
valueObject.setType(voLookup2);
}
// isActive
valueObject.setIsActive( domainObject.isIsActive() );
// Address
valueObject.setAddress(ims.core.vo.domain.PersonAddressAssembler.create(map, domainObject.getAddress()) );
// IsVirtual
valueObject.setIsVirtual( domainObject.isIsVirtual() );
return valueObject;
}
/**
* Create the domain object from the value object.
* @param domainFactory - used to create existing (persistent) domain objects.
* @param valueObject - extract the domain object fields from this.
*/
public static ims.core.resource.place.domain.objects.Location extractLocation(ims.domain.ILightweightDomainFactory domainFactory, ims.admin.vo.ConfigLocationLiteVo valueObject)
{
return extractLocation(domainFactory, valueObject, new HashMap());
}
public static ims.core.resource.place.domain.objects.Location extractLocation(ims.domain.ILightweightDomainFactory domainFactory, ims.admin.vo.ConfigLocationLiteVo valueObject, HashMap domMap)
{
if (null == valueObject)
{
return null;
}
Integer id = valueObject.getID_Location();
ims.core.resource.place.domain.objects.Location domainObject = null;
if ( null == id)
{
if (domMap.get(valueObject) != null)
{
return (ims.core.resource.place.domain.objects.Location)domMap.get(valueObject);
}
// ims.admin.vo.ConfigLocationLiteVo ID_Location field is unknown
domainObject = new ims.core.resource.place.domain.objects.Location();
domMap.put(valueObject, domainObject);
}
else
{
String key = (valueObject.getClass().getName() + "__" + valueObject.getID_Location());
if (domMap.get(key) != null)
{
return (ims.core.resource.place.domain.objects.Location)domMap.get(key);
}
domainObject = (ims.core.resource.place.domain.objects.Location) domainFactory.getDomainObject(ims.core.resource.place.domain.objects.Location.class, id );
//TODO: Not sure how this should be handled. Effectively it must be a staleobject exception, but maybe should be handled as that further up.
if (domainObject == null)
return null;
domMap.put(key, domainObject);
}
domainObject.setVersion(valueObject.getVersion_Location());
//This is to overcome a bug in both Sybase and Oracle which prevents them from storing an empty string correctly
//Sybase stores it as a single space, Oracle stores it as NULL. This fix will make them consistent at least.
if (valueObject.getName() != null && valueObject.getName().equals(""))
{
valueObject.setName(null);
}
domainObject.setName(valueObject.getName());
// create LookupInstance from vo LookupType
ims.domain.lookups.LookupInstance value2 = null;
if ( null != valueObject.getType() )
{
value2 =
domainFactory.getLookupInstance(valueObject.getType().getID());
}
domainObject.setType(value2);
domainObject.setIsActive(valueObject.getIsActive());
// SaveAsRefVO - treated as a refVo in extract methods
ims.core.generic.domain.objects.Address value4 = null;
if ( null != valueObject.getAddress() )
{
if (valueObject.getAddress().getBoId() == null)
{
if (domMap.get(valueObject.getAddress()) != null)
{
value4 = (ims.core.generic.domain.objects.Address)domMap.get(valueObject.getAddress());
}
}
else
{
value4 = (ims.core.generic.domain.objects.Address)domainFactory.getDomainObject(ims.core.generic.domain.objects.Address.class, valueObject.getAddress().getBoId());
}
}
domainObject.setAddress(value4);
domainObject.setIsVirtual(valueObject.getIsVirtual());
return domainObject;
}
}
| agpl-3.0 |
mchlrch/ownprofile | org.ownprofile.node/src/main/java/org/ownprofile/boundary/owner/client/Result.java | 2101 | package org.ownprofile.boundary.owner.client;
public class Result<T> {
private boolean isSuccess;
private T successValue;
private Fail fail;
public static Result<Void> success() {
return success(null);
}
public static <S> Result<S> success(S successValue) {
return new Result<S>(successValue);
}
public static <S> Result<S> fail(String message) {
return fail((Throwable)null, "%s", message);
}
public static <S> Result<S> fail(Throwable cause, String message) {
return fail(cause, "%s", message);
}
public static <S> Result<S> fail(String format, Object... args) {
return fail(null, format, args);
}
public static <S> Result<S> fail(Throwable cause, String format, Object... args) {
final Fail f = new Fail(cause, format, args);
return new Result<S>(f);
}
private Result(T successValue) {
this.isSuccess = true;
this.successValue = successValue;
}
private Result(Fail fail) {
this.isSuccess = false;
this.fail = fail;
}
public boolean isSuccess() {
return isSuccess;
}
public boolean isFail() {
return !isSuccess;
}
public T getSuccessValue() {
if (isSuccess) {
return successValue;
} else {
throw new IllegalStateException(String.format("Result is Fail: %s", fail));
}
}
public Fail getFail() {
if (isSuccess) {
throw new IllegalStateException(String.format("Result is Success"));
} else {
return fail;
}
}
@Override
public String toString() {
return String.format("%s: %s",
isSuccess ? "SUCCESS" : "FAIL",
isSuccess ? successValue : fail);
}
// ------------------------------
public static class Fail {
private String message;
private Throwable cause;
private Fail(Throwable cause, String message) {
this.cause = cause;
this.message = message;
}
private Fail(Throwable cause, String format, Object... args) {
this(cause, String.format(format, args));
}
public String getMessage() {
return message;
}
public Throwable getCause() {
return cause;
}
@Override
public String toString() {
return String.format("%s - %s", message, cause);
}
}
}
| agpl-3.0 |
FreudianNM/openMAXIMS | Source Library/openmaxims_workspace/Core/src/ims/core/forms/vitalsignstprbp/Handlers.java | 4321 | //#############################################################################
//# #
//# Copyright (C) <2015> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of #
//# this program. Users of this software do so entirely at their own risk. #
//# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time #
//# software that it builds, deploys and maintains. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814)
// Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.core.forms.vitalsignstprbp;
import ims.framework.delegates.*;
abstract public class Handlers implements ims.framework.UILogic, IFormUILogicCode
{
abstract protected void onFormOpen() throws ims.framework.exceptions.PresentationLogicException;
abstract protected void onChkLegendValueChanged() throws ims.framework.exceptions.PresentationLogicException;
abstract protected void onBtnViewClick() throws ims.framework.exceptions.PresentationLogicException;
abstract protected void onRadioButtongrpShowByValueChanged() throws ims.framework.exceptions.PresentationLogicException;
abstract protected void onBtnPrintClick() throws ims.framework.exceptions.PresentationLogicException;
public final void setContext(ims.framework.UIEngine engine, GenForm form)
{
this.engine = engine;
this.form = form;
this.form.setFormOpenEvent(new FormOpen()
{
private static final long serialVersionUID = 1L;
public void handle(Object[] args) throws ims.framework.exceptions.PresentationLogicException
{
onFormOpen();
}
});
this.form.chkLegend().setValueChangedEvent(new ValueChanged()
{
private static final long serialVersionUID = 1L;
public void handle() throws ims.framework.exceptions.PresentationLogicException
{
onChkLegendValueChanged();
}
});
this.form.btnView().setClickEvent(new Click()
{
private static final long serialVersionUID = 1L;
public void handle() throws ims.framework.exceptions.PresentationLogicException
{
onBtnViewClick();
}
});
this.form.grpShowBy().setValueChangedEvent(new ValueChanged()
{
private static final long serialVersionUID = 1L;
public void handle() throws ims.framework.exceptions.PresentationLogicException
{
onRadioButtongrpShowByValueChanged();
}
});
this.form.btnPrint().setClickEvent(new Click()
{
private static final long serialVersionUID = 1L;
public void handle() throws ims.framework.exceptions.PresentationLogicException
{
onBtnPrintClick();
}
});
}
public void free()
{
this.engine = null;
this.form = null;
}
protected ims.framework.UIEngine engine;
protected GenForm form;
}
| agpl-3.0 |
IMS-MAXIMS/openMAXIMS | Source Library/openmaxims_workspace/ValueObjects/src/ims/refman/vo/beans/PatientDiagnosisStatusForReferralCodingVoBean.java | 3988 | //#############################################################################
//# #
//# Copyright (C) <2015> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of #
//# this program. Users of this software do so entirely at their own risk. #
//# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time #
//# software that it builds, deploys and maintains. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814)
// Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.RefMan.vo.beans;
public class PatientDiagnosisStatusForReferralCodingVoBean extends ims.vo.ValueObjectBean
{
public PatientDiagnosisStatusForReferralCodingVoBean()
{
}
public PatientDiagnosisStatusForReferralCodingVoBean(ims.RefMan.vo.PatientDiagnosisStatusForReferralCodingVo vo)
{
this.id = vo.getBoId();
this.version = vo.getBoVersion();
this.status = vo.getStatus() == null ? null : (ims.vo.LookupInstanceBean)vo.getStatus().getBean();
}
public void populate(ims.vo.ValueObjectBeanMap map, ims.RefMan.vo.PatientDiagnosisStatusForReferralCodingVo vo)
{
this.id = vo.getBoId();
this.version = vo.getBoVersion();
this.status = vo.getStatus() == null ? null : (ims.vo.LookupInstanceBean)vo.getStatus().getBean();
}
public ims.RefMan.vo.PatientDiagnosisStatusForReferralCodingVo buildVo()
{
return this.buildVo(new ims.vo.ValueObjectBeanMap());
}
public ims.RefMan.vo.PatientDiagnosisStatusForReferralCodingVo buildVo(ims.vo.ValueObjectBeanMap map)
{
ims.RefMan.vo.PatientDiagnosisStatusForReferralCodingVo vo = null;
if(map != null)
vo = (ims.RefMan.vo.PatientDiagnosisStatusForReferralCodingVo)map.getValueObject(this);
if(vo == null)
{
vo = new ims.RefMan.vo.PatientDiagnosisStatusForReferralCodingVo();
map.addValueObject(this, vo);
vo.populate(map, this);
}
return vo;
}
public Integer getId()
{
return this.id;
}
public void setId(Integer value)
{
this.id = value;
}
public int getVersion()
{
return this.version;
}
public void setVersion(int value)
{
this.version = value;
}
public ims.vo.LookupInstanceBean getStatus()
{
return this.status;
}
public void setStatus(ims.vo.LookupInstanceBean value)
{
this.status = value;
}
private Integer id;
private int version;
private ims.vo.LookupInstanceBean status;
}
| agpl-3.0 |
accesstest3/cfunambol | ctp/ctp-server/src/main/java/com/funambol/ctp/server/notification/NotificationProviderException.java | 3078 | /*
* Funambol is a mobile platform developed by Funambol, Inc.
* Copyright (C) 2007 Funambol, Inc.
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License version 3 as published by
* the Free Software Foundation with the addition of the following permission
* added to Section 15 as permitted in Section 7(a): FOR ANY PART OF THE COVERED
* WORK IN WHICH THE COPYRIGHT IS OWNED BY FUNAMBOL, FUNAMBOL DISCLAIMS THE
* WARRANTY OF NON INFRINGEMENT OF THIRD PARTY RIGHTS.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, see http://www.gnu.org/licenses or write to
* the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA.
*
* You can contact Funambol, Inc. headquarters at 643 Bair Island Road, Suite
* 305, Redwood City, CA 94063, USA, or at email address info@funambol.com.
*
* The interactive user interfaces in modified source and object code versions
* of this program must display Appropriate Legal Notices, as required under
* Section 5 of the GNU Affero General Public License version 3.
*
* In accordance with Section 7(b) of the GNU Affero General Public License
* version 3, these Appropriate Legal Notices must retain the display of the
* "Powered by Funambol" logo. If the display of the logo is not reasonably
* feasible for technical reasons, the Appropriate Legal Notices must display
* the words "Powered by Funambol".
*/
package com.funambol.ctp.server.notification;
/**
*
* @version $Id: NotificationProviderException.java,v 1.2 2007-11-28 11:26:16 nichele Exp $
*/
public class NotificationProviderException extends Exception {
/**
* Creates a new instance of <code>NotificationProviderException</code> without
* detail message.
*/
public NotificationProviderException() {
super();
}
/**
* Constructs an instance of <code>NotificationProviderException</code> with the
* specified detail message.
*
* @param message the detail message.
*/
public NotificationProviderException(String message) {
super(message);
}
/**
* Constructs an instance of <code>NotificationProviderException</code> with the
* specified detail message and the given cause.
*
* @param message the detail message.
* @param cause the cause.
*/
public NotificationProviderException(String message, Throwable cause) {
super(message, cause);
}
/**
* Constructs an instance of <code>NotificationProviderException</code> with the
* specified cause.
*
* @param cause the cause.
*/
public NotificationProviderException(Throwable cause) {
super(cause);
}
}
| agpl-3.0 |
open-health-hub/openmaxims-linux | openmaxims_workspace/SpinalInjuries/src/ims/spinalinjuries/domain/base/impl/BaseSharedNewConcernImpl.java | 2507 | //#############################################################################
//# #
//# Copyright (C) <2014> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751)
// Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.spinalinjuries.domain.base.impl;
import ims.domain.impl.DomainImpl;
public abstract class BaseSharedNewConcernImpl extends DomainImpl implements ims.spinalinjuries.domain.SharedNewConcern, ims.domain.impl.Transactional
{
private static final long serialVersionUID = 1L;
@SuppressWarnings("unused")
public void validatesaveConcern(ims.core.vo.PatientCurrentConcernVo concern, ims.core.vo.PatientShort patient)
{
}
@SuppressWarnings("unused")
public void validatelistHcps(ims.core.vo.HcpFilter filter)
{
}
@SuppressWarnings("unused")
public void validatelistProbsOnAdmission(ims.core.vo.CareContextShortVo coClinicalContactShort)
{
}
@SuppressWarnings("unused")
public void validategetConcern(ims.core.clinical.vo.PatientConcernRefVo concernId)
{
}
}
| agpl-3.0 |
open-health-hub/openmaxims-linux | openmaxims_workspace/ValueObjects/src/ims/emergency/vo/domain/TrackingLiteVoAssembler.java | 17855 | //#############################################################################
//# #
//# Copyright (C) <2014> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//#############################################################################
//#EOH
/*
* This code was generated
* Copyright (C) 1995-2004 IMS MAXIMS plc. All rights reserved.
* IMS Development Environment (version 1.80 build 5007.25751)
* WARNING: DO NOT MODIFY the content of this file
* Generated on 16/04/2014, 12:31
*
*/
package ims.emergency.vo.domain;
import ims.vo.domain.DomainObjectMap;
import java.util.HashMap;
import org.hibernate.proxy.HibernateProxy;
/**
* @author Cornel Ventuneac
*/
public class TrackingLiteVoAssembler
{
/**
* Copy one ValueObject to another
* @param valueObjectDest to be updated
* @param valueObjectSrc to copy values from
*/
public static ims.emergency.vo.TrackingLiteVo copy(ims.emergency.vo.TrackingLiteVo valueObjectDest, ims.emergency.vo.TrackingLiteVo valueObjectSrc)
{
if (null == valueObjectSrc)
{
return valueObjectSrc;
}
valueObjectDest.setID_Tracking(valueObjectSrc.getID_Tracking());
valueObjectDest.setIsRIE(valueObjectSrc.getIsRIE());
// CurrentArea
valueObjectDest.setCurrentArea(valueObjectSrc.getCurrentArea());
// isPrimaryCare
valueObjectDest.setIsPrimaryCare(valueObjectSrc.getIsPrimaryCare());
// isDischarged
valueObjectDest.setIsDischarged(valueObjectSrc.getIsDischarged());
// LastMovementDateTime
valueObjectDest.setLastMovementDateTime(valueObjectSrc.getLastMovementDateTime());
return valueObjectDest;
}
/**
* Create the ValueObject collection to hold the set of DomainObjects.
* This is a convenience method only.
* It is intended to be used when one called to an Assembler is made.
* If more than one call to an Assembler is made then #createTrackingLiteVoCollectionFromTracking(DomainObjectMap, Set) should be used.
* @param domainObjectSet - Set of ims.emergency.domain.objects.Tracking objects.
*/
public static ims.emergency.vo.TrackingLiteVoCollection createTrackingLiteVoCollectionFromTracking(java.util.Set domainObjectSet)
{
return createTrackingLiteVoCollectionFromTracking(new DomainObjectMap(), domainObjectSet);
}
/**
* Create the ValueObject collection to hold the set of DomainObjects.
* @param map - maps DomainObjects to created ValueObjects
* @param domainObjectSet - Set of ims.emergency.domain.objects.Tracking objects.
*/
public static ims.emergency.vo.TrackingLiteVoCollection createTrackingLiteVoCollectionFromTracking(DomainObjectMap map, java.util.Set domainObjectSet)
{
ims.emergency.vo.TrackingLiteVoCollection voList = new ims.emergency.vo.TrackingLiteVoCollection();
if ( null == domainObjectSet )
{
return voList;
}
int rieCount=0;
int activeCount=0;
java.util.Iterator iterator = domainObjectSet.iterator();
while( iterator.hasNext() )
{
ims.emergency.domain.objects.Tracking domainObject = (ims.emergency.domain.objects.Tracking) iterator.next();
ims.emergency.vo.TrackingLiteVo vo = create(map, domainObject);
if (vo != null)
voList.add(vo);
if (domainObject != null)
{
if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true)
rieCount++;
else
activeCount++;
}
}
voList.setRieCount(rieCount);
voList.setActiveCount(activeCount);
return voList;
}
/**
* Create the ValueObject collection to hold the list of DomainObjects.
* @param domainObjectList - List of ims.emergency.domain.objects.Tracking objects.
*/
public static ims.emergency.vo.TrackingLiteVoCollection createTrackingLiteVoCollectionFromTracking(java.util.List domainObjectList)
{
return createTrackingLiteVoCollectionFromTracking(new DomainObjectMap(), domainObjectList);
}
/**
* Create the ValueObject collection to hold the list of DomainObjects.
* @param map - maps DomainObjects to created ValueObjects
* @param domainObjectList - List of ims.emergency.domain.objects.Tracking objects.
*/
public static ims.emergency.vo.TrackingLiteVoCollection createTrackingLiteVoCollectionFromTracking(DomainObjectMap map, java.util.List domainObjectList)
{
ims.emergency.vo.TrackingLiteVoCollection voList = new ims.emergency.vo.TrackingLiteVoCollection();
if ( null == domainObjectList )
{
return voList;
}
int rieCount=0;
int activeCount=0;
for (int i = 0; i < domainObjectList.size(); i++)
{
ims.emergency.domain.objects.Tracking domainObject = (ims.emergency.domain.objects.Tracking) domainObjectList.get(i);
ims.emergency.vo.TrackingLiteVo vo = create(map, domainObject);
if (vo != null)
voList.add(vo);
if (domainObject != null)
{
if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true)
rieCount++;
else
activeCount++;
}
}
voList.setRieCount(rieCount);
voList.setActiveCount(activeCount);
return voList;
}
/**
* Create the ims.emergency.domain.objects.Tracking set from the value object collection.
* @param domainFactory - used to create existing (persistent) domain objects.
* @param voCollection - the collection of value objects
*/
public static java.util.Set extractTrackingSet(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.TrackingLiteVoCollection voCollection)
{
return extractTrackingSet(domainFactory, voCollection, null, new HashMap());
}
public static java.util.Set extractTrackingSet(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.TrackingLiteVoCollection voCollection, java.util.Set domainObjectSet, HashMap domMap)
{
int size = (null == voCollection) ? 0 : voCollection.size();
if (domainObjectSet == null)
{
domainObjectSet = new java.util.HashSet();
}
java.util.Set newSet = new java.util.HashSet();
for(int i=0; i<size; i++)
{
ims.emergency.vo.TrackingLiteVo vo = voCollection.get(i);
ims.emergency.domain.objects.Tracking domainObject = TrackingLiteVoAssembler.extractTracking(domainFactory, vo, domMap);
//TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it.
if (domainObject == null)
{
continue;
}
//Trying to avoid the hibernate collection being marked as dirty via its public interface methods. (like add)
if (!domainObjectSet.contains(domainObject)) domainObjectSet.add(domainObject);
newSet.add(domainObject);
}
java.util.Set removedSet = new java.util.HashSet();
java.util.Iterator iter = domainObjectSet.iterator();
//Find out which objects need to be removed
while (iter.hasNext())
{
ims.domain.DomainObject o = (ims.domain.DomainObject)iter.next();
if ((o == null || o.getIsRIE() == null || !o.getIsRIE().booleanValue()) && !newSet.contains(o))
{
removedSet.add(o);
}
}
iter = removedSet.iterator();
//Remove the unwanted objects
while (iter.hasNext())
{
domainObjectSet.remove(iter.next());
}
return domainObjectSet;
}
/**
* Create the ims.emergency.domain.objects.Tracking list from the value object collection.
* @param domainFactory - used to create existing (persistent) domain objects.
* @param voCollection - the collection of value objects
*/
public static java.util.List extractTrackingList(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.TrackingLiteVoCollection voCollection)
{
return extractTrackingList(domainFactory, voCollection, null, new HashMap());
}
public static java.util.List extractTrackingList(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.TrackingLiteVoCollection voCollection, java.util.List domainObjectList, HashMap domMap)
{
int size = (null == voCollection) ? 0 : voCollection.size();
if (domainObjectList == null)
{
domainObjectList = new java.util.ArrayList();
}
for(int i=0; i<size; i++)
{
ims.emergency.vo.TrackingLiteVo vo = voCollection.get(i);
ims.emergency.domain.objects.Tracking domainObject = TrackingLiteVoAssembler.extractTracking(domainFactory, vo, domMap);
//TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it.
if (domainObject == null)
{
continue;
}
int domIdx = domainObjectList.indexOf(domainObject);
if (domIdx == -1)
{
domainObjectList.add(i, domainObject);
}
else if (i != domIdx && i < domainObjectList.size())
{
Object tmp = domainObjectList.get(i);
domainObjectList.set(i, domainObjectList.get(domIdx));
domainObjectList.set(domIdx, tmp);
}
}
//Remove all ones in domList where index > voCollection.size() as these should
//now represent the ones removed from the VO collection. No longer referenced.
int i1=domainObjectList.size();
while (i1 > size)
{
domainObjectList.remove(i1-1);
i1=domainObjectList.size();
}
return domainObjectList;
}
/**
* Create the ValueObject from the ims.emergency.domain.objects.Tracking object.
* @param domainObject ims.emergency.domain.objects.Tracking
*/
public static ims.emergency.vo.TrackingLiteVo create(ims.emergency.domain.objects.Tracking domainObject)
{
if (null == domainObject)
{
return null;
}
DomainObjectMap map = new DomainObjectMap();
return create(map, domainObject);
}
/**
* Create the ValueObject from the ims.emergency.domain.objects.Tracking object.
* @param map DomainObjectMap of DomainObjects to already created ValueObjects.
* @param domainObject
*/
public static ims.emergency.vo.TrackingLiteVo create(DomainObjectMap map, ims.emergency.domain.objects.Tracking domainObject)
{
if (null == domainObject)
{
return null;
}
// check if the domainObject already has a valueObject created for it
ims.emergency.vo.TrackingLiteVo valueObject = (ims.emergency.vo.TrackingLiteVo) map.getValueObject(domainObject, ims.emergency.vo.TrackingLiteVo.class);
if ( null == valueObject )
{
valueObject = new ims.emergency.vo.TrackingLiteVo(domainObject.getId(), domainObject.getVersion());
map.addValueObject(domainObject, valueObject);
valueObject = insert(map, valueObject, domainObject);
}
return valueObject;
}
/**
* Update the ValueObject with the Domain Object.
* @param valueObject to be updated
* @param domainObject ims.emergency.domain.objects.Tracking
*/
public static ims.emergency.vo.TrackingLiteVo insert(ims.emergency.vo.TrackingLiteVo valueObject, ims.emergency.domain.objects.Tracking domainObject)
{
if (null == domainObject)
{
return valueObject;
}
DomainObjectMap map = new DomainObjectMap();
return insert(map, valueObject, domainObject);
}
/**
* Update the ValueObject with the Domain Object.
* @param map DomainObjectMap of DomainObjects to already created ValueObjects.
* @param valueObject to be updated
* @param domainObject ims.emergency.domain.objects.Tracking
*/
public static ims.emergency.vo.TrackingLiteVo insert(DomainObjectMap map, ims.emergency.vo.TrackingLiteVo valueObject, ims.emergency.domain.objects.Tracking domainObject)
{
if (null == domainObject)
{
return valueObject;
}
if (null == map)
{
map = new DomainObjectMap();
}
valueObject.setID_Tracking(domainObject.getId());
valueObject.setIsRIE(domainObject.getIsRIE());
// If this is a recordedInError record, and the domainObject
// value isIncludeRecord has not been set, then we return null and
// not the value object
if (valueObject.getIsRIE() != null && valueObject.getIsRIE().booleanValue() == true && !domainObject.isIncludeRecord())
return null;
// If this is not a recordedInError record, and the domainObject
// value isIncludeRecord has been set, then we return null and
// not the value object
if ((valueObject.getIsRIE() == null || valueObject.getIsRIE().booleanValue() == false) && domainObject.isIncludeRecord())
return null;
// CurrentArea
if (domainObject.getCurrentArea() != null)
{
if(domainObject.getCurrentArea() instanceof HibernateProxy) // If the proxy is set, there is no need to lazy load, the proxy knows the id already.
{
HibernateProxy p = (HibernateProxy) domainObject.getCurrentArea();
int id = Integer.parseInt(p.getHibernateLazyInitializer().getIdentifier().toString());
valueObject.setCurrentArea(new ims.emergency.configuration.vo.TrackingAreaRefVo(id, -1));
}
else
{
valueObject.setCurrentArea(new ims.emergency.configuration.vo.TrackingAreaRefVo(domainObject.getCurrentArea().getId(), domainObject.getCurrentArea().getVersion()));
}
}
// isPrimaryCare
valueObject.setIsPrimaryCare( domainObject.isIsPrimaryCare() );
// isDischarged
valueObject.setIsDischarged( domainObject.isIsDischarged() );
// LastMovementDateTime
java.util.Date LastMovementDateTime = domainObject.getLastMovementDateTime();
if ( null != LastMovementDateTime )
{
valueObject.setLastMovementDateTime(new ims.framework.utils.DateTime(LastMovementDateTime) );
}
return valueObject;
}
/**
* Create the domain object from the value object.
* @param domainFactory - used to create existing (persistent) domain objects.
* @param valueObject - extract the domain object fields from this.
*/
public static ims.emergency.domain.objects.Tracking extractTracking(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.TrackingLiteVo valueObject)
{
return extractTracking(domainFactory, valueObject, new HashMap());
}
public static ims.emergency.domain.objects.Tracking extractTracking(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.TrackingLiteVo valueObject, HashMap domMap)
{
if (null == valueObject)
{
return null;
}
Integer id = valueObject.getID_Tracking();
ims.emergency.domain.objects.Tracking domainObject = null;
if ( null == id)
{
if (domMap.get(valueObject) != null)
{
return (ims.emergency.domain.objects.Tracking)domMap.get(valueObject);
}
// ims.emergency.vo.TrackingLiteVo ID_Tracking field is unknown
domainObject = new ims.emergency.domain.objects.Tracking();
domMap.put(valueObject, domainObject);
}
else
{
String key = (valueObject.getClass().getName() + "__" + valueObject.getID_Tracking());
if (domMap.get(key) != null)
{
return (ims.emergency.domain.objects.Tracking)domMap.get(key);
}
domainObject = (ims.emergency.domain.objects.Tracking) domainFactory.getDomainObject(ims.emergency.domain.objects.Tracking.class, id );
//TODO: Not sure how this should be handled. Effectively it must be a staleobject exception, but maybe should be handled as that further up.
if (domainObject == null)
return null;
domMap.put(key, domainObject);
}
domainObject.setVersion(valueObject.getVersion_Tracking());
ims.emergency.configuration.domain.objects.TrackingArea value1 = null;
if ( null != valueObject.getCurrentArea() )
{
if (valueObject.getCurrentArea().getBoId() == null)
{
if (domMap.get(valueObject.getCurrentArea()) != null)
{
value1 = (ims.emergency.configuration.domain.objects.TrackingArea)domMap.get(valueObject.getCurrentArea());
}
}
else if (valueObject.getBoVersion() == -1) // RefVo was not modified since obtained from the Assembler, no need to update the BO field
{
value1 = domainObject.getCurrentArea();
}
else
{
value1 = (ims.emergency.configuration.domain.objects.TrackingArea)domainFactory.getDomainObject(ims.emergency.configuration.domain.objects.TrackingArea.class, valueObject.getCurrentArea().getBoId());
}
}
domainObject.setCurrentArea(value1);
domainObject.setIsPrimaryCare(valueObject.getIsPrimaryCare());
domainObject.setIsDischarged(valueObject.getIsDischarged());
ims.framework.utils.DateTime dateTime4 = valueObject.getLastMovementDateTime();
java.util.Date value4 = null;
if ( dateTime4 != null )
{
value4 = dateTime4.getJavaDate();
}
domainObject.setLastMovementDateTime(value4);
return domainObject;
}
}
| agpl-3.0 |
maduhu/knx-jbilling2.2.0 | build/jsp-classes/com/sapienter/jbilling/client/jspc/payment/review_jsp.java | 11647 | package com.sapienter.jbilling.client.jspc.payment;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
import com.sapienter.jbilling.client.util.Constants;
public final class review_jsp extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent {
private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory();
private static java.util.List _jspx_dependants;
private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fsess_005fexistsAttribute_0026_005fvalue_005fname;
private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005ftiles_005finsert_0026_005fflush_005fdefinition_005fnobody;
private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fsess_005fexistsAttribute_0026_005fname;
private javax.el.ExpressionFactory _el_expressionfactory;
private org.apache.AnnotationProcessor _jsp_annotationprocessor;
public Object getDependants() {
return _jspx_dependants;
}
public void _jspInit() {
_005fjspx_005ftagPool_005fsess_005fexistsAttribute_0026_005fvalue_005fname = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_005fjspx_005ftagPool_005ftiles_005finsert_0026_005fflush_005fdefinition_005fnobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_005fjspx_005ftagPool_005fsess_005fexistsAttribute_0026_005fname = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();
_jsp_annotationprocessor = (org.apache.AnnotationProcessor) getServletConfig().getServletContext().getAttribute(org.apache.AnnotationProcessor.class.getName());
}
public void _jspDestroy() {
_005fjspx_005ftagPool_005fsess_005fexistsAttribute_0026_005fvalue_005fname.release();
_005fjspx_005ftagPool_005ftiles_005finsert_0026_005fflush_005fdefinition_005fnobody.release();
_005fjspx_005ftagPool_005fsess_005fexistsAttribute_0026_005fname.release();
}
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException, ServletException {
PageContext pageContext = null;
HttpSession session = null;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
JspWriter _jspx_out = null;
PageContext _jspx_page_context = null;
try {
response.setContentType("text/html");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
out.write("\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n");
if (_jspx_meth_sess_005fexistsAttribute_005f0(_jspx_page_context))
return;
out.write('\r');
out.write('\n');
if (_jspx_meth_sess_005fexistsAttribute_005f1(_jspx_page_context))
return;
out.write("\r\n\r\n");
} catch (Throwable t) {
if (!(t instanceof SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
try { out.clearBuffer(); } catch (java.io.IOException e) {}
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
}
private boolean _jspx_meth_sess_005fexistsAttribute_005f0(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// sess:existsAttribute
org.apache.taglibs.session.ExistsAttributeTag _jspx_th_sess_005fexistsAttribute_005f0 = (org.apache.taglibs.session.ExistsAttributeTag) _005fjspx_005ftagPool_005fsess_005fexistsAttribute_0026_005fvalue_005fname.get(org.apache.taglibs.session.ExistsAttributeTag.class);
_jspx_th_sess_005fexistsAttribute_005f0.setPageContext(_jspx_page_context);
_jspx_th_sess_005fexistsAttribute_005f0.setParent(null);
// /payment/review.jsp(30,0) name = name type = java.lang.String reqTime = false required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_sess_005fexistsAttribute_005f0.setName("jsp_is_refund");
// /payment/review.jsp(30,0) name = value type = java.lang.String reqTime = false required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_sess_005fexistsAttribute_005f0.setValue(false);
int _jspx_eval_sess_005fexistsAttribute_005f0 = _jspx_th_sess_005fexistsAttribute_005f0.doStartTag();
if (_jspx_eval_sess_005fexistsAttribute_005f0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n ");
if (_jspx_meth_tiles_005finsert_005f0(_jspx_th_sess_005fexistsAttribute_005f0, _jspx_page_context))
return true;
out.write('\r');
out.write('\n');
int evalDoAfterBody = _jspx_th_sess_005fexistsAttribute_005f0.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_sess_005fexistsAttribute_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_005fjspx_005ftagPool_005fsess_005fexistsAttribute_0026_005fvalue_005fname.reuse(_jspx_th_sess_005fexistsAttribute_005f0);
return true;
}
_005fjspx_005ftagPool_005fsess_005fexistsAttribute_0026_005fvalue_005fname.reuse(_jspx_th_sess_005fexistsAttribute_005f0);
return false;
}
private boolean _jspx_meth_tiles_005finsert_005f0(javax.servlet.jsp.tagext.JspTag _jspx_th_sess_005fexistsAttribute_005f0, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// tiles:insert
org.apache.struts.taglib.tiles.InsertTag _jspx_th_tiles_005finsert_005f0 = (org.apache.struts.taglib.tiles.InsertTag) _005fjspx_005ftagPool_005ftiles_005finsert_0026_005fflush_005fdefinition_005fnobody.get(org.apache.struts.taglib.tiles.InsertTag.class);
_jspx_th_tiles_005finsert_005f0.setPageContext(_jspx_page_context);
_jspx_th_tiles_005finsert_005f0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_sess_005fexistsAttribute_005f0);
// /payment/review.jsp(31,3) name = definition type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_tiles_005finsert_005f0.setDefinition("payment.review");
// /payment/review.jsp(31,3) name = flush type = java.lang.String reqTime = false required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_tiles_005finsert_005f0.setFlush(true);
int _jspx_eval_tiles_005finsert_005f0 = _jspx_th_tiles_005finsert_005f0.doStartTag();
if (_jspx_th_tiles_005finsert_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_005fjspx_005ftagPool_005ftiles_005finsert_0026_005fflush_005fdefinition_005fnobody.reuse(_jspx_th_tiles_005finsert_005f0);
return true;
}
_005fjspx_005ftagPool_005ftiles_005finsert_0026_005fflush_005fdefinition_005fnobody.reuse(_jspx_th_tiles_005finsert_005f0);
return false;
}
private boolean _jspx_meth_sess_005fexistsAttribute_005f1(PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// sess:existsAttribute
org.apache.taglibs.session.ExistsAttributeTag _jspx_th_sess_005fexistsAttribute_005f1 = (org.apache.taglibs.session.ExistsAttributeTag) _005fjspx_005ftagPool_005fsess_005fexistsAttribute_0026_005fname.get(org.apache.taglibs.session.ExistsAttributeTag.class);
_jspx_th_sess_005fexistsAttribute_005f1.setPageContext(_jspx_page_context);
_jspx_th_sess_005fexistsAttribute_005f1.setParent(null);
// /payment/review.jsp(33,0) name = name type = java.lang.String reqTime = false required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_sess_005fexistsAttribute_005f1.setName("jsp_is_refund");
int _jspx_eval_sess_005fexistsAttribute_005f1 = _jspx_th_sess_005fexistsAttribute_005f1.doStartTag();
if (_jspx_eval_sess_005fexistsAttribute_005f1 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
do {
out.write("\r\n ");
if (_jspx_meth_tiles_005finsert_005f1(_jspx_th_sess_005fexistsAttribute_005f1, _jspx_page_context))
return true;
out.write('\r');
out.write('\n');
int evalDoAfterBody = _jspx_th_sess_005fexistsAttribute_005f1.doAfterBody();
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
}
if (_jspx_th_sess_005fexistsAttribute_005f1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_005fjspx_005ftagPool_005fsess_005fexistsAttribute_0026_005fname.reuse(_jspx_th_sess_005fexistsAttribute_005f1);
return true;
}
_005fjspx_005ftagPool_005fsess_005fexistsAttribute_0026_005fname.reuse(_jspx_th_sess_005fexistsAttribute_005f1);
return false;
}
private boolean _jspx_meth_tiles_005finsert_005f1(javax.servlet.jsp.tagext.JspTag _jspx_th_sess_005fexistsAttribute_005f1, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// tiles:insert
org.apache.struts.taglib.tiles.InsertTag _jspx_th_tiles_005finsert_005f1 = (org.apache.struts.taglib.tiles.InsertTag) _005fjspx_005ftagPool_005ftiles_005finsert_0026_005fflush_005fdefinition_005fnobody.get(org.apache.struts.taglib.tiles.InsertTag.class);
_jspx_th_tiles_005finsert_005f1.setPageContext(_jspx_page_context);
_jspx_th_tiles_005finsert_005f1.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_sess_005fexistsAttribute_005f1);
// /payment/review.jsp(34,3) name = definition type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_tiles_005finsert_005f1.setDefinition("refund.review");
// /payment/review.jsp(34,3) name = flush type = java.lang.String reqTime = false required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_tiles_005finsert_005f1.setFlush(true);
int _jspx_eval_tiles_005finsert_005f1 = _jspx_th_tiles_005finsert_005f1.doStartTag();
if (_jspx_th_tiles_005finsert_005f1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_005fjspx_005ftagPool_005ftiles_005finsert_0026_005fflush_005fdefinition_005fnobody.reuse(_jspx_th_tiles_005finsert_005f1);
return true;
}
_005fjspx_005ftagPool_005ftiles_005finsert_0026_005fflush_005fdefinition_005fnobody.reuse(_jspx_th_tiles_005finsert_005f1);
return false;
}
}
| agpl-3.0 |
open-health-hub/openmaxims-linux | openmaxims_workspace/Core/src/ims/core/forms/notificationdialog/IFormUILogicCode.java | 1804 | //#############################################################################
//# #
//# Copyright (C) <2014> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5007.25751)
// Copyright (C) 1995-2014 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.core.forms.notificationdialog;
public interface IFormUILogicCode
{
// No methods yet.
}
| agpl-3.0 |
FreudianNM/openMAXIMS | Source Library/openmaxims_workspace/Scheduling/src/ims/scheduling/domain/impl/ReasonTextDialogImpl.java | 3583 | //#############################################################################
//# #
//# Copyright (C) <2015> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of #
//# this program. Users of this software do so entirely at their own risk. #
//# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time #
//# software that it builds, deploys and maintains. #
//# #
//#############################################################################
//#EOH
// This code was generated by Silviu Checherita using IMS Development Environment (version 1.80 build 5567.19951)
// Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved.
package ims.scheduling.domain.impl;
import java.util.ArrayList;
import java.util.List;
import ims.domain.DomainFactory;
import ims.domain.lookups.LookupInstance;
import ims.scheduling.domain.base.impl.BaseReasonTextDialogImpl;
import ims.scheduling.vo.lookups.CancelAppointmentReason;
import ims.scheduling.vo.lookups.CancelAppointmentReasonCollection;
import ims.scheduling.vo.lookups.Status_Reason;
public class ReasonTextDialogImpl extends BaseReasonTextDialogImpl
{
private static final long serialVersionUID = 1L;
//WDEV-21736
public CancelAppointmentReasonCollection listReasons()
{
DomainFactory factory = getDomainFactory();
ArrayList markers = new ArrayList();
ArrayList values = new ArrayList();
String hql = "SELECT r FROM CancellationTypeReason AS t LEFT JOIN t.cancellationReason as r WHERE t.cancellationType.id = :cancellationType AND r.active = 1";
markers.add("cancellationType");
values.add(Status_Reason.HOSPITALCANCELLED.getID());
List results = factory.find(hql.toString(), markers,values);
if (results == null)
return null;
CancelAppointmentReasonCollection col = new CancelAppointmentReasonCollection();
for (int i=0; i<results.size(); i++)
{
CancelAppointmentReason reason = new CancelAppointmentReason(((LookupInstance) results.get(i)).getId(), ((LookupInstance) results.get(i)).getText(), ((LookupInstance) results.get(i)).isActive());
col.add(reason);
}
return col;
}
//WDEV-21736 ends here
}
| agpl-3.0 |
FreudianNM/openMAXIMS | Source Library/openmaxims_workspace/ValueObjects/src/ims/oncology/vo/lookups/GradeofDifferentation.java | 5476 | //#############################################################################
//# #
//# Copyright (C) <2015> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of #
//# this program. Users of this software do so entirely at their own risk. #
//# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time #
//# software that it builds, deploys and maintains. #
//# #
//#############################################################################
//#EOH
// This code was generated by Barbara Worwood using IMS Development Environment (version 1.80 build 5589.25814)
// Copyright (C) 1995-2015 IMS MAXIMS. All rights reserved.
// WARNING: DO NOT MODIFY the content of this file
package ims.oncology.vo.lookups;
import ims.framework.cn.data.TreeNode;
import java.util.ArrayList;
import ims.framework.utils.Image;
import ims.framework.utils.Color;
public class GradeofDifferentation extends ims.vo.LookupInstVo implements TreeNode
{
private static final long serialVersionUID = 1L;
public GradeofDifferentation()
{
super();
}
public GradeofDifferentation(int id)
{
super(id, "", true);
}
public GradeofDifferentation(int id, String text, boolean active)
{
super(id, text, active, null, null, null);
}
public GradeofDifferentation(int id, String text, boolean active, GradeofDifferentation parent, Image image)
{
super(id, text, active, parent, image);
}
public GradeofDifferentation(int id, String text, boolean active, GradeofDifferentation parent, Image image, Color color)
{
super(id, text, active, parent, image, color);
}
public GradeofDifferentation(int id, String text, boolean active, GradeofDifferentation parent, Image image, Color color, int order)
{
super(id, text, active, parent, image, color, order);
}
public static GradeofDifferentation buildLookup(ims.vo.LookupInstanceBean bean)
{
return new GradeofDifferentation(bean.getId(), bean.getText(), bean.isActive());
}
public String toString()
{
if(getText() != null)
return getText();
return "";
}
public TreeNode getParentNode()
{
return (GradeofDifferentation)super.getParentInstance();
}
public GradeofDifferentation getParent()
{
return (GradeofDifferentation)super.getParentInstance();
}
public void setParent(GradeofDifferentation parent)
{
super.setParentInstance(parent);
}
public TreeNode[] getChildren()
{
ArrayList children = super.getChildInstances();
GradeofDifferentation[] typedChildren = new GradeofDifferentation[children.size()];
for (int i = 0; i < children.size(); i++)
{
typedChildren[i] = (GradeofDifferentation)children.get(i);
}
return typedChildren;
}
public int addChild(TreeNode child)
{
if (child instanceof GradeofDifferentation)
{
super.addChild((GradeofDifferentation)child);
}
return super.getChildInstances().size();
}
public int removeChild(TreeNode child)
{
if (child instanceof GradeofDifferentation)
{
super.removeChild((GradeofDifferentation)child);
}
return super.getChildInstances().size();
}
public Image getExpandedImage()
{
return super.getImage();
}
public Image getCollapsedImage()
{
return super.getImage();
}
public static ims.framework.IItemCollection getNegativeInstancesAsIItemCollection()
{
GradeofDifferentationCollection result = new GradeofDifferentationCollection();
return result;
}
public static GradeofDifferentation[] getNegativeInstances()
{
return new GradeofDifferentation[] {};
}
public static String[] getNegativeInstanceNames()
{
return new String[] {};
}
public static GradeofDifferentation getNegativeInstance(String name)
{
if(name == null)
return null;
// No negative instances found
return null;
}
public static GradeofDifferentation getNegativeInstance(Integer id)
{
if(id == null)
return null;
// No negative instances found
return null;
}
public int getTypeId()
{
return TYPE_ID;
}
public static final int TYPE_ID = 1251032;
}
| agpl-3.0 |
rapidminer/rapidminer-5 | src/com/rapid_i/deployment/update/client/PendingPurchasesInstallationDialog.java | 11249 | /*
* RapidMiner
*
* Copyright (C) 2001-2014 by RapidMiner and the contributors
*
* Complete list of developers available at our web site:
*
* http://rapidminer.com
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see http://www.gnu.org/licenses/.
*/
package com.rapid_i.deployment.update.client;
import java.awt.BorderLayout;
import java.awt.Dimension;
import java.awt.event.ActionEvent;
import java.awt.event.KeyEvent;
import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.logging.Level;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.JButton;
import javax.swing.JCheckBox;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JList;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.KeyStroke;
import javax.swing.SwingUtilities;
import javax.swing.border.EmptyBorder;
import javax.swing.border.EtchedBorder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import com.rapid_i.deployment.update.client.listmodels.AbstractPackageListModel;
import com.rapidminer.deployment.client.wsimport.PackageDescriptor;
import com.rapidminer.deployment.client.wsimport.UpdateService;
import com.rapidminer.gui.RapidMinerGUI;
import com.rapidminer.gui.tools.ExtendedJScrollPane;
import com.rapidminer.gui.tools.ProgressThread;
import com.rapidminer.gui.tools.ResourceAction;
import com.rapidminer.gui.tools.SwingTools;
import com.rapidminer.gui.tools.dialogs.ButtonDialog;
import com.rapidminer.gui.tools.dialogs.ConfirmDialog;
import com.rapidminer.io.process.XMLTools;
import com.rapidminer.tools.FileSystemService;
import com.rapidminer.tools.I18N;
import com.rapidminer.tools.LogService;
import com.rapidminer.tools.ParameterService;
import com.rapidminer.tools.XMLException;
/**
* The Dialog is eventually shown at the start of RapidMiner, if the user purchased extensions online but haven't installed them yet.
*
* @author Dominik Halfkann
*/
public class PendingPurchasesInstallationDialog extends ButtonDialog {
private static final long serialVersionUID = 1L;
private final PackageDescriptorCache packageDescriptorCache = new PackageDescriptorCache();
private AbstractPackageListModel purchasedModel = new PurchasedNotInstalledModel(packageDescriptorCache);
JCheckBox neverAskAgain = new JCheckBox(I18N.getMessage(I18N.getGUIBundle(), "gui.dialog.purchased_not_installed.not_check_on_startup"));
private final List<String> packages;
private boolean isConfirmed;
private LinkedList<PackageDescriptor> installablePackageList;
private JButton remindNeverButton;
private JButton remindLaterButton;
private JButton okButton;
private class PurchasedNotInstalledModel extends AbstractPackageListModel {
private static final long serialVersionUID = 1L;
public PurchasedNotInstalledModel(PackageDescriptorCache cache) {
super(cache, "gui.dialog.update.tab.no_packages");
}
@Override
public List<String> handleFetchPackageNames() {
return packages;
}
}
public PendingPurchasesInstallationDialog(List<String> packages) {
super("purchased_not_installed");
this.packages = packages;
remindNeverButton = remindNeverButton();
remindLaterButton = remindLaterButton();
okButton = makeOkButton("install_purchased");
layoutDefault(makeContentPanel(), NORMAL, okButton, remindNeverButton, remindLaterButton);
this.setPreferredSize(new Dimension(404, 430));
this.setMaximumSize(new Dimension(404, 430));
this.setMinimumSize(new Dimension(404, 300));
this.setSize(new Dimension(404, 430));
}
private JPanel makeContentPanel() {
BorderLayout layout = new BorderLayout(12, 12);
JPanel panel = new JPanel(layout);
panel.setBorder(new EmptyBorder(0, 12, 8, 12));
panel.add(createExtensionListScrollPane(purchasedModel), BorderLayout.CENTER);
purchasedModel.update();
JPanel southPanel = new JPanel(new BorderLayout(0, 7));
JLabel question = new JLabel(I18N.getMessage(I18N.getGUIBundle(), "gui.dialog.purchased_not_installed.should_install"));
southPanel.add(question, BorderLayout.CENTER);
southPanel.add(neverAskAgain, BorderLayout.SOUTH);
panel.add(southPanel, BorderLayout.SOUTH);
return panel;
}
private JScrollPane createExtensionListScrollPane(AbstractPackageListModel model) {
final JList updateList = new JList(model);
updateList.setCellRenderer(new UpdateListCellRenderer(true));
JScrollPane extensionListScrollPane = new ExtendedJScrollPane(updateList);
extensionListScrollPane.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.LOWERED));
return extensionListScrollPane;
}
private JButton remindLaterButton() {
Action Action = new ResourceAction("ask_later") {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e) {
wasConfirmed = false;
checkNeverAskAgain();
close();
}
};
getRootPane().getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0, false), "CLOSE");
getRootPane().getActionMap().put("CLOSE", Action);
JButton button = new JButton(Action);
getRootPane().setDefaultButton(button);
return button;
}
private JButton remindNeverButton() {
Action Action = new ResourceAction("ask_never") {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e) {
wasConfirmed = false;
checkNeverAskAgain();
neverRemindAgain();
close();
}
};
JButton button = new JButton(Action);
getRootPane().setDefaultButton(button);
return button;
}
@Override
protected void ok() {
checkNeverAskAgain();
startUpdate(getPackageDescriptorList());
dispose();
}
public List<PackageDescriptor> getPackageDescriptorList() {
List<PackageDescriptor> packageList = new ArrayList<PackageDescriptor>();
for (int a = 0; a < purchasedModel.getSize(); a++) {
Object listItem = purchasedModel.getElementAt(a);
if (listItem instanceof PackageDescriptor) {
packageList.add((PackageDescriptor) listItem);
}
}
return packageList;
}
public void startUpdate(final List<PackageDescriptor> downloadList) {
final UpdateService service;
try {
service = UpdateManager.getService();
} catch (Exception e) {
SwingTools.showSimpleErrorMessage("failed_update_server", e, UpdateManager.getBaseUrl());
return;
}
new ProgressThread("resolving_dependencies", true) {
@Override
public void run() {
try {
getProgressListener().setTotal(100);
remindLaterButton.setEnabled(false);
remindNeverButton.setEnabled(false);
final HashMap<PackageDescriptor, HashSet<PackageDescriptor>> dependency = UpdateDialog.resolveDependency(downloadList, packageDescriptorCache);
getProgressListener().setCompleted(30);
installablePackageList = UpdateDialog.getPackagesforInstallation(dependency);
final HashMap<String, String> licenseNameToLicenseTextMap = UpdateDialog.collectLicenses(installablePackageList,getProgressListener(),100,30,100);
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
isConfirmed = ConfirmLicensesDialog.confirm(dependency, licenseNameToLicenseTextMap);
new ProgressThread("installing_updates", true) {
@Override
public void run() {
try {
if (isConfirmed) {
getProgressListener().setTotal(100);
getProgressListener().setCompleted(20);
UpdateService service = UpdateManager.getService();
UpdateManager um = new UpdateManager(service);
List<PackageDescriptor> installedPackages = um.performUpdates(installablePackageList, getProgressListener());
getProgressListener().setCompleted(40);
if (installedPackages.size() > 0) {
int confirmation = SwingTools.showConfirmDialog((installedPackages.size() == 1 ? "update.complete_restart" : "update.complete_restart1"),
ConfirmDialog.YES_NO_OPTION, installedPackages.size());
if (confirmation == ConfirmDialog.YES_OPTION) {
RapidMinerGUI.getMainFrame().exit(true);
} else if (confirmation == ConfirmDialog.NO_OPTION) {
if (installedPackages.size() == installablePackageList.size()) {
dispose();
}
}
}
getProgressListener().complete();
}
} catch (Exception e) {
SwingTools.showSimpleErrorMessage("error_installing_update", e, e.getMessage());
} finally {
getProgressListener().complete();
}
}
}.start();
}
});
remindLaterButton.setEnabled(true);
remindNeverButton.setEnabled(true);
getProgressListener().complete();
} catch (Exception e) {
SwingTools.showSimpleErrorMessage("error_resolving_dependencies", e, e.getMessage());
}
}
}.start();
}
private void checkNeverAskAgain() {
if (neverAskAgain.isSelected()) {
ParameterService.setParameterValue(RapidMinerGUI.PROPERTY_RAPIDMINER_GUI_PURCHASED_NOT_INSTALLED_CHECK, "false");
ParameterService.saveParameters();
}
}
private void neverRemindAgain() {
LogService.getRoot().log(Level.CONFIG, "com.rapid_i.deployment.update.client.PurchasedNotInstalledDialog.saving_ignored_extensions_file");
Document doc;
try {
doc = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
} catch (ParserConfigurationException e) {
LogService.getRoot().log(Level.WARNING,
I18N.getMessage(LogService.getRoot().getResourceBundle(),
"com.rapid_i.deployment.update.client.PurchasedNotInstalledDialog.creating_xml_document_error",
e),
e);
return;
}
Element root = doc.createElement(UpdateManager.NEVER_REMIND_INSTALL_EXTENSIONS_FILE_NAME);
doc.appendChild(root);
for (String i : purchasedModel.fetchPackageNames()) {
Element entryElem = doc.createElement("extension_name");
entryElem.setTextContent(i);
root.appendChild(entryElem);
}
File file = FileSystemService.getUserConfigFile(UpdateManager.NEVER_REMIND_INSTALL_EXTENSIONS_FILE_NAME);
try {
XMLTools.stream(doc, file, null);
} catch (XMLException e) {
LogService.getRoot().log(Level.WARNING,
I18N.getMessage(LogService.getRoot().getResourceBundle(),
"com.rapid_i.deployment.update.client.PurchasedNotInstalledDialog.saving_ignored_extensions_file_error",
e),
e);
}
}
}
| agpl-3.0 |
FreudianNM/openMAXIMS | Source Library/openmaxims_workspace/ValueObjects/src/ims/emergency/vo/domain/EDPartialAdmissionForDischargeDetailOutcomeVoAssembler.java | 28003 | //#############################################################################
//# #
//# Copyright (C) <2015> <IMS MAXIMS> #
//# #
//# This program is free software: you can redistribute it and/or modify #
//# it under the terms of the GNU Affero General Public License as #
//# published by the Free Software Foundation, either version 3 of the #
//# License, or (at your option) any later version. #
//# #
//# This program is distributed in the hope that it will be useful, #
//# but WITHOUT ANY WARRANTY; without even the implied warranty of #
//# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the #
//# GNU Affero General Public License for more details. #
//# #
//# You should have received a copy of the GNU Affero General Public License #
//# along with this program. If not, see <http://www.gnu.org/licenses/>. #
//# #
//# IMS MAXIMS provides absolutely NO GUARANTEE OF THE CLINICAL SAFTEY of #
//# this program. Users of this software do so entirely at their own risk. #
//# IMS MAXIMS only ensures the Clinical Safety of unaltered run-time #
//# software that it builds, deploys and maintains. #
//# #
//#############################################################################
//#EOH
/*
* This code was generated
* Copyright (C) 1995-2004 IMS MAXIMS plc. All rights reserved.
* IMS Development Environment (version 1.80 build 5589.25814)
* WARNING: DO NOT MODIFY the content of this file
* Generated on 12/10/2015, 13:25
*
*/
package ims.emergency.vo.domain;
import ims.vo.domain.DomainObjectMap;
import java.util.HashMap;
import org.hibernate.proxy.HibernateProxy;
/**
* @author Florin Blindu
*/
public class EDPartialAdmissionForDischargeDetailOutcomeVoAssembler
{
/**
* Copy one ValueObject to another
* @param valueObjectDest to be updated
* @param valueObjectSrc to copy values from
*/
public static ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo copy(ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo valueObjectDest, ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo valueObjectSrc)
{
if (null == valueObjectSrc)
{
return valueObjectSrc;
}
valueObjectDest.setID_EDPartialAdmission(valueObjectSrc.getID_EDPartialAdmission());
valueObjectDest.setIsRIE(valueObjectSrc.getIsRIE());
// DecisionToAdmitDateTime
valueObjectDest.setDecisionToAdmitDateTime(valueObjectSrc.getDecisionToAdmitDateTime());
// Specialty
valueObjectDest.setSpecialty(valueObjectSrc.getSpecialty());
// AllocatedStatus
valueObjectDest.setAllocatedStatus(valueObjectSrc.getAllocatedStatus());
// AllocatedBedType
valueObjectDest.setAllocatedBedType(valueObjectSrc.getAllocatedBedType());
// AuthoringInfo
valueObjectDest.setAuthoringInfo(valueObjectSrc.getAuthoringInfo());
// AllocatedDateTime
valueObjectDest.setAllocatedDateTime(valueObjectSrc.getAllocatedDateTime());
// AdmittingConsultant
valueObjectDest.setAdmittingConsultant(valueObjectSrc.getAdmittingConsultant());
// AccomodationRequestedType
valueObjectDest.setAccomodationRequestedType(valueObjectSrc.getAccomodationRequestedType());
return valueObjectDest;
}
/**
* Create the ValueObject collection to hold the set of DomainObjects.
* This is a convenience method only.
* It is intended to be used when one called to an Assembler is made.
* If more than one call to an Assembler is made then #createEDPartialAdmissionForDischargeDetailOutcomeVoCollectionFromEDPartialAdmission(DomainObjectMap, Set) should be used.
* @param domainObjectSet - Set of ims.emergency.domain.objects.EDPartialAdmission objects.
*/
public static ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVoCollection createEDPartialAdmissionForDischargeDetailOutcomeVoCollectionFromEDPartialAdmission(java.util.Set domainObjectSet)
{
return createEDPartialAdmissionForDischargeDetailOutcomeVoCollectionFromEDPartialAdmission(new DomainObjectMap(), domainObjectSet);
}
/**
* Create the ValueObject collection to hold the set of DomainObjects.
* @param map - maps DomainObjects to created ValueObjects
* @param domainObjectSet - Set of ims.emergency.domain.objects.EDPartialAdmission objects.
*/
public static ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVoCollection createEDPartialAdmissionForDischargeDetailOutcomeVoCollectionFromEDPartialAdmission(DomainObjectMap map, java.util.Set domainObjectSet)
{
ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVoCollection voList = new ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVoCollection();
if ( null == domainObjectSet )
{
return voList;
}
int rieCount=0;
int activeCount=0;
java.util.Iterator iterator = domainObjectSet.iterator();
while( iterator.hasNext() )
{
ims.emergency.domain.objects.EDPartialAdmission domainObject = (ims.emergency.domain.objects.EDPartialAdmission) iterator.next();
ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo vo = create(map, domainObject);
if (vo != null)
voList.add(vo);
if (domainObject != null)
{
if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true)
rieCount++;
else
activeCount++;
}
}
voList.setRieCount(rieCount);
voList.setActiveCount(activeCount);
return voList;
}
/**
* Create the ValueObject collection to hold the list of DomainObjects.
* @param domainObjectList - List of ims.emergency.domain.objects.EDPartialAdmission objects.
*/
public static ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVoCollection createEDPartialAdmissionForDischargeDetailOutcomeVoCollectionFromEDPartialAdmission(java.util.List domainObjectList)
{
return createEDPartialAdmissionForDischargeDetailOutcomeVoCollectionFromEDPartialAdmission(new DomainObjectMap(), domainObjectList);
}
/**
* Create the ValueObject collection to hold the list of DomainObjects.
* @param map - maps DomainObjects to created ValueObjects
* @param domainObjectList - List of ims.emergency.domain.objects.EDPartialAdmission objects.
*/
public static ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVoCollection createEDPartialAdmissionForDischargeDetailOutcomeVoCollectionFromEDPartialAdmission(DomainObjectMap map, java.util.List domainObjectList)
{
ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVoCollection voList = new ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVoCollection();
if ( null == domainObjectList )
{
return voList;
}
int rieCount=0;
int activeCount=0;
for (int i = 0; i < domainObjectList.size(); i++)
{
ims.emergency.domain.objects.EDPartialAdmission domainObject = (ims.emergency.domain.objects.EDPartialAdmission) domainObjectList.get(i);
ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo vo = create(map, domainObject);
if (vo != null)
voList.add(vo);
if (domainObject != null)
{
if (domainObject.getIsRIE() != null && domainObject.getIsRIE().booleanValue() == true)
rieCount++;
else
activeCount++;
}
}
voList.setRieCount(rieCount);
voList.setActiveCount(activeCount);
return voList;
}
/**
* Create the ims.emergency.domain.objects.EDPartialAdmission set from the value object collection.
* @param domainFactory - used to create existing (persistent) domain objects.
* @param voCollection - the collection of value objects
*/
public static java.util.Set extractEDPartialAdmissionSet(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVoCollection voCollection)
{
return extractEDPartialAdmissionSet(domainFactory, voCollection, null, new HashMap());
}
public static java.util.Set extractEDPartialAdmissionSet(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVoCollection voCollection, java.util.Set domainObjectSet, HashMap domMap)
{
int size = (null == voCollection) ? 0 : voCollection.size();
if (domainObjectSet == null)
{
domainObjectSet = new java.util.HashSet();
}
java.util.Set newSet = new java.util.HashSet();
for(int i=0; i<size; i++)
{
ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo vo = voCollection.get(i);
ims.emergency.domain.objects.EDPartialAdmission domainObject = EDPartialAdmissionForDischargeDetailOutcomeVoAssembler.extractEDPartialAdmission(domainFactory, vo, domMap);
//TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it.
if (domainObject == null)
{
continue;
}
//Trying to avoid the hibernate collection being marked as dirty via its public interface methods. (like add)
if (!domainObjectSet.contains(domainObject)) domainObjectSet.add(domainObject);
newSet.add(domainObject);
}
java.util.Set removedSet = new java.util.HashSet();
java.util.Iterator iter = domainObjectSet.iterator();
//Find out which objects need to be removed
while (iter.hasNext())
{
ims.domain.DomainObject o = (ims.domain.DomainObject)iter.next();
if ((o == null || o.getIsRIE() == null || !o.getIsRIE().booleanValue()) && !newSet.contains(o))
{
removedSet.add(o);
}
}
iter = removedSet.iterator();
//Remove the unwanted objects
while (iter.hasNext())
{
domainObjectSet.remove(iter.next());
}
return domainObjectSet;
}
/**
* Create the ims.emergency.domain.objects.EDPartialAdmission list from the value object collection.
* @param domainFactory - used to create existing (persistent) domain objects.
* @param voCollection - the collection of value objects
*/
public static java.util.List extractEDPartialAdmissionList(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVoCollection voCollection)
{
return extractEDPartialAdmissionList(domainFactory, voCollection, null, new HashMap());
}
public static java.util.List extractEDPartialAdmissionList(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVoCollection voCollection, java.util.List domainObjectList, HashMap domMap)
{
int size = (null == voCollection) ? 0 : voCollection.size();
if (domainObjectList == null)
{
domainObjectList = new java.util.ArrayList();
}
for(int i=0; i<size; i++)
{
ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo vo = voCollection.get(i);
ims.emergency.domain.objects.EDPartialAdmission domainObject = EDPartialAdmissionForDischargeDetailOutcomeVoAssembler.extractEDPartialAdmission(domainFactory, vo, domMap);
//TODO: This can only occur in the situation of a stale object exception. For now leave it to the Interceptor to handle it.
if (domainObject == null)
{
continue;
}
int domIdx = domainObjectList.indexOf(domainObject);
if (domIdx == -1)
{
domainObjectList.add(i, domainObject);
}
else if (i != domIdx && i < domainObjectList.size())
{
Object tmp = domainObjectList.get(i);
domainObjectList.set(i, domainObjectList.get(domIdx));
domainObjectList.set(domIdx, tmp);
}
}
//Remove all ones in domList where index > voCollection.size() as these should
//now represent the ones removed from the VO collection. No longer referenced.
int i1=domainObjectList.size();
while (i1 > size)
{
domainObjectList.remove(i1-1);
i1=domainObjectList.size();
}
return domainObjectList;
}
/**
* Create the ValueObject from the ims.emergency.domain.objects.EDPartialAdmission object.
* @param domainObject ims.emergency.domain.objects.EDPartialAdmission
*/
public static ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo create(ims.emergency.domain.objects.EDPartialAdmission domainObject)
{
if (null == domainObject)
{
return null;
}
DomainObjectMap map = new DomainObjectMap();
return create(map, domainObject);
}
/**
* Create the ValueObject from the ims.emergency.domain.objects.EDPartialAdmission object.
* @param map DomainObjectMap of DomainObjects to already created ValueObjects.
* @param domainObject
*/
public static ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo create(DomainObjectMap map, ims.emergency.domain.objects.EDPartialAdmission domainObject)
{
if (null == domainObject)
{
return null;
}
// check if the domainObject already has a valueObject created for it
ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo valueObject = (ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo) map.getValueObject(domainObject, ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo.class);
if ( null == valueObject )
{
valueObject = new ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo(domainObject.getId(), domainObject.getVersion());
map.addValueObject(domainObject, valueObject);
valueObject = insert(map, valueObject, domainObject);
}
return valueObject;
}
/**
* Update the ValueObject with the Domain Object.
* @param valueObject to be updated
* @param domainObject ims.emergency.domain.objects.EDPartialAdmission
*/
public static ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo insert(ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo valueObject, ims.emergency.domain.objects.EDPartialAdmission domainObject)
{
if (null == domainObject)
{
return valueObject;
}
DomainObjectMap map = new DomainObjectMap();
return insert(map, valueObject, domainObject);
}
/**
* Update the ValueObject with the Domain Object.
* @param map DomainObjectMap of DomainObjects to already created ValueObjects.
* @param valueObject to be updated
* @param domainObject ims.emergency.domain.objects.EDPartialAdmission
*/
public static ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo insert(DomainObjectMap map, ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo valueObject, ims.emergency.domain.objects.EDPartialAdmission domainObject)
{
if (null == domainObject)
{
return valueObject;
}
if (null == map)
{
map = new DomainObjectMap();
}
valueObject.setID_EDPartialAdmission(domainObject.getId());
valueObject.setIsRIE(domainObject.getIsRIE());
// If this is a recordedInError record, and the domainObject
// value isIncludeRecord has not been set, then we return null and
// not the value object
if (valueObject.getIsRIE() != null && valueObject.getIsRIE().booleanValue() == true && !domainObject.isIncludeRecord())
return null;
// If this is not a recordedInError record, and the domainObject
// value isIncludeRecord has been set, then we return null and
// not the value object
if ((valueObject.getIsRIE() == null || valueObject.getIsRIE().booleanValue() == false) && domainObject.isIncludeRecord())
return null;
// DecisionToAdmitDateTime
java.util.Date DecisionToAdmitDateTime = domainObject.getDecisionToAdmitDateTime();
if ( null != DecisionToAdmitDateTime )
{
valueObject.setDecisionToAdmitDateTime(new ims.framework.utils.DateTime(DecisionToAdmitDateTime) );
}
// Specialty
ims.domain.lookups.LookupInstance instance2 = domainObject.getSpecialty();
if ( null != instance2 ) {
ims.framework.utils.ImagePath img = null;
ims.framework.utils.Color color = null;
img = null;
if (instance2.getImage() != null)
{
img = new ims.framework.utils.ImagePath(instance2.getImage().getImageId(), instance2.getImage().getImagePath());
}
color = instance2.getColor();
if (color != null)
color.getValue();
ims.core.vo.lookups.Specialty voLookup2 = new ims.core.vo.lookups.Specialty(instance2.getId(),instance2.getText(), instance2.isActive(), null, img, color);
ims.core.vo.lookups.Specialty parentVoLookup2 = voLookup2;
ims.domain.lookups.LookupInstance parent2 = instance2.getParent();
while (parent2 != null)
{
if (parent2.getImage() != null)
{
img = new ims.framework.utils.ImagePath(parent2.getImage().getImageId(), parent2.getImage().getImagePath() );
}
else
{
img = null;
}
color = parent2.getColor();
if (color != null)
color.getValue();
parentVoLookup2.setParent(new ims.core.vo.lookups.Specialty(parent2.getId(),parent2.getText(), parent2.isActive(), null, img, color));
parentVoLookup2 = parentVoLookup2.getParent();
parent2 = parent2.getParent();
}
valueObject.setSpecialty(voLookup2);
}
// AllocatedStatus
ims.domain.lookups.LookupInstance instance3 = domainObject.getAllocatedStatus();
if ( null != instance3 ) {
ims.framework.utils.ImagePath img = null;
ims.framework.utils.Color color = null;
img = null;
if (instance3.getImage() != null)
{
img = new ims.framework.utils.ImagePath(instance3.getImage().getImageId(), instance3.getImage().getImagePath());
}
color = instance3.getColor();
if (color != null)
color.getValue();
ims.emergency.vo.lookups.AllocationStatus voLookup3 = new ims.emergency.vo.lookups.AllocationStatus(instance3.getId(),instance3.getText(), instance3.isActive(), null, img, color);
ims.emergency.vo.lookups.AllocationStatus parentVoLookup3 = voLookup3;
ims.domain.lookups.LookupInstance parent3 = instance3.getParent();
while (parent3 != null)
{
if (parent3.getImage() != null)
{
img = new ims.framework.utils.ImagePath(parent3.getImage().getImageId(), parent3.getImage().getImagePath() );
}
else
{
img = null;
}
color = parent3.getColor();
if (color != null)
color.getValue();
parentVoLookup3.setParent(new ims.emergency.vo.lookups.AllocationStatus(parent3.getId(),parent3.getText(), parent3.isActive(), null, img, color));
parentVoLookup3 = parentVoLookup3.getParent();
parent3 = parent3.getParent();
}
valueObject.setAllocatedStatus(voLookup3);
}
// AllocatedBedType
ims.domain.lookups.LookupInstance instance4 = domainObject.getAllocatedBedType();
if ( null != instance4 ) {
ims.framework.utils.ImagePath img = null;
ims.framework.utils.Color color = null;
img = null;
if (instance4.getImage() != null)
{
img = new ims.framework.utils.ImagePath(instance4.getImage().getImageId(), instance4.getImage().getImagePath());
}
color = instance4.getColor();
if (color != null)
color.getValue();
ims.emergency.vo.lookups.AllocatedBedType voLookup4 = new ims.emergency.vo.lookups.AllocatedBedType(instance4.getId(),instance4.getText(), instance4.isActive(), null, img, color);
ims.emergency.vo.lookups.AllocatedBedType parentVoLookup4 = voLookup4;
ims.domain.lookups.LookupInstance parent4 = instance4.getParent();
while (parent4 != null)
{
if (parent4.getImage() != null)
{
img = new ims.framework.utils.ImagePath(parent4.getImage().getImageId(), parent4.getImage().getImagePath() );
}
else
{
img = null;
}
color = parent4.getColor();
if (color != null)
color.getValue();
parentVoLookup4.setParent(new ims.emergency.vo.lookups.AllocatedBedType(parent4.getId(),parent4.getText(), parent4.isActive(), null, img, color));
parentVoLookup4 = parentVoLookup4.getParent();
parent4 = parent4.getParent();
}
valueObject.setAllocatedBedType(voLookup4);
}
// AuthoringInfo
valueObject.setAuthoringInfo(ims.core.vo.domain.AuthoringInformationVoAssembler.create(map, domainObject.getAuthoringInfo()) );
// AllocatedDateTime
java.util.Date AllocatedDateTime = domainObject.getAllocatedDateTime();
if ( null != AllocatedDateTime )
{
valueObject.setAllocatedDateTime(new ims.framework.utils.DateTime(AllocatedDateTime) );
}
// AdmittingConsultant
valueObject.setAdmittingConsultant(ims.core.vo.domain.HcpMinVoAssembler.create(map, domainObject.getAdmittingConsultant()) );
// AccomodationRequestedType
ims.domain.lookups.LookupInstance instance8 = domainObject.getAccomodationRequestedType();
if ( null != instance8 ) {
ims.framework.utils.ImagePath img = null;
ims.framework.utils.Color color = null;
img = null;
if (instance8.getImage() != null)
{
img = new ims.framework.utils.ImagePath(instance8.getImage().getImageId(), instance8.getImage().getImagePath());
}
color = instance8.getColor();
if (color != null)
color.getValue();
ims.core.vo.lookups.AccomodationRequestedType voLookup8 = new ims.core.vo.lookups.AccomodationRequestedType(instance8.getId(),instance8.getText(), instance8.isActive(), null, img, color);
ims.core.vo.lookups.AccomodationRequestedType parentVoLookup8 = voLookup8;
ims.domain.lookups.LookupInstance parent8 = instance8.getParent();
while (parent8 != null)
{
if (parent8.getImage() != null)
{
img = new ims.framework.utils.ImagePath(parent8.getImage().getImageId(), parent8.getImage().getImagePath() );
}
else
{
img = null;
}
color = parent8.getColor();
if (color != null)
color.getValue();
parentVoLookup8.setParent(new ims.core.vo.lookups.AccomodationRequestedType(parent8.getId(),parent8.getText(), parent8.isActive(), null, img, color));
parentVoLookup8 = parentVoLookup8.getParent();
parent8 = parent8.getParent();
}
valueObject.setAccomodationRequestedType(voLookup8);
}
return valueObject;
}
/**
* Create the domain object from the value object.
* @param domainFactory - used to create existing (persistent) domain objects.
* @param valueObject - extract the domain object fields from this.
*/
public static ims.emergency.domain.objects.EDPartialAdmission extractEDPartialAdmission(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo valueObject)
{
return extractEDPartialAdmission(domainFactory, valueObject, new HashMap());
}
public static ims.emergency.domain.objects.EDPartialAdmission extractEDPartialAdmission(ims.domain.ILightweightDomainFactory domainFactory, ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo valueObject, HashMap domMap)
{
if (null == valueObject)
{
return null;
}
Integer id = valueObject.getID_EDPartialAdmission();
ims.emergency.domain.objects.EDPartialAdmission domainObject = null;
if ( null == id)
{
if (domMap.get(valueObject) != null)
{
return (ims.emergency.domain.objects.EDPartialAdmission)domMap.get(valueObject);
}
// ims.emergency.vo.EDPartialAdmissionForDischargeDetailOutcomeVo ID_EDPartialAdmission field is unknown
domainObject = new ims.emergency.domain.objects.EDPartialAdmission();
domMap.put(valueObject, domainObject);
}
else
{
String key = (valueObject.getClass().getName() + "__" + valueObject.getID_EDPartialAdmission());
if (domMap.get(key) != null)
{
return (ims.emergency.domain.objects.EDPartialAdmission)domMap.get(key);
}
domainObject = (ims.emergency.domain.objects.EDPartialAdmission) domainFactory.getDomainObject(ims.emergency.domain.objects.EDPartialAdmission.class, id );
//TODO: Not sure how this should be handled. Effectively it must be a staleobject exception, but maybe should be handled as that further up.
if (domainObject == null)
return null;
domMap.put(key, domainObject);
}
domainObject.setVersion(valueObject.getVersion_EDPartialAdmission());
ims.framework.utils.DateTime dateTime1 = valueObject.getDecisionToAdmitDateTime();
java.util.Date value1 = null;
if ( dateTime1 != null )
{
value1 = dateTime1.getJavaDate();
}
domainObject.setDecisionToAdmitDateTime(value1);
// create LookupInstance from vo LookupType
ims.domain.lookups.LookupInstance value2 = null;
if ( null != valueObject.getSpecialty() )
{
value2 =
domainFactory.getLookupInstance(valueObject.getSpecialty().getID());
}
domainObject.setSpecialty(value2);
// create LookupInstance from vo LookupType
ims.domain.lookups.LookupInstance value3 = null;
if ( null != valueObject.getAllocatedStatus() )
{
value3 =
domainFactory.getLookupInstance(valueObject.getAllocatedStatus().getID());
}
domainObject.setAllocatedStatus(value3);
// create LookupInstance from vo LookupType
ims.domain.lookups.LookupInstance value4 = null;
if ( null != valueObject.getAllocatedBedType() )
{
value4 =
domainFactory.getLookupInstance(valueObject.getAllocatedBedType().getID());
}
domainObject.setAllocatedBedType(value4);
// SaveAsRefVO - treated as a refVo in extract methods
ims.core.clinical.domain.objects.AuthoringInformation value5 = null;
if ( null != valueObject.getAuthoringInfo() )
{
if (valueObject.getAuthoringInfo().getBoId() == null)
{
if (domMap.get(valueObject.getAuthoringInfo()) != null)
{
value5 = (ims.core.clinical.domain.objects.AuthoringInformation)domMap.get(valueObject.getAuthoringInfo());
}
}
else
{
value5 = (ims.core.clinical.domain.objects.AuthoringInformation)domainFactory.getDomainObject(ims.core.clinical.domain.objects.AuthoringInformation.class, valueObject.getAuthoringInfo().getBoId());
}
}
domainObject.setAuthoringInfo(value5);
ims.framework.utils.DateTime dateTime6 = valueObject.getAllocatedDateTime();
java.util.Date value6 = null;
if ( dateTime6 != null )
{
value6 = dateTime6.getJavaDate();
}
domainObject.setAllocatedDateTime(value6);
// SaveAsRefVO - treated as a refVo in extract methods
ims.core.resource.people.domain.objects.Hcp value7 = null;
if ( null != valueObject.getAdmittingConsultant() )
{
if (valueObject.getAdmittingConsultant().getBoId() == null)
{
if (domMap.get(valueObject.getAdmittingConsultant()) != null)
{
value7 = (ims.core.resource.people.domain.objects.Hcp)domMap.get(valueObject.getAdmittingConsultant());
}
}
else
{
value7 = (ims.core.resource.people.domain.objects.Hcp)domainFactory.getDomainObject(ims.core.resource.people.domain.objects.Hcp.class, valueObject.getAdmittingConsultant().getBoId());
}
}
domainObject.setAdmittingConsultant(value7);
// create LookupInstance from vo LookupType
ims.domain.lookups.LookupInstance value8 = null;
if ( null != valueObject.getAccomodationRequestedType() )
{
value8 =
domainFactory.getLookupInstance(valueObject.getAccomodationRequestedType().getID());
}
domainObject.setAccomodationRequestedType(value8);
return domainObject;
}
}
| agpl-3.0 |
maduhu/knx-jbilling2.2.0 | build/jsp-classes/com/sapienter/jbilling/client/jspc/user/listProcessSuccessfulUsersTop_jsp.java | 13697 | package com.sapienter.jbilling.client.jspc.user;
import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.jsp.*;
import com.sapienter.jbilling.client.util.Constants;
public final class listProcessSuccessfulUsersTop_jsp extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent {
private static final JspFactory _jspxFactory = JspFactory.getDefaultFactory();
private static java.util.List _jspx_dependants;
private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fhtml_005fmessages_0026_005fmessage_005fid;
private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fbean_005fwrite_0026_005fname_005fnobody;
private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fbean_005fdefine_0026_005fvalue_005ftoScope_005fid_005fnobody;
private org.apache.jasper.runtime.TagHandlerPool _005fjspx_005ftagPool_005fjbilling_005fgenericList_0026_005ftype_005fsetup_005fnobody;
private javax.el.ExpressionFactory _el_expressionfactory;
private org.apache.AnnotationProcessor _jsp_annotationprocessor;
public Object getDependants() {
return _jspx_dependants;
}
public void _jspInit() {
_005fjspx_005ftagPool_005fhtml_005fmessages_0026_005fmessage_005fid = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_005fjspx_005ftagPool_005fbean_005fwrite_0026_005fname_005fnobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_005fjspx_005ftagPool_005fbean_005fdefine_0026_005fvalue_005ftoScope_005fid_005fnobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_005fjspx_005ftagPool_005fjbilling_005fgenericList_0026_005ftype_005fsetup_005fnobody = org.apache.jasper.runtime.TagHandlerPool.getTagHandlerPool(getServletConfig());
_el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();
_jsp_annotationprocessor = (org.apache.AnnotationProcessor) getServletConfig().getServletContext().getAttribute(org.apache.AnnotationProcessor.class.getName());
}
public void _jspDestroy() {
_005fjspx_005ftagPool_005fhtml_005fmessages_0026_005fmessage_005fid.release();
_005fjspx_005ftagPool_005fbean_005fwrite_0026_005fname_005fnobody.release();
_005fjspx_005ftagPool_005fbean_005fdefine_0026_005fvalue_005ftoScope_005fid_005fnobody.release();
_005fjspx_005ftagPool_005fjbilling_005fgenericList_0026_005ftype_005fsetup_005fnobody.release();
}
public void _jspService(HttpServletRequest request, HttpServletResponse response)
throws java.io.IOException, ServletException {
PageContext pageContext = null;
HttpSession session = null;
ServletContext application = null;
ServletConfig config = null;
JspWriter out = null;
Object page = this;
JspWriter _jspx_out = null;
PageContext _jspx_page_context = null;
try {
response.setContentType("text/html");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
out.write("\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n\r\n");
out.write("\r\n\r\n");
// html:messages
org.apache.struts.taglib.html.MessagesTag _jspx_th_html_005fmessages_005f0 = (org.apache.struts.taglib.html.MessagesTag) _005fjspx_005ftagPool_005fhtml_005fmessages_0026_005fmessage_005fid.get(org.apache.struts.taglib.html.MessagesTag.class);
_jspx_th_html_005fmessages_005f0.setPageContext(_jspx_page_context);
_jspx_th_html_005fmessages_005f0.setParent(null);
// /user/listProcessSuccessfulUsersTop.jsp(30,0) name = message type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_html_005fmessages_005f0.setMessage("true");
// /user/listProcessSuccessfulUsersTop.jsp(30,0) name = id type = java.lang.String reqTime = false required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_html_005fmessages_005f0.setId("myMessage");
int _jspx_eval_html_005fmessages_005f0 = _jspx_th_html_005fmessages_005f0.doStartTag();
if (_jspx_eval_html_005fmessages_005f0 != javax.servlet.jsp.tagext.Tag.SKIP_BODY) {
java.lang.String myMessage = null;
if (_jspx_eval_html_005fmessages_005f0 != javax.servlet.jsp.tagext.Tag.EVAL_BODY_INCLUDE) {
out = _jspx_page_context.pushBody();
_jspx_th_html_005fmessages_005f0.setBodyContent((javax.servlet.jsp.tagext.BodyContent) out);
_jspx_th_html_005fmessages_005f0.doInitBody();
}
myMessage = (java.lang.String) _jspx_page_context.findAttribute("myMessage");
do {
out.write("\r\n\t<p>");
if (_jspx_meth_bean_005fwrite_005f0(_jspx_th_html_005fmessages_005f0, _jspx_page_context))
return;
out.write("</p>\r\n");
int evalDoAfterBody = _jspx_th_html_005fmessages_005f0.doAfterBody();
myMessage = (java.lang.String) _jspx_page_context.findAttribute("myMessage");
if (evalDoAfterBody != javax.servlet.jsp.tagext.BodyTag.EVAL_BODY_AGAIN)
break;
} while (true);
if (_jspx_eval_html_005fmessages_005f0 != javax.servlet.jsp.tagext.Tag.EVAL_BODY_INCLUDE) {
out = _jspx_page_context.popBody();
}
}
if (_jspx_th_html_005fmessages_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_005fjspx_005ftagPool_005fhtml_005fmessages_0026_005fmessage_005fid.reuse(_jspx_th_html_005fmessages_005f0);
return;
}
_005fjspx_005ftagPool_005fhtml_005fmessages_0026_005fmessage_005fid.reuse(_jspx_th_html_005fmessages_005f0);
out.write("\r\n\r\n");
out.write('\r');
out.write('\n');
// bean:define
org.apache.struts.taglib.bean.DefineTag _jspx_th_bean_005fdefine_005f0 = (org.apache.struts.taglib.bean.DefineTag) _005fjspx_005ftagPool_005fbean_005fdefine_0026_005fvalue_005ftoScope_005fid_005fnobody.get(org.apache.struts.taglib.bean.DefineTag.class);
_jspx_th_bean_005fdefine_005f0.setPageContext(_jspx_page_context);
_jspx_th_bean_005fdefine_005f0.setParent(null);
// /user/listProcessSuccessfulUsersTop.jsp(36,0) name = id type = java.lang.String reqTime = false required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_bean_005fdefine_005f0.setId("forward_from");
// /user/listProcessSuccessfulUsersTop.jsp(36,0) name = value type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_bean_005fdefine_005f0.setValue(Constants.FORWARD_USER_VIEW);
// /user/listProcessSuccessfulUsersTop.jsp(36,0) name = toScope type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_bean_005fdefine_005f0.setToScope("session");
int _jspx_eval_bean_005fdefine_005f0 = _jspx_th_bean_005fdefine_005f0.doStartTag();
if (_jspx_th_bean_005fdefine_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_005fjspx_005ftagPool_005fbean_005fdefine_0026_005fvalue_005ftoScope_005fid_005fnobody.reuse(_jspx_th_bean_005fdefine_005f0);
return;
}
_005fjspx_005ftagPool_005fbean_005fdefine_0026_005fvalue_005ftoScope_005fid_005fnobody.reuse(_jspx_th_bean_005fdefine_005f0);
java.lang.String forward_from = null;
forward_from = (java.lang.String) _jspx_page_context.findAttribute("forward_from");
out.write("\r\n\r\n");
// bean:define
org.apache.struts.taglib.bean.DefineTag _jspx_th_bean_005fdefine_005f1 = (org.apache.struts.taglib.bean.DefineTag) _005fjspx_005ftagPool_005fbean_005fdefine_0026_005fvalue_005ftoScope_005fid_005fnobody.get(org.apache.struts.taglib.bean.DefineTag.class);
_jspx_th_bean_005fdefine_005f1.setPageContext(_jspx_page_context);
_jspx_th_bean_005fdefine_005f1.setParent(null);
// /user/listProcessSuccessfulUsersTop.jsp(40,0) name = id type = java.lang.String reqTime = false required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_bean_005fdefine_005f1.setId("forward_to");
// /user/listProcessSuccessfulUsersTop.jsp(40,0) name = value type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_bean_005fdefine_005f1.setValue(Constants.FORWARD_USER_VIEW);
// /user/listProcessSuccessfulUsersTop.jsp(40,0) name = toScope type = null reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_bean_005fdefine_005f1.setToScope("session");
int _jspx_eval_bean_005fdefine_005f1 = _jspx_th_bean_005fdefine_005f1.doStartTag();
if (_jspx_th_bean_005fdefine_005f1.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_005fjspx_005ftagPool_005fbean_005fdefine_0026_005fvalue_005ftoScope_005fid_005fnobody.reuse(_jspx_th_bean_005fdefine_005f1);
return;
}
_005fjspx_005ftagPool_005fbean_005fdefine_0026_005fvalue_005ftoScope_005fid_005fnobody.reuse(_jspx_th_bean_005fdefine_005f1);
java.lang.String forward_to = null;
forward_to = (java.lang.String) _jspx_page_context.findAttribute("forward_to");
out.write("\r\n\r\n");
// jbilling:genericList
com.sapienter.jbilling.client.list.GenericListTag _jspx_th_jbilling_005fgenericList_005f0 = (com.sapienter.jbilling.client.list.GenericListTag) _005fjspx_005ftagPool_005fjbilling_005fgenericList_0026_005ftype_005fsetup_005fnobody.get(com.sapienter.jbilling.client.list.GenericListTag.class);
_jspx_th_jbilling_005fgenericList_005f0.setPageContext(_jspx_page_context);
_jspx_th_jbilling_005fgenericList_005f0.setParent(null);
// /user/listProcessSuccessfulUsersTop.jsp(44,0) name = setup type = java.lang.Boolean reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_jbilling_005fgenericList_005f0.setSetup(new Boolean(true));
// /user/listProcessSuccessfulUsersTop.jsp(44,0) name = type type = java.lang.String reqTime = true required = false fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_jbilling_005fgenericList_005f0.setType(Constants.LIST_TYPE_PROCESS_RUN_SUCCESSFULL_USERS);
int _jspx_eval_jbilling_005fgenericList_005f0 = _jspx_th_jbilling_005fgenericList_005f0.doStartTag();
if (_jspx_th_jbilling_005fgenericList_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_005fjspx_005ftagPool_005fjbilling_005fgenericList_0026_005ftype_005fsetup_005fnobody.reuse(_jspx_th_jbilling_005fgenericList_005f0);
return;
}
_005fjspx_005ftagPool_005fjbilling_005fgenericList_0026_005ftype_005fsetup_005fnobody.reuse(_jspx_th_jbilling_005fgenericList_005f0);
out.write(" \r\n \r\n");
} catch (Throwable t) {
if (!(t instanceof SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
try { out.clearBuffer(); } catch (java.io.IOException e) {}
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
}
private boolean _jspx_meth_bean_005fwrite_005f0(javax.servlet.jsp.tagext.JspTag _jspx_th_html_005fmessages_005f0, PageContext _jspx_page_context)
throws Throwable {
PageContext pageContext = _jspx_page_context;
JspWriter out = _jspx_page_context.getOut();
// bean:write
org.apache.struts.taglib.bean.WriteTag _jspx_th_bean_005fwrite_005f0 = (org.apache.struts.taglib.bean.WriteTag) _005fjspx_005ftagPool_005fbean_005fwrite_0026_005fname_005fnobody.get(org.apache.struts.taglib.bean.WriteTag.class);
_jspx_th_bean_005fwrite_005f0.setPageContext(_jspx_page_context);
_jspx_th_bean_005fwrite_005f0.setParent((javax.servlet.jsp.tagext.Tag) _jspx_th_html_005fmessages_005f0);
// /user/listProcessSuccessfulUsersTop.jsp(31,4) name = name type = null reqTime = true required = true fragment = false deferredValue = false expectedTypeName = null deferredMethod = false methodSignature = null
_jspx_th_bean_005fwrite_005f0.setName("myMessage");
int _jspx_eval_bean_005fwrite_005f0 = _jspx_th_bean_005fwrite_005f0.doStartTag();
if (_jspx_th_bean_005fwrite_005f0.doEndTag() == javax.servlet.jsp.tagext.Tag.SKIP_PAGE) {
_005fjspx_005ftagPool_005fbean_005fwrite_0026_005fname_005fnobody.reuse(_jspx_th_bean_005fwrite_005f0);
return true;
}
_005fjspx_005ftagPool_005fbean_005fwrite_0026_005fname_005fnobody.reuse(_jspx_th_bean_005fwrite_005f0);
return false;
}
}
| agpl-3.0 |
BiosemanticsDotOrg/GeneDiseasePlosBio | java/DataImport/src/JochemBuilder/KEGGcompound/KEGGcompoundImport.java | 3807 | /*
* Concept profile generation tool suite
* Copyright (C) 2015 Biosemantics Group, Erasmus University Medical Center,
* Rotterdam, The Netherlands
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>
*/
package JochemBuilder.KEGGcompound;
import org.erasmusmc.ontology.OntologyFileLoader;
import org.erasmusmc.ontology.OntologyStore;
import org.erasmusmc.ontology.ontologyutilities.OntologyCurator;
import org.erasmusmc.utilities.StringUtilities;
import JochemBuilder.SharedCurationScripts.CasperForJochem;
import JochemBuilder.SharedCurationScripts.CurateUsingManualCurationFile;
import JochemBuilder.SharedCurationScripts.RemoveDictAndCompanyNamesAtEndOfTerm;
import JochemBuilder.SharedCurationScripts.RewriteFurther;
import JochemBuilder.SharedCurationScripts.SaveOnlyCASandInchiEntries;
public class KEGGcompoundImport {
public static String date = "110809";
public static String home = "/home/khettne/Projects/Jochem";
public static String keggcImportFile = home+"/KEGG/Compound/compound";
public static String compoundToDrugMappingOutFile = home+"/KEGG/Compound/compoundToDrugMapping";
public static String keggcToInchiMappingFile = home+"/KEGG/Compound/compound.inchi";
public static String keggcDictionariesLog = home+"/KEGG/Compound/KEGGc_dictionaries_"+date+".log";
public static String keggcRewriteLog = home+"/KEGG/Compound/KEGGcCAS_casperFiltered_"+date+".log";
public static String keggcLowerCaseLog = home+"/KEGG/Compound/KEGGcCAS_lowerCase_"+date+".log";
public static String termsToRemove = "keggcTermsToRemove.txt";
public static String keggcCuratedOntologyPath = home+"/KEGG/Compound/KEGGcCAS_curated_"+date+".ontology";
public static String keggcCuratedLog = home+"/KEGG/Compound/KEGGcCAS_curated_"+date+".log";
public static void main(String[] args) {
OntologyStore ontology = new OntologyStore();
OntologyFileLoader loader = new OntologyFileLoader();
//Make unprocessed thesaurus
ChemicalsFromKEGGcompound keggchem = new ChemicalsFromKEGGcompound();
ontology = keggchem.run(keggcImportFile, compoundToDrugMappingOutFile);
RemoveDictAndCompanyNamesAtEndOfTerm remove = new RemoveDictAndCompanyNamesAtEndOfTerm();
ontology = remove.run(ontology, keggcDictionariesLog);
MapKEGGc2InChI mapOntology = new MapKEGGc2InChI();
ontology = mapOntology.map(ontology, keggcToInchiMappingFile);
// CAS and InChI
SaveOnlyCASandInchiEntries make = new SaveOnlyCASandInchiEntries();
ontology = make.run(ontology);
//Rewrite
CasperForJochem casper = new CasperForJochem();
casper.run(ontology, keggcRewriteLog);
// Make some entries lower case and filter further
RewriteFurther rewrite = new RewriteFurther();
ontology = rewrite.run(ontology, keggcLowerCaseLog);
//Remove terms based on medline frequency
CurateUsingManualCurationFile curate = new CurateUsingManualCurationFile();
ontology = curate.run(ontology, keggcCuratedLog,termsToRemove);
//Set default flags and save ontology
OntologyCurator curator = new OntologyCurator();
curator.curateAndPrepare(ontology);
loader.save(ontology,keggcCuratedOntologyPath);
System.out.println("Done! " + StringUtilities.now());
}
}
| agpl-3.0 |
xwiki-contrib/sankoreorg | xwiki-platform-oldcore/src/main/java/com/xpn/xwiki/objects/BaseProperty.java | 5379 | /*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*
*/
package com.xpn.xwiki.objects;
import java.io.IOException;
import java.io.Serializable;
import java.io.StringWriter;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.dom.DOMDocument;
import org.dom4j.dom.DOMElement;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import com.xpn.xwiki.web.Utils;
/**
* @version $Id$
*/
// TODO: shouldn't this be abstract? toFormString and toText
// will never work unless getValue is overriden
public class BaseProperty extends BaseElement implements PropertyInterface, Serializable, Cloneable
{
private BaseCollection object;
private int id;
/**
* {@inheritDoc}
*
* @see com.xpn.xwiki.objects.PropertyInterface#getObject()
*/
public BaseCollection getObject()
{
return this.object;
}
/**
* {@inheritDoc}
*
* @see com.xpn.xwiki.objects.PropertyInterface#setObject(com.xpn.xwiki.objects.BaseCollection)
*/
public void setObject(BaseCollection object)
{
this.object = object;
}
/**
* {@inheritDoc}
*
* @see com.xpn.xwiki.objects.BaseElement#equals(java.lang.Object)
*/
@Override
public boolean equals(Object el)
{
// Same Java object, they sure are equal
if (this == el) {
return true;
}
// I hate this.. needed for hibernate to find the object
// when loading the collections..
if ((this.object == null) || ((BaseProperty) el).getObject() == null) {
return (hashCode() == el.hashCode());
}
if (!super.equals(el)) {
return false;
}
return (getId() == ((BaseProperty) el).getId());
}
public int getId()
{
// I hate this.. needed for hibernate to find the object
// when loading the collections..
if (this.object == null) {
return this.id;
} else {
return getObject().getId();
}
}
/**
* {@inheritDoc}
*
* @see com.xpn.xwiki.objects.PropertyInterface#setId(int)
*/
public void setId(int id)
{
// I hate this.. needed for hibernate to find the object
// when loading the collections..
this.id = id;
}
/**
* {@inheritDoc}
*
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode()
{
// I hate this.. needed for hibernate to find the object
// when loading the collections..
return ("" + getId() + getName()).hashCode();
}
public String getClassType()
{
return getClass().getName();
}
public void setClassType(String type)
{
}
/**
* {@inheritDoc}
*
* @see com.xpn.xwiki.objects.BaseElement#clone()
*/
@Override
public Object clone()
{
BaseProperty property = (BaseProperty) super.clone();
property.setObject(getObject());
return property;
}
public Object getValue()
{
return null;
}
public void setValue(Object value)
{
}
/**
* {@inheritDoc}
*
* @see com.xpn.xwiki.objects.PropertyInterface#toXML()
*/
public Element toXML()
{
Element el = new DOMElement(getName());
Object value = getValue();
el.setText((value == null) ? "" : value.toString());
return el;
}
/**
* {@inheritDoc}
*
* @see com.xpn.xwiki.objects.PropertyInterface#toFormString()
*/
public String toFormString()
{
return Utils.formEncode(toText());
}
public String toText()
{
Object value = getValue();
return (value == null) ? "" : value.toString();
}
public String toXMLString()
{
Document doc = new DOMDocument();
doc.setRootElement(toXML());
OutputFormat outputFormat = new OutputFormat("", true);
StringWriter out = new StringWriter();
XMLWriter writer = new XMLWriter(out, outputFormat);
try {
writer.write(doc);
return out.toString();
} catch (IOException e) {
e.printStackTrace();
return "";
}
}
/**
* {@inheritDoc}
*
* @see java.lang.Object#toString()
*/
@Override
public String toString()
{
return toXMLString();
}
public Object getCustomMappingValue()
{
return getValue();
}
}
| lgpl-2.1 |
simon04/jfreechart | src/main/java/org/jfree/chart/Effect3D.java | 2135 | /* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2016, by Object Refinery Limited and Contributors.
*
* Project Info: http://www.jfree.org/jfreechart/index.html
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* [Oracle and Java are registered trademarks of Oracle and/or its affiliates.
* Other names may be trademarks of their respective owners.]
*
* -------------
* Effect3D.java
* -------------
* (C) Copyright 2002-2008, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes
* -------
* 05-Nov-2002 : Version 1 (DG);
* 14-Nov-2002 : Modified to have independent x and y offsets (DG);
*
*/
package org.jfree.chart;
/**
* An interface that should be implemented by renderers that use a 3D effect.
* This allows the axes to mirror the same effect by querying the renderer.
*/
public interface Effect3D {
/**
* Returns the x-offset (in Java2D units) for the 3D effect.
*
* @return The offset.
*/
public double getXOffset();
/**
* Returns the y-offset (in Java2D units) for the 3D effect.
*
* @return The offset.
*/
public double getYOffset();
}
| lgpl-2.1 |
yuan39/TuxGuitar | TuxGuitar/src/org/herac/tuxguitar/app/actions/layout/SetTablatureEnabledAction.java | 1189 | /*
* Created on 17-dic-2005
*
* TODO To change the template for this generated file go to
* Window - Preferences - Java - Code Style - Code Templates
*/
package org.herac.tuxguitar.app.actions.layout;
import org.herac.tuxguitar.app.actions.Action;
import org.herac.tuxguitar.app.actions.ActionData;
import org.herac.tuxguitar.graphics.control.TGLayout;
/**
* @author julian
*
* TODO To change the template for this generated type comment go to
* Window - Preferences - Java - Code Style - Code Templates
*/
public class SetTablatureEnabledAction extends Action{
public static final String NAME = "action.view.layout-set-tablature-enabled";
public SetTablatureEnabledAction() {
super(NAME, AUTO_LOCK | AUTO_UNLOCK | AUTO_UPDATE | KEY_BINDING_AVAILABLE);
}
protected int execute(ActionData actionData){
TGLayout layout = getEditor().getTablature().getViewLayout();
layout.setStyle( ( layout.getStyle() ^ TGLayout.DISPLAY_TABLATURE ) );
if((layout.getStyle() & TGLayout.DISPLAY_TABLATURE) == 0 && (layout.getStyle() & TGLayout.DISPLAY_SCORE) == 0 ){
layout.setStyle( ( layout.getStyle() ^ TGLayout.DISPLAY_SCORE ) );
}
updateTablature();
return 0;
}
}
| lgpl-2.1 |
jasonchaffee/checkstyle | src/main/java/com/puppycrawl/tools/checkstyle/checks/coding/OneStatementPerLineCheck.java | 6201 | ////////////////////////////////////////////////////////////////////////////////
// checkstyle: Checks Java source code for adherence to a set of rules.
// Copyright (C) 2001-2015 the original author or authors.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
////////////////////////////////////////////////////////////////////////////////
package com.puppycrawl.tools.checkstyle.checks.coding;
import com.puppycrawl.tools.checkstyle.api.Check;
import com.puppycrawl.tools.checkstyle.api.DetailAST;
import com.puppycrawl.tools.checkstyle.api.TokenTypes;
/**
* Restricts the number of statements per line to one.
* <p>
* Rationale: It's very difficult to read multiple statements on one line.
* </p>
* <p>
* In the Java programming language, statements are the fundamental unit of
* execution. All statements except blocks are terminated by a semicolon.
* Blocks are denoted by open and close curly braces.
* </p>
* <p>
* OneStatementPerLineCheck checks the following types of statements:
* variable declaration statements, empty statements, assignment statements,
* expression statements, increment statements, object creation statements,
* 'for loop' statements, 'break' statements, 'continue' statements,
* 'return' statements, import statements.
* </p>
* <p>
* The following examples will be flagged as a violation:
* </p>
* <pre>
* //Each line causes violation:
* int var1; int var2;
* var1 = 1; var2 = 2;
* int var1 = 1; int var2 = 2;
* var1++; var2++;
* Object obj1 = new Object(); Object obj2 = new Object();
* import java.io.EOFException; import java.io.BufferedReader;
* ;; //two empty statements on the same line.
*
* //Multi-line statements:
* int var1 = 1
* ; var2 = 2; //violation here
* int o = 1, p = 2,
* r = 5; int t; //violation here
* </pre>
*
* @author Alexander Jesse
* @author Oliver Burn
* @author Andrei Selkin
*/
public final class OneStatementPerLineCheck extends Check {
/**
* A key is pointing to the warning message text in "messages.properties"
* file.
*/
public static final String MSG_KEY = "multiple.statements.line";
/**
* Hold the line-number where the last statement ended.
*/
private int lastStatementEnd = -1;
/**
* Hold the line-number where the last 'for-loop' statement ended.
*/
private int forStatementEnd = -1;
/**
* The for-header usually has 3 statements on one line, but THIS IS OK.
*/
private boolean inForHeader;
@Override
public int[] getDefaultTokens() {
return getAcceptableTokens();
}
@Override
public int[] getAcceptableTokens() {
return new int[]{
TokenTypes.SEMI, TokenTypes.FOR_INIT,
TokenTypes.FOR_ITERATOR,
};
}
@Override
public int[] getRequiredTokens() {
return getAcceptableTokens();
}
@Override
public void beginTree(DetailAST rootAST) {
inForHeader = false;
lastStatementEnd = -1;
forStatementEnd = -1;
}
@Override
public void visitToken(DetailAST ast) {
switch (ast.getType()) {
case TokenTypes.SEMI:
DetailAST currentStatement = ast;
if (isMultilineStatement(currentStatement)) {
currentStatement = ast.getPreviousSibling();
}
if (isOnTheSameLine(currentStatement, lastStatementEnd,
forStatementEnd) && !inForHeader) {
log(ast, MSG_KEY);
}
break;
case TokenTypes.FOR_ITERATOR:
forStatementEnd = ast.getLineNo();
break;
default:
inForHeader = true;
break;
}
}
@Override
public void leaveToken(DetailAST ast) {
switch (ast.getType()) {
case TokenTypes.SEMI:
lastStatementEnd = ast.getLineNo();
forStatementEnd = -1;
break;
case TokenTypes.FOR_ITERATOR:
inForHeader = false;
break;
default:
break;
}
}
/**
* Checks whether two statements are on the same line.
* @param ast token for the current statement.
* @param lastStatementEnd the line-number where the last statement ended.
* @param forStatementEnd the line-number where the last 'for-loop'
* statement ended.
* @return true if two statements are on the same line.
*/
private static boolean isOnTheSameLine(DetailAST ast, int lastStatementEnd,
int forStatementEnd) {
return lastStatementEnd == ast.getLineNo() && forStatementEnd != ast.getLineNo();
}
/**
* Checks whether statement is multiline.
* @param ast token for the current statement.
* @return true if one statement is distributed over two or more lines.
*/
private static boolean isMultilineStatement(DetailAST ast) {
final boolean multiline;
if (ast.getPreviousSibling() == null) {
multiline = false;
}
else {
final DetailAST prevSibling = ast.getPreviousSibling();
multiline = prevSibling.getLineNo() != ast.getLineNo()
&& ast.getParent() != null;
}
return multiline;
}
}
| lgpl-2.1 |
oclab/howto-callme | kurento-http-player/src/main/java/org/kurento/tutorial/player/KurentoHttpPlayer.java | 2724 | /*
* (C) Copyright 2014 Kurento (http://kurento.org/)
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 2.1 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl-2.1.html
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
*/
package org.kurento.tutorial.player;
import java.awt.Desktop;
import java.io.IOException;
import java.net.URI;
import java.net.URISyntaxException;
import org.kurento.client.EndOfStreamEvent;
import org.kurento.client.EventListener;
import org.kurento.client.FaceOverlayFilter;
import org.kurento.client.HttpGetEndpoint;
import org.kurento.client.MediaPipeline;
import org.kurento.client.PlayerEndpoint;
import org.kurento.client.KurentoClient;
/**
* HTTP Player with Kurento; the media pipeline is composed by a PlayerEndpoint
* connected to a filter (FaceOverlay) and an HttpGetEnpoint; the default
* desktop web browser is launched to play the video.
*
* @author Micael Gallego (micael.gallego@gmail.com)
* @author Boni Garcia (bgarcia@gsyc.es)
* @since 5.0.0
*/
public class KurentoHttpPlayer {
public static void main(String[] args) throws IOException,
URISyntaxException, InterruptedException {
// Connecting to Kurento Server
KurentoClient kurento = KurentoClient
.create("ws://localhost:8888/kurento");
// Creating media pipeline
MediaPipeline pipeline = kurento.createMediaPipeline();
// Creating media elements
PlayerEndpoint player = new PlayerEndpoint.Builder(pipeline,
"http://files.kurento.org/video/fiwarecut.mp4").build();
FaceOverlayFilter filter = new FaceOverlayFilter.Builder(pipeline)
.build();
filter.setOverlayedImage(
"http://files.kurento.org/imgs/mario-wings.png", -0.2F, -1.1F,
1.6F, 1.6F);
HttpGetEndpoint http = new HttpGetEndpoint.Builder(pipeline).build();
// Connecting media elements
player.connect(filter);
filter.connect(http);
// Reacting to events
player.addEndOfStreamListener(new EventListener<EndOfStreamEvent>() {
@Override
public void onEvent(EndOfStreamEvent event) {
System.out.println("The playing has finished");
System.exit(0);
}
});
// Playing media and opening the default desktop browser
player.play();
String videoUrl = http.getUrl();
Desktop.getDesktop().browse(new URI(videoUrl));
// Setting a delay to wait the EndOfStream event, previously subscribed
Thread.sleep(60000);
}
}
| lgpl-2.1 |
simon04/jfreechart | src/main/java/org/jfree/data/statistics/MeanAndStandardDeviation.java | 5489 | /* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2016, by Object Refinery Limited and Contributors.
*
* Project Info: http://www.jfree.org/jfreechart/index.html
*
* This library is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as published by
* the Free Software Foundation; either version 2.1 of the License, or
* (at your option) any later version.
*
* This library is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public
* License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301,
* USA.
*
* [Oracle and Java are registered trademarks of Oracle and/or its affiliates.
* Other names may be trademarks of their respective owners.]
*
* -----------------------------
* MeanAndStandardDeviation.java
* -----------------------------
* (C) Copyright 2003-2008, by Object Refinery Limited.
*
* Original Author: David Gilbert (for Object Refinery Limited);
* Contributor(s): -;
*
* Changes:
* --------
* 05-Feb-2002 : Version 1 (DG);
* 05-Feb-2005 : Added equals() method and implemented Serializable (DG);
* 02-Oct-2007 : Added getMeanValue() and getStandardDeviationValue() methods
* for convenience, and toString() method for debugging (DG);
*
*/
package org.jfree.data.statistics;
import java.io.Serializable;
import org.jfree.util.ObjectUtilities;
/**
* A simple data structure that holds a mean value and a standard deviation
* value. This is used in the
* {@link org.jfree.data.statistics.DefaultStatisticalCategoryDataset} class.
*/
public class MeanAndStandardDeviation implements Serializable {
/** For serialization. */
private static final long serialVersionUID = 7413468697315721515L;
/** The mean. */
private Number mean;
/** The standard deviation. */
private Number standardDeviation;
/**
* Creates a new mean and standard deviation record.
*
* @param mean the mean.
* @param standardDeviation the standard deviation.
*/
public MeanAndStandardDeviation(double mean, double standardDeviation) {
this(new Double(mean), new Double(standardDeviation));
}
/**
* Creates a new mean and standard deviation record.
*
* @param mean the mean ({@code null} permitted).
* @param standardDeviation the standard deviation ({@code null}
* permitted.
*/
public MeanAndStandardDeviation(Number mean, Number standardDeviation) {
this.mean = mean;
this.standardDeviation = standardDeviation;
}
/**
* Returns the mean.
*
* @return The mean.
*/
public Number getMean() {
return this.mean;
}
/**
* Returns the mean as a double primitive. If the underlying mean is
* {@code null}, this method will return {@code Double.NaN}.
*
* @return The mean.
*
* @see #getMean()
*
* @since 1.0.7
*/
public double getMeanValue() {
double result = Double.NaN;
if (this.mean != null) {
result = this.mean.doubleValue();
}
return result;
}
/**
* Returns the standard deviation.
*
* @return The standard deviation.
*/
public Number getStandardDeviation() {
return this.standardDeviation;
}
/**
* Returns the standard deviation as a double primitive. If the underlying
* standard deviation is {@code null}, this method will return
* {@code Double.NaN}.
*
* @return The standard deviation.
*
* @since 1.0.7
*/
public double getStandardDeviationValue() {
double result = Double.NaN;
if (this.standardDeviation != null) {
result = this.standardDeviation.doubleValue();
}
return result;
}
/**
* Tests this instance for equality with an arbitrary object.
*
* @param obj the object ({@code null} permitted).
*
* @return A boolean.
*/
@Override
public boolean equals(Object obj) {
if (obj == this) {
return true;
}
if (!(obj instanceof MeanAndStandardDeviation)) {
return false;
}
MeanAndStandardDeviation that = (MeanAndStandardDeviation) obj;
if (!ObjectUtilities.equal(this.mean, that.mean)) {
return false;
}
if (!ObjectUtilities.equal(
this.standardDeviation, that.standardDeviation)
) {
return false;
}
return true;
}
/**
* Returns a string representing this instance.
*
* @return A string.
*
* @since 1.0.7
*/
@Override
public String toString() {
return "[" + this.mean + ", " + this.standardDeviation + "]";
}
} | lgpl-2.1 |
digital-crafting-habitat/dch_forge_mod | src/main/java/com/digitalcraftinghabitat/forgemod/util/DCHLog.java | 1264 | package com.digitalcraftinghabitat.forgemod.util;
import org.apache.logging.log4j.Level;
import cpw.mods.fml.relauncher.FMLRelaunchLog;
/**
* Created by christopher on 02/08/15.
*/
public class DCHLog {
public static final FMLRelaunchLog INSTANCE = FMLRelaunchLog.log;
private DCHLog(){
}
public static void warning( String format, Object... data )
{
log( Level.WARN, format, data );
}
private static void log( Level level, String format, Object... data )
{
FMLRelaunchLog.log( "DCH:", level, format, data );
}
public static void error( Throwable e )
{
severe( "Error: " + e.getClass().getName() + " : " + e.getMessage() );
e.printStackTrace();
}
public static void severe( String format, Object... data )
{
log( Level.ERROR, format, data );
}
public static void blockUpdate( int xCoord, int yCoord, int zCoord, String title)
{
info( title + " @ " + xCoord + ", " + yCoord + ", " + zCoord );
}
public static void info( String format, Object... data )
{
log( Level.INFO, format, data );
}
public static void crafting( String format, Object... data )
{
log( Level.INFO, format, data );
}
}
| lgpl-2.1 |
Chandrashar/jradius | applet/src/main/java/Base64.java | 53360 | /**
* Encodes and decodes to and from Base64 notation.
*
* <p>
* Change Log:
* </p>
* <ul>
* <li>v2.1 - Cleaned up javadoc comments and unused variables and methods. Added
* some convenience methods for reading and writing to and from files.</li>
* <li>v2.0.2 - Now specifies UTF-8 encoding in places where the code fails on systems
* with other encodings (like EBCDIC).</li>
* <li>v2.0.1 - Fixed an error when decoding a single byte, that is, when the
* encoded data was a single byte.</li>
* <li>v2.0 - I got rid of methods that used booleans to set options.
* Now everything is more consolidated and cleaner. The code now detects
* when data that's being decoded is gzip-compressed and will decompress it
* automatically. Generally things are cleaner. You'll probably have to
* change some method calls that you were making to support the new
* options format (<tt>int</tt>s that you "OR" together).</li>
* <li>v1.5.1 - Fixed bug when decompressing and decoding to a
* byte[] using <tt>decode( String s, boolean gzipCompressed )</tt>.
* Added the ability to "suspend" encoding in the Output Stream so
* you can turn on and off the encoding if you need to embed base64
* data in an otherwise "normal" stream (like an XML file).</li>
* <li>v1.5 - Output stream pases on flush() command but doesn't do anything itself.
* This helps when using GZIP streams.
* Added the ability to GZip-compress objects before encoding them.</li>
* <li>v1.4 - Added helper methods to read/write files.</li>
* <li>v1.3.6 - Fixed OutputStream.flush() so that 'position' is reset.</li>
* <li>v1.3.5 - Added flag to turn on and off line breaks. Fixed bug in input stream
* where last buffer being read, if not completely full, was not returned.</li>
* <li>v1.3.4 - Fixed when "improperly padded stream" error was thrown at the wrong time.</li>
* <li>v1.3.3 - Fixed I/O streams which were totally messed up.</li>
* </ul>
*
* <p>
* I am placing this code in the Public Domain. Do with it as you will.
* This software comes with no guarantees or warranties but with
* plenty of well-wishing instead!
* Please visit <a href="http://iharder.net/base64">http://iharder.net/base64</a>
* periodically to check for updates or to contribute improvements.
* </p>
*
* @author Robert Harder
* @author rob@iharder.net
* @version 2.1
*/
public class Base64
{
/* ******** P U B L I C F I E L D S ******** */
/** No options specified. Value is zero. */
public final static int NO_OPTIONS = 0;
/** Specify encoding. */
public final static int ENCODE = 1;
/** Specify decoding. */
public final static int DECODE = 0;
/** Specify that data should be gzip-compressed. */
public final static int GZIP = 2;
/** Don't break lines when encoding (violates strict Base64 specification) */
public final static int DONT_BREAK_LINES = 8;
/* ******** P R I V A T E F I E L D S ******** */
/** Maximum line length (76) of Base64 output. */
private final static int MAX_LINE_LENGTH = 76;
/** The equals sign (=) as a byte. */
private final static byte EQUALS_SIGN = (byte)'=';
/** The new line character (\n) as a byte. */
private final static byte NEW_LINE = (byte)'\n';
/** Preferred encoding. */
private final static String PREFERRED_ENCODING = "UTF-8";
/** The 64 valid Base64 values. */
private final static byte[] ALPHABET;
private final static byte[] _NATIVE_ALPHABET = /* May be something funny like EBCDIC */
{
(byte)'A', (byte)'B', (byte)'C', (byte)'D', (byte)'E', (byte)'F', (byte)'G',
(byte)'H', (byte)'I', (byte)'J', (byte)'K', (byte)'L', (byte)'M', (byte)'N',
(byte)'O', (byte)'P', (byte)'Q', (byte)'R', (byte)'S', (byte)'T', (byte)'U',
(byte)'V', (byte)'W', (byte)'X', (byte)'Y', (byte)'Z',
(byte)'a', (byte)'b', (byte)'c', (byte)'d', (byte)'e', (byte)'f', (byte)'g',
(byte)'h', (byte)'i', (byte)'j', (byte)'k', (byte)'l', (byte)'m', (byte)'n',
(byte)'o', (byte)'p', (byte)'q', (byte)'r', (byte)'s', (byte)'t', (byte)'u',
(byte)'v', (byte)'w', (byte)'x', (byte)'y', (byte)'z',
(byte)'0', (byte)'1', (byte)'2', (byte)'3', (byte)'4', (byte)'5',
(byte)'6', (byte)'7', (byte)'8', (byte)'9', (byte)'+', (byte)'/'
};
/** Determine which ALPHABET to use. */
static
{
byte[] __bytes;
try
{
__bytes = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/".getBytes( PREFERRED_ENCODING );
} // end try
catch (java.io.UnsupportedEncodingException use)
{
__bytes = _NATIVE_ALPHABET; // Fall back to native encoding
} // end catch
ALPHABET = __bytes;
} // end static
/**
* Translates a Base64 value to either its 6-bit reconstruction value
* or a negative number indicating some other meaning.
**/
private final static byte[] DECODABET =
{
-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 0 - 8
-5,-5, // Whitespace: Tab and Linefeed
-9,-9, // Decimal 11 - 12
-5, // Whitespace: Carriage Return
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 14 - 26
-9,-9,-9,-9,-9, // Decimal 27 - 31
-5, // Whitespace: Space
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 33 - 42
62, // Plus sign at decimal 43
-9,-9,-9, // Decimal 44 - 46
63, // Slash at decimal 47
52,53,54,55,56,57,58,59,60,61, // Numbers zero through nine
-9,-9,-9, // Decimal 58 - 60
-1, // Equals sign at decimal 61
-9,-9,-9, // Decimal 62 - 64
0,1,2,3,4,5,6,7,8,9,10,11,12,13, // Letters 'A' through 'N'
14,15,16,17,18,19,20,21,22,23,24,25, // Letters 'O' through 'Z'
-9,-9,-9,-9,-9,-9, // Decimal 91 - 96
26,27,28,29,30,31,32,33,34,35,36,37,38, // Letters 'a' through 'm'
39,40,41,42,43,44,45,46,47,48,49,50,51, // Letters 'n' through 'z'
-9,-9,-9,-9 // Decimal 123 - 126
/*,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 127 - 139
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 140 - 152
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 153 - 165
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 166 - 178
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 179 - 191
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 192 - 204
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 205 - 217
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 218 - 230
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9, // Decimal 231 - 243
-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9,-9 // Decimal 244 - 255 */
};
// I think I end up not using the BAD_ENCODING indicator.
//private final static byte BAD_ENCODING = -9; // Indicates error in encoding
private final static byte WHITE_SPACE_ENC = -5; // Indicates white space in encoding
private final static byte EQUALS_SIGN_ENC = -1; // Indicates equals sign in encoding
/** Defeats instantiation. */
private Base64(){}
/* ******** E N C O D I N G M E T H O D S ******** */
/**
* Encodes up to the first three bytes of array <var>threeBytes</var>
* and returns a four-byte array in Base64 notation.
* The actual number of significant bytes in your array is
* given by <var>numSigBytes</var>.
* The array <var>threeBytes</var> needs only be as big as
* <var>numSigBytes</var>.
* Code can reuse a byte array by passing a four-byte array as <var>b4</var>.
*
* @param b4 A reusable byte array to reduce array instantiation
* @param threeBytes the array to convert
* @param numSigBytes the number of significant bytes in your array
* @return four byte array in Base64 notation.
* @since 1.5.1
*/
private static byte[] encode3to4( byte[] b4, byte[] threeBytes, int numSigBytes )
{
encode3to4( threeBytes, 0, numSigBytes, b4, 0 );
return b4;
} // end encode3to4
/**
* Encodes up to three bytes of the array <var>source</var>
* and writes the resulting four Base64 bytes to <var>destination</var>.
* The source and destination arrays can be manipulated
* anywhere along their length by specifying
* <var>srcOffset</var> and <var>destOffset</var>.
* This method does not check to make sure your arrays
* are large enough to accomodate <var>srcOffset</var> + 3 for
* the <var>source</var> array or <var>destOffset</var> + 4 for
* the <var>destination</var> array.
* The actual number of significant bytes in your array is
* given by <var>numSigBytes</var>.
*
* @param source the array to convert
* @param srcOffset the index where conversion begins
* @param numSigBytes the number of significant bytes in your array
* @param destination the array to hold the conversion
* @param destOffset the index where output will be put
* @return the <var>destination</var> array
* @since 1.3
*/
private static byte[] encode3to4(
byte[] source, int srcOffset, int numSigBytes,
byte[] destination, int destOffset )
{
// 1 2 3
// 01234567890123456789012345678901 Bit position
// --------000000001111111122222222 Array position from threeBytes
// --------| || || || | Six bit groups to index ALPHABET
// >>18 >>12 >> 6 >> 0 Right shift necessary
// 0x3f 0x3f 0x3f Additional AND
// Create buffer with zero-padding if there are only one or two
// significant bytes passed in the array.
// We have to shift left 24 in order to flush out the 1's that appear
// when Java treats a value as negative that is cast from a byte to an int.
int inBuff = ( numSigBytes > 0 ? ((source[ srcOffset ] << 24) >>> 8) : 0 )
| ( numSigBytes > 1 ? ((source[ srcOffset + 1 ] << 24) >>> 16) : 0 )
| ( numSigBytes > 2 ? ((source[ srcOffset + 2 ] << 24) >>> 24) : 0 );
switch( numSigBytes )
{
case 3:
destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ];
destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ];
destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ];
destination[ destOffset + 3 ] = ALPHABET[ (inBuff ) & 0x3f ];
return destination;
case 2:
destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ];
destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ];
destination[ destOffset + 2 ] = ALPHABET[ (inBuff >>> 6) & 0x3f ];
destination[ destOffset + 3 ] = EQUALS_SIGN;
return destination;
case 1:
destination[ destOffset ] = ALPHABET[ (inBuff >>> 18) ];
destination[ destOffset + 1 ] = ALPHABET[ (inBuff >>> 12) & 0x3f ];
destination[ destOffset + 2 ] = EQUALS_SIGN;
destination[ destOffset + 3 ] = EQUALS_SIGN;
return destination;
default:
return destination;
} // end switch
} // end encode3to4
/**
* Serializes an object and returns the Base64-encoded
* version of that serialized object. If the object
* cannot be serialized or there is another error,
* the method will return <tt>null</tt>.
* The object is not GZip-compressed before being encoded.
*
* @param serializableObject The object to encode
* @return The Base64-encoded object
* @since 1.4
*/
public static String encodeObject( java.io.Serializable serializableObject )
{
return encodeObject( serializableObject, NO_OPTIONS );
} // end encodeObject
/**
* Serializes an object and returns the Base64-encoded
* version of that serialized object. If the object
* cannot be serialized or there is another error,
* the method will return <tt>null</tt>.
* <p>
* Valid options:<pre>
* GZIP: gzip-compresses object before encoding it.
* DONT_BREAK_LINES: don't break lines at 76 characters
* <i>Note: Technically, this makes your encoding non-compliant.</i>
* </pre>
* <p>
* Example: <code>encodeObject( myObj, Base64.GZIP )</code> or
* <p>
* Example: <code>encodeObject( myObj, Base64.GZIP | Base64.DONT_BREAK_LINES )</code>
*
* @param serializableObject The object to encode
* @param options Specified options
* @return The Base64-encoded object
* @see Base64#GZIP
* @see Base64#DONT_BREAK_LINES
* @since 2.0
*/
public static String encodeObject( java.io.Serializable serializableObject, int options )
{
// Streams
java.io.ByteArrayOutputStream baos = null;
java.io.OutputStream b64os = null;
java.io.ObjectOutputStream oos = null;
java.util.zip.GZIPOutputStream gzos = null;
// Isolate options
int gzip = (options & GZIP);
int dontBreakLines = (options & DONT_BREAK_LINES);
try
{
// ObjectOutputStream -> (GZIP) -> Base64 -> ByteArrayOutputStream
baos = new java.io.ByteArrayOutputStream();
b64os = new Base64.OutputStream( baos, ENCODE | dontBreakLines );
// GZip?
if( gzip == GZIP )
{
gzos = new java.util.zip.GZIPOutputStream( b64os );
oos = new java.io.ObjectOutputStream( gzos );
} // end if: gzip
else
oos = new java.io.ObjectOutputStream( b64os );
oos.writeObject( serializableObject );
} // end try
catch( java.io.IOException e )
{
e.printStackTrace();
return null;
} // end catch
finally
{
try{ oos.close(); } catch( Exception e ){}
try{ gzos.close(); } catch( Exception e ){}
try{ b64os.close(); } catch( Exception e ){}
try{ baos.close(); } catch( Exception e ){}
} // end finally
// Return value according to relevant encoding.
try
{
return new String( baos.toByteArray(), PREFERRED_ENCODING );
} // end try
catch (java.io.UnsupportedEncodingException uue)
{
return new String( baos.toByteArray() );
} // end catch
} // end encode
/**
* Encodes a byte array into Base64 notation.
* Does not GZip-compress data.
*
* @param source The data to convert
* @since 1.4
*/
public static String encodeBytes( byte[] source )
{
return encodeBytes( source, 0, source.length, NO_OPTIONS );
} // end encodeBytes
/**
* Encodes a byte array into Base64 notation.
* <p>
* Valid options:<pre>
* GZIP: gzip-compresses object before encoding it.
* DONT_BREAK_LINES: don't break lines at 76 characters
* <i>Note: Technically, this makes your encoding non-compliant.</i>
* </pre>
* <p>
* Example: <code>encodeBytes( myData, Base64.GZIP )</code> or
* <p>
* Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DONT_BREAK_LINES )</code>
*
*
* @param source The data to convert
* @param options Specified options
* @see Base64#GZIP
* @see Base64#DONT_BREAK_LINES
* @since 2.0
*/
public static String encodeBytes( byte[] source, int options )
{
return encodeBytes( source, 0, source.length, options );
} // end encodeBytes
/**
* Encodes a byte array into Base64 notation.
* Does not GZip-compress data.
*
* @param source The data to convert
* @param off Offset in array where conversion should begin
* @param len Length of data to convert
* @since 1.4
*/
public static String encodeBytes( byte[] source, int off, int len )
{
return encodeBytes( source, off, len, NO_OPTIONS );
} // end encodeBytes
/**
* Encodes a byte array into Base64 notation.
* <p>
* Valid options:<pre>
* GZIP: gzip-compresses object before encoding it.
* DONT_BREAK_LINES: don't break lines at 76 characters
* <i>Note: Technically, this makes your encoding non-compliant.</i>
* </pre>
* <p>
* Example: <code>encodeBytes( myData, Base64.GZIP )</code> or
* <p>
* Example: <code>encodeBytes( myData, Base64.GZIP | Base64.DONT_BREAK_LINES )</code>
*
*
* @param source The data to convert
* @param off Offset in array where conversion should begin
* @param len Length of data to convert
* @param options Specified options
* @see Base64#GZIP
* @see Base64#DONT_BREAK_LINES
* @since 2.0
*/
public static String encodeBytes( byte[] source, int off, int len, int options )
{
// Isolate options
int dontBreakLines = ( options & DONT_BREAK_LINES );
int gzip = ( options & GZIP );
// Compress?
if( gzip == GZIP )
{
java.io.ByteArrayOutputStream baos = null;
java.util.zip.GZIPOutputStream gzos = null;
Base64.OutputStream b64os = null;
try
{
// GZip -> Base64 -> ByteArray
baos = new java.io.ByteArrayOutputStream();
b64os = new Base64.OutputStream( baos, ENCODE | dontBreakLines );
gzos = new java.util.zip.GZIPOutputStream( b64os );
gzos.write( source, off, len );
gzos.close();
} // end try
catch( java.io.IOException e )
{
e.printStackTrace();
return null;
} // end catch
finally
{
try{ gzos.close(); } catch( Exception e ){}
try{ b64os.close(); } catch( Exception e ){}
try{ baos.close(); } catch( Exception e ){}
} // end finally
// Return value according to relevant encoding.
try
{
return new String( baos.toByteArray(), PREFERRED_ENCODING );
} // end try
catch (java.io.UnsupportedEncodingException uue)
{
return new String( baos.toByteArray() );
} // end catch
} // end if: compress
// Else, don't compress. Better not to use streams at all then.
else
{
// Convert option to boolean in way that code likes it.
boolean breakLines = dontBreakLines == 0;
int len43 = len * 4 / 3;
byte[] outBuff = new byte[ ( len43 ) // Main 4:3
+ ( (len % 3) > 0 ? 4 : 0 ) // Account for padding
+ (breakLines ? ( len43 / MAX_LINE_LENGTH ) : 0) ]; // New lines
int d = 0;
int e = 0;
int len2 = len - 2;
int lineLength = 0;
for( ; d < len2; d+=3, e+=4 )
{
encode3to4( source, d+off, 3, outBuff, e );
lineLength += 4;
if( breakLines && lineLength == MAX_LINE_LENGTH )
{
outBuff[e+4] = NEW_LINE;
e++;
lineLength = 0;
} // end if: end of line
} // en dfor: each piece of array
if( d < len )
{
encode3to4( source, d+off, len - d, outBuff, e );
e += 4;
} // end if: some padding needed
// Return value according to relevant encoding.
try
{
return new String( outBuff, 0, e, PREFERRED_ENCODING );
} // end try
catch (java.io.UnsupportedEncodingException uue)
{
return new String( outBuff, 0, e );
} // end catch
} // end else: don't compress
} // end encodeBytes
/* ******** D E C O D I N G M E T H O D S ******** */
/**
* Decodes four bytes from array <var>source</var>
* and writes the resulting bytes (up to three of them)
* to <var>destination</var>.
* The source and destination arrays can be manipulated
* anywhere along their length by specifying
* <var>srcOffset</var> and <var>destOffset</var>.
* This method does not check to make sure your arrays
* are large enough to accomodate <var>srcOffset</var> + 4 for
* the <var>source</var> array or <var>destOffset</var> + 3 for
* the <var>destination</var> array.
* This method returns the actual number of bytes that
* were converted from the Base64 encoding.
*
*
* @param source the array to convert
* @param srcOffset the index where conversion begins
* @param destination the array to hold the conversion
* @param destOffset the index where output will be put
* @return the number of decoded bytes converted
* @since 1.3
*/
private static int decode4to3( byte[] source, int srcOffset, byte[] destination, int destOffset )
{
// Example: Dk==
if( source[ srcOffset + 2] == EQUALS_SIGN )
{
// Two ways to do the same thing. Don't know which way I like best.
//int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
// | ( ( DECODABET[ source[ srcOffset + 1] ] << 24 ) >>> 12 );
int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
| ( ( DECODABET[ source[ srcOffset + 1] ] & 0xFF ) << 12 );
destination[ destOffset ] = (byte)( outBuff >>> 16 );
return 1;
}
// Example: DkL=
else if( source[ srcOffset + 3 ] == EQUALS_SIGN )
{
// Two ways to do the same thing. Don't know which way I like best.
//int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
// | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
// | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 );
int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
| ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 )
| ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6 );
destination[ destOffset ] = (byte)( outBuff >>> 16 );
destination[ destOffset + 1 ] = (byte)( outBuff >>> 8 );
return 2;
}
// Example: DkLE
else
{
try{
// Two ways to do the same thing. Don't know which way I like best.
//int outBuff = ( ( DECODABET[ source[ srcOffset ] ] << 24 ) >>> 6 )
// | ( ( DECODABET[ source[ srcOffset + 1 ] ] << 24 ) >>> 12 )
// | ( ( DECODABET[ source[ srcOffset + 2 ] ] << 24 ) >>> 18 )
// | ( ( DECODABET[ source[ srcOffset + 3 ] ] << 24 ) >>> 24 );
int outBuff = ( ( DECODABET[ source[ srcOffset ] ] & 0xFF ) << 18 )
| ( ( DECODABET[ source[ srcOffset + 1 ] ] & 0xFF ) << 12 )
| ( ( DECODABET[ source[ srcOffset + 2 ] ] & 0xFF ) << 6)
| ( ( DECODABET[ source[ srcOffset + 3 ] ] & 0xFF ) );
destination[ destOffset ] = (byte)( outBuff >> 16 );
destination[ destOffset + 1 ] = (byte)( outBuff >> 8 );
destination[ destOffset + 2 ] = (byte)( outBuff );
return 3;
}catch( Exception e){
System.out.println(""+source[srcOffset]+ ": " + ( DECODABET[ source[ srcOffset ] ] ) );
System.out.println(""+source[srcOffset+1]+ ": " + ( DECODABET[ source[ srcOffset + 1 ] ] ) );
System.out.println(""+source[srcOffset+2]+ ": " + ( DECODABET[ source[ srcOffset + 2 ] ] ) );
System.out.println(""+source[srcOffset+3]+ ": " + ( DECODABET[ source[ srcOffset + 3 ] ] ) );
return -1;
} //e nd catch
}
} // end decodeToBytes
/**
* Very low-level access to decoding ASCII characters in
* the form of a byte array. Does not support automatically
* gunzipping or any other "fancy" features.
*
* @param source The Base64 encoded data
* @param off The offset of where to begin decoding
* @param len The length of characters to decode
* @return decoded data
* @since 1.3
*/
public static byte[] decode( byte[] source, int off, int len )
{
int len34 = len * 3 / 4;
byte[] outBuff = new byte[ len34 ]; // Upper limit on size of output
int outBuffPosn = 0;
byte[] b4 = new byte[4];
int b4Posn = 0;
int i = 0;
byte sbiCrop = 0;
byte sbiDecode = 0;
for( i = off; i < off+len; i++ )
{
sbiCrop = (byte)(source[i] & 0x7f); // Only the low seven bits
sbiDecode = DECODABET[ sbiCrop ];
if( sbiDecode >= WHITE_SPACE_ENC ) // White space, Equals sign or better
{
if( sbiDecode >= EQUALS_SIGN_ENC )
{
b4[ b4Posn++ ] = sbiCrop;
if( b4Posn > 3 )
{
outBuffPosn += decode4to3( b4, 0, outBuff, outBuffPosn );
b4Posn = 0;
// If that was the equals sign, break out of 'for' loop
if( sbiCrop == EQUALS_SIGN )
break;
} // end if: quartet built
} // end if: equals sign or better
} // end if: white space, equals sign or better
else
{
//System.err.println( "Bad Base64 input character at " + i + ": " + source[i] + "(decimal)" );
return null;
} // end else:
} // each input character
byte[] out = new byte[ outBuffPosn ];
System.arraycopy( outBuff, 0, out, 0, outBuffPosn );
return out;
} // end decode
/**
* Decodes data from Base64 notation, automatically
* detecting gzip-compressed data and decompressing it.
*
* @param s the string to decode
* @return the decoded data
* @since 1.4
*/
public static byte[] decode( String s )
{
byte[] bytes;
try
{
bytes = s.getBytes( PREFERRED_ENCODING );
} // end try
catch( java.io.UnsupportedEncodingException uee )
{
bytes = s.getBytes();
} // end catch
//</change>
// Decode
bytes = decode( bytes, 0, bytes.length );
// Check to see if it's gzip-compressed
// GZIP Magic Two-Byte Number: 0x8b1f (35615)
if( bytes != null && bytes.length >= 4 )
{
int head = ((int)bytes[0] & 0xff) | ((bytes[1] << 8) & 0xff00);
if( java.util.zip.GZIPInputStream.GZIP_MAGIC == head )
{
java.io.ByteArrayInputStream bais = null;
java.util.zip.GZIPInputStream gzis = null;
java.io.ByteArrayOutputStream baos = null;
byte[] buffer = new byte[2048];
int length = 0;
try
{
baos = new java.io.ByteArrayOutputStream();
bais = new java.io.ByteArrayInputStream( bytes );
gzis = new java.util.zip.GZIPInputStream( bais );
while( ( length = gzis.read( buffer ) ) >= 0 )
{
baos.write(buffer,0,length);
} // end while: reading input
// No error? Get new bytes.
bytes = baos.toByteArray();
} // end try
catch( java.io.IOException e )
{
// Just return originally-decoded bytes
} // end catch
finally
{
try{ baos.close(); } catch( Exception e ){}
try{ gzis.close(); } catch( Exception e ){}
try{ bais.close(); } catch( Exception e ){}
} // end finally
} // end if: gzipped
} // end if: bytes.length >= 2
return bytes;
} // end decode
/**
* Attempts to decode Base64 data and deserialize a Java
* Object within. Returns <tt>null</tt> if there was an error.
*
* @param encodedObject The Base64 data to decode
* @return The decoded and deserialized object
* @since 1.5
*/
public static Object decodeToObject( String encodedObject )
{
// Decode and gunzip if necessary
byte[] objBytes = decode( encodedObject );
java.io.ByteArrayInputStream bais = null;
java.io.ObjectInputStream ois = null;
Object obj = null;
try
{
bais = new java.io.ByteArrayInputStream( objBytes );
ois = new java.io.ObjectInputStream( bais );
obj = ois.readObject();
} // end try
catch( java.io.IOException e )
{
e.printStackTrace();
obj = null;
} // end catch
catch( java.lang.ClassNotFoundException e )
{
e.printStackTrace();
obj = null;
} // end catch
finally
{
try{ bais.close(); } catch( Exception e ){}
try{ ois.close(); } catch( Exception e ){}
} // end finally
return obj;
} // end decodeObject
/**
* Convenience method for encoding data to a file.
*
* @param dataToEncode byte array of data to encode in base64 form
* @param filename Filename for saving encoded data
* @return <tt>true</tt> if successful, <tt>false</tt> otherwise
*
* @since 2.1
*/
public static boolean encodeToFile( byte[] dataToEncode, String filename )
{
boolean success = false;
Base64.OutputStream bos = null;
try
{
bos = new Base64.OutputStream(
new java.io.FileOutputStream( filename ), Base64.ENCODE );
bos.write( dataToEncode );
success = true;
} // end try
catch( java.io.IOException e )
{
success = false;
} // end catch: IOException
finally
{
try{ bos.close(); } catch( Exception e ){}
} // end finally
return success;
} // end encodeToFile
/**
* Convenience method for decoding data to a file.
*
* @param dataToDecode Base64-encoded data as a string
* @param filename Filename for saving decoded data
* @return <tt>true</tt> if successful, <tt>false</tt> otherwise
*
* @since 2.1
*/
public static boolean decodeToFile( String dataToDecode, String filename )
{
boolean success = false;
Base64.OutputStream bos = null;
try
{
bos = new Base64.OutputStream(
new java.io.FileOutputStream( filename ), Base64.DECODE );
bos.write( dataToDecode.getBytes( PREFERRED_ENCODING ) );
success = true;
} // end try
catch( java.io.IOException e )
{
success = false;
} // end catch: IOException
finally
{
try{ bos.close(); } catch( Exception e ){}
} // end finally
return success;
} // end decodeToFile
/**
* Convenience method for reading a base64-encoded
* file and decoding it.
*
* @param filename Filename for reading encoded data
* @return decoded byte array or null if unsuccessful
*
* @since 2.1
*/
public static byte[] decodeFromFile( String filename )
{
byte[] decodedData = null;
Base64.InputStream bis = null;
try
{
// Set up some useful variables
java.io.File file = new java.io.File( filename );
byte[] buffer = null;
int length = 0;
int numBytes = 0;
// Check for size of file
if( file.length() > Integer.MAX_VALUE )
{
System.err.println( "File is too big for this convenience method (" + file.length() + " bytes)." );
return null;
} // end if: file too big for int index
buffer = new byte[ (int)file.length() ];
// Open a stream
bis = new Base64.InputStream(
new java.io.BufferedInputStream(
new java.io.FileInputStream( file ) ), Base64.DECODE );
// Read until done
while( ( numBytes = bis.read( buffer, length, 4096 ) ) >= 0 )
length += numBytes;
// Save in a variable to return
decodedData = new byte[ length ];
System.arraycopy( buffer, 0, decodedData, 0, length );
} // end try
catch( java.io.IOException e )
{
System.err.println( "Error decoding from file " + filename );
} // end catch: IOException
finally
{
try{ bis.close(); } catch( Exception e) {}
} // end finally
return decodedData;
} // end decodeFromFile
/**
* Convenience method for reading a binary file
* and base64-encoding it.
*
* @param filename Filename for reading binary data
* @return base64-encoded string or null if unsuccessful
*
* @since 2.1
*/
public static String encodeFromFile( String filename )
{
String encodedData = null;
Base64.InputStream bis = null;
try
{
// Set up some useful variables
java.io.File file = new java.io.File( filename );
byte[] buffer = new byte[ (int)(file.length() * 1.4) ];
int length = 0;
int numBytes = 0;
// Open a stream
bis = new Base64.InputStream(
new java.io.BufferedInputStream(
new java.io.FileInputStream( file ) ), Base64.ENCODE );
// Read until done
while( ( numBytes = bis.read( buffer, length, 4096 ) ) >= 0 )
length += numBytes;
// Save in a variable to return
encodedData = new String( buffer, 0, length, Base64.PREFERRED_ENCODING );
} // end try
catch( java.io.IOException e )
{
System.err.println( "Error encoding from file " + filename );
} // end catch: IOException
finally
{
try{ bis.close(); } catch( Exception e) {}
} // end finally
return encodedData;
} // end encodeFromFile
/* ******** I N N E R C L A S S I N P U T S T R E A M ******** */
/**
* A {@link Base64.InputStream} will read data from another
* <tt>java.io.InputStream</tt>, given in the constructor,
* and encode/decode to/from Base64 notation on the fly.
*
* @see Base64
* @since 1.3
*/
public static class InputStream extends java.io.FilterInputStream
{
private boolean encode; // Encoding or decoding
private int position; // Current position in the buffer
private byte[] buffer; // Small buffer holding converted data
private int bufferLength; // Length of buffer (3 or 4)
private int numSigBytes; // Number of meaningful bytes in the buffer
private int lineLength;
private boolean breakLines; // Break lines at less than 80 characters
/**
* Constructs a {@link Base64.InputStream} in DECODE mode.
*
* @param in the <tt>java.io.InputStream</tt> from which to read data.
* @since 1.3
*/
public InputStream( java.io.InputStream in )
{
this( in, DECODE );
} // end constructor
/**
* Constructs a {@link Base64.InputStream} in
* either ENCODE or DECODE mode.
* <p>
* Valid options:<pre>
* ENCODE or DECODE: Encode or Decode as data is read.
* DONT_BREAK_LINES: don't break lines at 76 characters
* (only meaningful when encoding)
* <i>Note: Technically, this makes your encoding non-compliant.</i>
* </pre>
* <p>
* Example: <code>new Base64.InputStream( in, Base64.DECODE )</code>
*
*
* @param in the <tt>java.io.InputStream</tt> from which to read data.
* @param options Specified options
* @see Base64#ENCODE
* @see Base64#DECODE
* @see Base64#DONT_BREAK_LINES
* @since 2.0
*/
public InputStream( java.io.InputStream in, int options )
{
super( in );
this.breakLines = (options & DONT_BREAK_LINES) != DONT_BREAK_LINES;
this.encode = (options & ENCODE) == ENCODE;
this.bufferLength = encode ? 4 : 3;
this.buffer = new byte[ bufferLength ];
this.position = -1;
this.lineLength = 0;
} // end constructor
/**
* Reads enough of the input stream to convert
* to/from Base64 and returns the next byte.
*
* @return next byte
* @since 1.3
*/
public int read() throws java.io.IOException
{
// Do we need to get data?
if( position < 0 )
{
if( encode )
{
byte[] b3 = new byte[3];
int numBinaryBytes = 0;
for( int i = 0; i < 3; i++ )
{
try
{
int b = in.read();
// If end of stream, b is -1.
if( b >= 0 )
{
b3[i] = (byte)b;
numBinaryBytes++;
} // end if: not end of stream
} // end try: read
catch( java.io.IOException e )
{
// Only a problem if we got no data at all.
if( i == 0 )
throw e;
} // end catch
} // end for: each needed input byte
if( numBinaryBytes > 0 )
{
encode3to4( b3, 0, numBinaryBytes, buffer, 0 );
position = 0;
numSigBytes = 4;
} // end if: got data
else
{
return -1;
} // end else
} // end if: encoding
// Else decoding
else
{
byte[] b4 = new byte[4];
int i = 0;
for( i = 0; i < 4; i++ )
{
// Read four "meaningful" bytes:
int b = 0;
do{ b = in.read(); }
while( b >= 0 && DECODABET[ b & 0x7f ] <= WHITE_SPACE_ENC );
if( b < 0 )
break; // Reads a -1 if end of stream
b4[i] = (byte)b;
} // end for: each needed input byte
if( i == 4 )
{
numSigBytes = decode4to3( b4, 0, buffer, 0 );
position = 0;
} // end if: got four characters
else if( i == 0 ){
return -1;
} // end else if: also padded correctly
else
{
// Must have broken out from above.
throw new java.io.IOException( "Improperly padded Base64 input." );
} // end
} // end else: decode
} // end else: get data
// Got data?
if( position >= 0 )
{
// End of relevant data?
if( /*!encode &&*/ position >= numSigBytes )
return -1;
if( encode && breakLines && lineLength >= MAX_LINE_LENGTH )
{
lineLength = 0;
return '\n';
} // end if
else
{
lineLength++; // This isn't important when decoding
// but throwing an extra "if" seems
// just as wasteful.
int b = buffer[ position++ ];
if( position >= bufferLength )
position = -1;
return b & 0xFF; // This is how you "cast" a byte that's
// intended to be unsigned.
} // end else
} // end if: position >= 0
// Else error
else
{
// When JDK1.4 is more accepted, use an assertion here.
throw new java.io.IOException( "Error in Base64 code reading stream." );
} // end else
} // end read
/**
* Calls {@link #read()} repeatedly until the end of stream
* is reached or <var>len</var> bytes are read.
* Returns number of bytes read into array or -1 if
* end of stream is encountered.
*
* @param dest array to hold values
* @param off offset for array
* @param len max number of bytes to read into array
* @return bytes read into array or -1 if end of stream is encountered.
* @since 1.3
*/
public int read( byte[] dest, int off, int len ) throws java.io.IOException
{
int i;
int b;
for( i = 0; i < len; i++ )
{
b = read();
//if( b < 0 && i == 0 )
// return -1;
if( b >= 0 )
dest[off + i] = (byte)b;
else if( i == 0 )
return -1;
else
break; // Out of 'for' loop
} // end for: each byte read
return i;
} // end read
} // end inner class InputStream
/* ******** I N N E R C L A S S O U T P U T S T R E A M ******** */
/**
* A {@link Base64.OutputStream} will write data to another
* <tt>java.io.OutputStream</tt>, given in the constructor,
* and encode/decode to/from Base64 notation on the fly.
*
* @see Base64
* @since 1.3
*/
public static class OutputStream extends java.io.FilterOutputStream
{
private boolean encode;
private int position;
private byte[] buffer;
private int bufferLength;
private int lineLength;
private boolean breakLines;
private byte[] b4; // Scratch used in a few places
private boolean suspendEncoding;
/**
* Constructs a {@link Base64.OutputStream} in ENCODE mode.
*
* @param out the <tt>java.io.OutputStream</tt> to which data will be written.
* @since 1.3
*/
public OutputStream( java.io.OutputStream out )
{
this( out, ENCODE );
} // end constructor
/**
* Constructs a {@link Base64.OutputStream} in
* either ENCODE or DECODE mode.
* <p>
* Valid options:<pre>
* ENCODE or DECODE: Encode or Decode as data is read.
* DONT_BREAK_LINES: don't break lines at 76 characters
* (only meaningful when encoding)
* <i>Note: Technically, this makes your encoding non-compliant.</i>
* </pre>
* <p>
* Example: <code>new Base64.OutputStream( out, Base64.ENCODE )</code>
*
* @param out the <tt>java.io.OutputStream</tt> to which data will be written.
* @param options Specified options.
* @see Base64#ENCODE
* @see Base64#DECODE
* @see Base64#DONT_BREAK_LINES
* @since 1.3
*/
public OutputStream( java.io.OutputStream out, int options )
{
super( out );
this.breakLines = (options & DONT_BREAK_LINES) != DONT_BREAK_LINES;
this.encode = (options & ENCODE) == ENCODE;
this.bufferLength = encode ? 3 : 4;
this.buffer = new byte[ bufferLength ];
this.position = 0;
this.lineLength = 0;
this.suspendEncoding = false;
this.b4 = new byte[4];
} // end constructor
/**
* Writes the byte to the output stream after
* converting to/from Base64 notation.
* When encoding, bytes are buffered three
* at a time before the output stream actually
* gets a write() call.
* When decoding, bytes are buffered four
* at a time.
*
* @param theByte the byte to write
* @since 1.3
*/
public void write(int theByte) throws java.io.IOException
{
// Encoding suspended?
if( suspendEncoding )
{
super.out.write( theByte );
return;
} // end if: supsended
// Encode?
if( encode )
{
buffer[ position++ ] = (byte)theByte;
if( position >= bufferLength ) // Enough to encode.
{
out.write( encode3to4( b4, buffer, bufferLength ) );
lineLength += 4;
if( breakLines && lineLength >= MAX_LINE_LENGTH )
{
out.write( NEW_LINE );
lineLength = 0;
} // end if: end of line
position = 0;
} // end if: enough to output
} // end if: encoding
// Else, Decoding
else
{
// Meaningful Base64 character?
if( DECODABET[ theByte & 0x7f ] > WHITE_SPACE_ENC )
{
buffer[ position++ ] = (byte)theByte;
if( position >= bufferLength ) // Enough to output.
{
int len = Base64.decode4to3( buffer, 0, b4, 0 );
out.write( b4, 0, len );
//out.write( Base64.decode4to3( buffer ) );
position = 0;
} // end if: enough to output
} // end if: meaningful base64 character
else if( DECODABET[ theByte & 0x7f ] != WHITE_SPACE_ENC )
{
throw new java.io.IOException( "Invalid character in Base64 data." );
} // end else: not white space either
} // end else: decoding
} // end write
/**
* Calls {@link #write(int)} repeatedly until <var>len</var>
* bytes are written.
*
* @param theBytes array from which to read bytes
* @param off offset for array
* @param len max number of bytes to read into array
* @since 1.3
*/
public void write( byte[] theBytes, int off, int len ) throws java.io.IOException
{
// Encoding suspended?
if( suspendEncoding )
{
super.out.write( theBytes, off, len );
return;
} // end if: supsended
for( int i = 0; i < len; i++ )
{
write( theBytes[ off + i ] );
} // end for: each byte written
} // end write
/**
* Method added by PHIL. [Thanks, PHIL. -Rob]
* This pads the buffer without closing the stream.
*/
public void flushBase64() throws java.io.IOException
{
if( position > 0 )
{
if( encode )
{
out.write( encode3to4( b4, buffer, position ) );
position = 0;
} // end if: encoding
else
{
throw new java.io.IOException( "Base64 input not properly padded." );
} // end else: decoding
} // end if: buffer partially full
} // end flush
/**
* Flushes and closes (I think, in the superclass) the stream.
*
* @since 1.3
*/
public void close() throws java.io.IOException
{
// 1. Ensure that pending characters are written
flushBase64();
// 2. Actually close the stream
// Base class both flushes and closes.
super.close();
buffer = null;
out = null;
} // end close
/**
* Suspends encoding of the stream.
* May be helpful if you need to embed a piece of
* base640-encoded data in a stream.
*
* @since 1.5.1
*/
public void suspendEncoding() throws java.io.IOException
{
flushBase64();
this.suspendEncoding = true;
} // end suspendEncoding
/**
* Resumes encoding of the stream.
* May be helpful if you need to embed a piece of
* base640-encoded data in a stream.
*
* @since 1.5.1
*/
public void resumeEncoding()
{
this.suspendEncoding = false;
} // end resumeEncoding
} // end inner class OutputStream
} // end class Base64
| lgpl-2.1 |
dukeboard/kevoree-modeling-framework | org.kevoree.modeling.microframework/src/test/java/org/kevoree/modeling/memory/struct/map/impl/ArrayLongLongHashMapTest.java | 443 | package org.kevoree.modeling.memory.struct.map.impl;
import org.kevoree.modeling.memory.struct.map.BaseKLongLongHashMapTest;
import org.kevoree.modeling.memory.struct.map.KLongLongMap;
public class ArrayLongLongHashMapTest extends BaseKLongLongHashMapTest {
@Override
public KLongLongMap createKLongLongHashMap(int p_initalCapacity, float p_loadFactor) {
return new ArrayLongLongMap(p_initalCapacity, p_loadFactor);
}
}
| lgpl-3.0 |
qfactor2013/BizStudyParallel | DB/Day5/src/com/samepage/view/EmpView.java | 569 | package com.samepage.view;
import java.util.List;
import com.samepage.model.EmpDTO;
public class EmpView {
public static void print(String title, List<EmpDTO> emplist){
System.out.println(title + ">>========== ¿©·¯°Ç Ãâ·Â ===========<<");
for (EmpDTO empDTO : emplist) {
System.out.println(empDTO);
}
}
public static void printOne(String title, EmpDTO empDTO){
System.out.println(title + ">>========== ÇÑ°Ç Ãâ·Â ===========<<");
System.out.println(empDTO);
}
public static void sysMessage(String message){
System.out.println(message);
}
}
| lgpl-3.0 |
simeshev/parabuild-ci | 3rdparty/findbugs086src/src/java/edu/umd/cs/findbugs/detect/NoteSuppressedWarnings.java | 4473 | /*
* FindBugs - Find bugs in Java programs
* Copyright (C) 2003,2004 University of Maryland
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package edu.umd.cs.findbugs.detect;
import java.util.*;
import edu.umd.cs.findbugs.*;
import edu.umd.cs.findbugs.ba.AnalysisContext;
import edu.umd.cs.findbugs.ba.ClassContext;
import edu.umd.cs.findbugs.visitclass.AnnotationVisitor;
import org.apache.bcel.Repository;
import org.apache.bcel.classfile.*;
import edu.umd.cs.findbugs.visitclass.Constants2;
import static edu.umd.cs.findbugs.visitclass.Constants2.*;
public class NoteSuppressedWarnings extends AnnotationVisitor
implements Detector, Constants2 {
private static Set<String> packages = new HashSet<String>();
private SuppressionMatcher suppressionMatcher;
private BugReporter bugReporter;
private AnalysisContext analysisContext;
private NoteSuppressedWarnings recursiveDetector;
public NoteSuppressedWarnings(BugReporter bugReporter) {
this(bugReporter, false);
}
public NoteSuppressedWarnings(BugReporter bugReporter, boolean recursive) {
if (!recursive) {
DelegatingBugReporter b = (DelegatingBugReporter) bugReporter;
BugReporter origBugReporter = b.getRealBugReporter();
suppressionMatcher = new SuppressionMatcher();
BugReporter filterBugReporter = new FilterBugReporter(origBugReporter, suppressionMatcher, false);
b.setRealBugReporter(filterBugReporter);
recursiveDetector = new NoteSuppressedWarnings(bugReporter,true);
recursiveDetector.suppressionMatcher =
suppressionMatcher;
}
this.bugReporter = bugReporter;
}
public void setAnalysisContext(AnalysisContext analysisContext) {
this.analysisContext = analysisContext;
}
public void visitClassContext(ClassContext classContext) {
classContext.getJavaClass().accept(this);
}
public void visit(JavaClass obj) {
if (recursiveDetector == null) return;
try {
if (getClassName().endsWith("package-info")) return;
String packageName = getPackageName().replace('/', '.');
if (!packages.add(packageName)) return;
String packageInfo = "package-info";
if (packageName.length() > 0)
packageInfo = packageName + "." + packageInfo;
JavaClass packageInfoClass = Repository.lookupClass(packageInfo);
recursiveDetector.visitJavaClass(packageInfoClass);
} catch (ClassNotFoundException e) {
// ignore
}
}
public void visitAnnotation(String annotationClass, Map<String, Object> map,
boolean runtimeVisible) {
if (!annotationClass.endsWith("SuppressWarnings")) return;
Object value = map.get("value");
if (value == null || !(value instanceof Object[])) {
suppressWarning(null);
return;
}
Object [] suppressedWarnings = (Object[]) value;
if (suppressedWarnings.length == 0)
suppressWarning(null);
else for(int i = 0; i < suppressedWarnings.length; i++)
suppressWarning((String)suppressedWarnings[i]);
}
private void suppressWarning(String pattern) {
String className = getDottedClassName();
ClassAnnotation clazz = new ClassAnnotation(getDottedClassName());
if (className.endsWith("package-info") && recursiveDetector == null)
suppressionMatcher.addPackageSuppressor(
new PackageWarningSuppressor(pattern,
getPackageName().replace('/', '.')));
else if (visitingMethod())
suppressionMatcher.addSuppressor(
new MethodWarningSuppressor(pattern,
clazz, MethodAnnotation.fromVisitedMethod(this)));
else if (visitingField())
suppressionMatcher.addSuppressor(
new FieldWarningSuppressor(pattern,
clazz, FieldAnnotation.fromVisitedField(this)));
else
suppressionMatcher.addSuppressor(
new ClassWarningSuppressor(pattern,
clazz));
}
public void report() {
}
}
| lgpl-3.0 |
snmaher/xacml4j | xacml-core/src/main/java/org/xacml4j/v30/pdp/FunctionParamSpec.java | 1952 | package org.xacml4j.v30.pdp;
/*
* #%L
* Xacml4J Core Engine Implementation
* %%
* Copyright (C) 2009 - 2014 Xacml4J.org
* %%
* 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 java.util.ListIterator;
import org.xacml4j.v30.Expression;
import org.xacml4j.v30.ValueType;
import org.xacml4j.v30.spi.function.FunctionParamSpecVisitor;
public interface FunctionParamSpec
{
/**
* Validates if the "sequence" of expressions
* from the current position is valid according
* this specification. Iterator will be advanced to
* the next expression after "sequence"
*
* @param it an iterator
* @return {@code true} if sequence of
* expressions starting at the current position
* is valid according this spec
*/
boolean validate(ListIterator<Expression> it);
Expression getDefaultValue();
boolean isOptional();
/**
* Tests if instances of a given value type
* can be used as values for a function
* parameter specified by this specification
*
* @param type a value type
* @return {@code true}
*/
boolean isValidParamType(ValueType type);
/**
* Tests if this parameter is variadic
*
* @return {@code true} if a function
* parameter represented by this object is
* variadic
*/
boolean isVariadic();
void accept(FunctionParamSpecVisitor v);
}
| lgpl-3.0 |
cswaroop/Catalano-Framework | Catalano.Image/src/Catalano/Imaging/Filters/FrequencyFilter.java | 3543 | // Catalano Imaging Library
// The Catalano Framework
//
// Copyright © Diego Catalano, 2015
// diego.catalano at live.com
//
// Copyright © Andrew Kirillov, 2007-2008
// andrew.kirillov@gmail.com
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
//
package Catalano.Imaging.Filters;
import Catalano.Core.IntRange;
import Catalano.Math.ComplexNumber;
/**
* Filtering of frequencies outside of specified range in complex Fourier transformed image.
* @author Diego Catalano
*/
public class FrequencyFilter {
private IntRange freq = new IntRange(0, 1024);
/**
* Initializes a new instance of the FrequencyFilter class.
*/
public FrequencyFilter() {}
/**
* Initializes a new instance of the FrequencyFilter class.
* @param min Minimum value for to keep.
* @param max Maximum value for to keep.
*/
public FrequencyFilter(int min, int max){
this.freq = new IntRange(min, max);
}
/**
* Initializes a new instance of the FrequencyFilter class.S
* @param range IntRange.
*/
public FrequencyFilter(IntRange range) {
this.freq = range;
}
/**
* Get range of frequencies to keep.
* @return IntRange.
*/
public IntRange getFrequencyRange() {
return freq;
}
/**
* Set range of frequencies to keep.
* @param freq IntRange.
*/
public void setFrequencyRange(IntRange freq) {
this.freq = freq;
}
/**
* Apply filter to an fourierTransform.
* @param fourierTransform Fourier transformed.
*/
public void ApplyInPlace(FourierTransform fourierTransform){
if (!fourierTransform.isFourierTransformed()) {
try {
throw new Exception("the image should be fourier transformed.");
} catch (Exception e) {
e.printStackTrace();
}
}
int width = fourierTransform.getWidth();
int height = fourierTransform.getHeight();
int halfWidth = width / 2;
int halfHeight = height / 2;
int min = freq.getMin();
int max = freq.getMax();
ComplexNumber[][] c = fourierTransform.getData();
for ( int i = 0; i < height; i++ ){
int y = i - halfHeight;
for ( int j = 0; j < width; j++ ){
int x = j - halfWidth;
int d = (int) Math.sqrt( x * x + y * y );
// filter values outside the range
if ( ( d > max ) || ( d < min ) ){
c[i][j].real = 0;
c[i][j].imaginary = 0;
}
}
}
}
}
| lgpl-3.0 |
salviof/SBJSFComp | htmlOffiline/Volverine/tag/src/main/java/org/primefaces/adamantium/view/data/datatable/ColumnsView.java | 3441 | /*
* Copyright 2009-2014 PrimeTek.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.primefaces.adamantium.view.data.datatable;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ManagedProperty;
import javax.faces.bean.ViewScoped;
import javax.faces.component.UIComponent;
import javax.faces.context.FacesContext;
import org.primefaces.adamantium.domain.Car;
import org.primefaces.adamantium.service.CarService;
@ManagedBean(name="dtColumnsView")
@ViewScoped
public class ColumnsView implements Serializable {
private final static List<String> VALID_COLUMN_KEYS = Arrays.asList("id", "brand", "year", "color", "price");
private String columnTemplate = "id brand year";
private List<ColumnModel> columns;
private List<Car> cars;
private List<Car> filteredCars;
@ManagedProperty("#{carService}")
private CarService service;
@PostConstruct
public void init() {
cars = service.createCars(10);
createDynamicColumns();
}
public List<Car> getCars() {
return cars;
}
public List<Car> getFilteredCars() {
return filteredCars;
}
public void setFilteredCars(List<Car> filteredCars) {
this.filteredCars = filteredCars;
}
public void setService(CarService service) {
this.service = service;
}
public String getColumnTemplate() {
return columnTemplate;
}
public void setColumnTemplate(String columnTemplate) {
this.columnTemplate = columnTemplate;
}
public List<ColumnModel> getColumns() {
return columns;
}
private void createDynamicColumns() {
String[] columnKeys = columnTemplate.split(" ");
columns = new ArrayList<ColumnModel>();
for(String columnKey : columnKeys) {
String key = columnKey.trim();
if(VALID_COLUMN_KEYS.contains(key)) {
columns.add(new ColumnModel(columnKey.toUpperCase(), columnKey));
}
}
}
public void updateColumns() {
//reset table state
UIComponent table = FacesContext.getCurrentInstance().getViewRoot().findComponent(":form:cars");
table.setValueExpression("sortBy", null);
//update columns
createDynamicColumns();
}
static public class ColumnModel implements Serializable {
private String header;
private String property;
public ColumnModel(String header, String property) {
this.header = header;
this.property = property;
}
public String getHeader() {
return header;
}
public String getProperty() {
return property;
}
}
}
| lgpl-3.0 |
mrjato/BDBM | gui/es/uvigo/esei/sing/bdbm/gui/configuration/ConfigurationPanel.java | 16988 | package es.uvigo.esei.sing.bdbm.gui.configuration;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.io.File;
import java.util.EventListener;
import java.util.EventObject;
import java.util.concurrent.Callable;
import javax.swing.AbstractAction;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JTextField;
import es.uvigo.esei.sing.bdbm.gui.BDBMGUIController;
public class ConfigurationPanel extends JPanel {
private static final long serialVersionUID = 1L;
private final BDBMGUIController controller;
private final JTextField txtRepository;
private final JTextField txtBLAST;
private final JTextField txtEMBOSS;
private final JTextField txtBedTools;
private final JTextField txtSplign;
private final JTextField txtCompart;
private final JButton btnBuildRepository;
public ConfigurationPanel(BDBMGUIController controller) {
super();
this.controller = controller;
// this.setPreferredSize(new Dimension(600, 140));
final GroupLayout layout = new GroupLayout(this);
layout.setAutoCreateContainerGaps(true);
layout.setAutoCreateGaps(true);
this.setLayout(layout);
final JLabel lblRepository = new JLabel("Repository Path");
final JLabel lblBLAST = new JLabel("BLAST Path");
final JLabel lblEMBOSS = new JLabel("EMBOSS Path");
final JLabel lblBedTools = new JLabel("BedTools Path");
final JLabel lblSplign = new JLabel("Splign Path");
final JLabel lblCompart = new JLabel("Compart Path");
final File repositoryPath = this.controller.getEnvironment()
.getRepositoryPaths().getBaseDirectory();
final File blastBD = this.controller.getEnvironment()
.getBLASTBinaries().getBaseDirectory();
final File embossBD = this.controller.getEnvironment()
.getEMBOSSBinaries().getBaseDirectory();
final File bedToolsBD = this.controller.getEnvironment()
.getBedToolsBinaries().getBaseDirectory();
final File splignBD = this.controller.getEnvironment()
.getSplignBinaries().getBaseDirectory();
final File compartBD = this.controller.getEnvironment()
.getCompartBinaries().getBaseDirectory();
this.txtRepository = new JTextField(repositoryPath.getAbsolutePath());
this.txtBLAST = new JTextField(blastBD == null ? "" : blastBD.getAbsolutePath());
this.txtEMBOSS = new JTextField(embossBD == null ? "" : embossBD.getAbsolutePath());
this.txtBedTools = new JTextField(bedToolsBD == null ? "" : bedToolsBD.getAbsolutePath());
this.txtSplign = new JTextField(splignBD == null ? "" : splignBD.getAbsolutePath());
this.txtCompart = new JTextField(compartBD == null ? "" : compartBD.getAbsolutePath());
this.txtRepository.setEditable(false);
this.txtBLAST.setEditable(false);
this.txtEMBOSS.setEditable(false);
this.txtBedTools.setEditable(false);
this.txtSplign.setEditable(false);
this.txtCompart.setEditable(false);
final JButton btnRepository = new JButton("Select...");
final JButton btnBLASTSelect = new JButton("Select...");
final JButton btnEMBOSSSelect = new JButton("Select...");
final JButton btnBedToolsSelect = new JButton("Select...");
final JButton btnSplignSelect = new JButton("Select...");
final JButton btnCompartSelect = new JButton("Select...");
final JButton btnBLASTInPath = new JButton("In system path");
final JButton btnEMBOSSInPath = new JButton("In system path");
final JButton btnBedToolsInPath = new JButton("In system path");
final JButton btnSplignInPath = new JButton("In system path");
final JButton btnCompartInPath = new JButton("In system path");
this.btnBuildRepository = new JButton(new AbstractAction("Build") {
private static final long serialVersionUID = 1L;
@Override
public void actionPerformed(ActionEvent e) {
ConfigurationPanel.this.buildRepository();
}
});
this.btnBuildRepository.setEnabled(false);
layout.setVerticalGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup()
.addComponent(lblRepository, Alignment.CENTER)
.addComponent(this.txtRepository)
.addComponent(btnRepository)
.addComponent(this.btnBuildRepository)
)
.addGroup(layout.createParallelGroup()
.addComponent(lblBLAST, Alignment.CENTER)
.addComponent(this.txtBLAST)
.addComponent(btnBLASTSelect)
.addComponent(btnBLASTInPath)
)
.addGroup(layout.createParallelGroup()
.addComponent(lblEMBOSS, Alignment.CENTER)
.addComponent(this.txtEMBOSS)
.addComponent(btnEMBOSSSelect)
.addComponent(btnEMBOSSInPath)
)
.addGroup(layout.createParallelGroup()
.addComponent(lblBedTools, Alignment.CENTER)
.addComponent(this.txtBedTools)
.addComponent(btnBedToolsSelect)
.addComponent(btnBedToolsInPath)
)
.addGroup(layout.createParallelGroup()
.addComponent(lblSplign, Alignment.CENTER)
.addComponent(this.txtSplign)
.addComponent(btnSplignSelect)
.addComponent(btnSplignInPath)
)
.addGroup(layout.createParallelGroup()
.addComponent(lblCompart, Alignment.CENTER)
.addComponent(this.txtCompart)
.addComponent(btnCompartSelect)
.addComponent(btnCompartInPath)
)
);
layout.setHorizontalGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup()
.addComponent(lblRepository)
.addComponent(lblBLAST)
.addComponent(lblEMBOSS)
.addComponent(lblBedTools)
.addComponent(lblSplign)
.addComponent(lblCompart)
)
.addGroup(layout.createParallelGroup()
.addComponent(this.txtRepository)
.addComponent(this.txtBLAST)
.addComponent(this.txtEMBOSS)
.addComponent(this.txtBedTools)
.addComponent(this.txtSplign)
.addComponent(this.txtCompart)
)
.addGroup(layout.createParallelGroup()
.addComponent(btnRepository)
.addComponent(btnBLASTSelect)
.addComponent(btnEMBOSSSelect)
.addComponent(btnBedToolsSelect)
.addComponent(btnSplignSelect)
.addComponent(btnCompartSelect)
)
.addGroup(layout.createParallelGroup()
.addComponent(this.btnBuildRepository)
.addComponent(btnBLASTInPath)
.addComponent(btnEMBOSSInPath)
.addComponent(btnBedToolsInPath)
.addComponent(btnSplignInPath)
.addComponent(btnCompartInPath)
)
);
final Callable<Boolean> callbackRepositorySelection = new Callable<Boolean>() {
@Override
public Boolean call() {
if (ConfigurationPanel.this.isValidRepositoryPath()) {
btnBuildRepository.setEnabled(false);
} else {
btnBuildRepository.setEnabled(true);
if (JOptionPane.showConfirmDialog(
ConfigurationPanel.this,
"Repository path does not exist or its structure is incomplete. Do you wish to build repository structure?",
"Invalid Repository",
JOptionPane.YES_NO_OPTION,
JOptionPane.WARNING_MESSAGE
) == JOptionPane.YES_OPTION) {
ConfigurationPanel.this.buildRepository();
}
}
return true;
}
};
btnRepository.addActionListener(
new PathSelectionActionListener(this.txtRepository, callbackRepositorySelection)
);
final Callable<Boolean> callbackCheckBLAST = new Callable<Boolean>() {
@Override
public Boolean call() {
if (ConfigurationPanel.this.isValidBLASTPath()) {
return true;
} else {
JOptionPane.showMessageDialog(
ConfigurationPanel.this,
"Invalid BLAST binaries path. Please, change the selected path",
"Invalid Path",
JOptionPane.ERROR_MESSAGE
);
return false;
}
}
};
btnBLASTSelect.addActionListener(
new PathSelectionActionListener(this.txtBLAST, callbackCheckBLAST)
);
btnBLASTInPath.addActionListener(
new SystemPathSelectionActionListener(this.txtBLAST, callbackCheckBLAST)
);
final Callable<Boolean> callbackCheckEMBOSS = new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
if (ConfigurationPanel.this.isValidEMBOSSPath()) {
return true;
} else {
JOptionPane.showMessageDialog(
ConfigurationPanel.this,
"Invalid EMBOSS binaries path. Please, change the selected path",
"Invalid Path",
JOptionPane.ERROR_MESSAGE
);
return false;
}
}
};
btnEMBOSSSelect.addActionListener(
new PathSelectionActionListener(this.txtEMBOSS, callbackCheckEMBOSS)
);
btnEMBOSSInPath.addActionListener(
new SystemPathSelectionActionListener(this.txtEMBOSS, callbackCheckEMBOSS)
);
final Callable<Boolean> callbackCheckBedTools = new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
if (ConfigurationPanel.this.isValidBedToolsPath()) {
return true;
} else {
JOptionPane.showMessageDialog(
ConfigurationPanel.this,
"Invalid bedtools binaries path. Please, change the selected path",
"Invalid Path",
JOptionPane.ERROR_MESSAGE
);
return false;
}
}
};
btnBedToolsSelect.addActionListener(
new PathSelectionActionListener(this.txtBedTools, callbackCheckBedTools)
);
btnBedToolsInPath.addActionListener(
new SystemPathSelectionActionListener(this.txtBedTools, callbackCheckBedTools)
);
final Callable<Boolean> callbackCheckSplign = new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
if (ConfigurationPanel.this.isValidSplignPath()) {
return true;
} else {
JOptionPane.showMessageDialog(
ConfigurationPanel.this,
"Invalid splign binaries path. Please, change the selected path",
"Invalid Path",
JOptionPane.ERROR_MESSAGE
);
return false;
}
}
};
btnSplignSelect.addActionListener(
new PathSelectionActionListener(this.txtSplign, callbackCheckSplign)
);
btnSplignInPath.addActionListener(
new SystemPathSelectionActionListener(this.txtSplign, callbackCheckSplign)
);
final Callable<Boolean> callbackCheckCompart = new Callable<Boolean>() {
@Override
public Boolean call() throws Exception {
if (ConfigurationPanel.this.isValidCompartPath()) {
return true;
} else {
JOptionPane.showMessageDialog(
ConfigurationPanel.this,
"Invalid compart binaries path. Please, change the selected path",
"Invalid Path",
JOptionPane.ERROR_MESSAGE
);
return false;
}
}
};
btnCompartSelect.addActionListener(
new PathSelectionActionListener(this.txtCompart, callbackCheckCompart)
);
btnCompartInPath.addActionListener(
new SystemPathSelectionActionListener(this.txtCompart, callbackCheckCompart)
);
}
public void addConfigurationChangeListener(ConfigurationChangeEventListener listener) {
this.listenerList.add(ConfigurationChangeEventListener.class, listener);
}
public void removeConfigurationChangeListener(ConfigurationChangeEventListener listener) {
this.listenerList.remove(ConfigurationChangeEventListener.class, listener);
}
protected void fireChangeEvent(ConfigurationChangeEvent event) {
final ConfigurationChangeEventListener[] listeners =
this.listenerList.getListeners(ConfigurationChangeEventListener.class);
for (ConfigurationChangeEventListener listener : listeners) {
listener.configurationChanged(event);
}
}
protected void fireChange() {
this.fireChangeEvent(new ConfigurationChangeEvent(this));
}
protected File getRepositoryDirectory() {
return new File(this.txtRepository.getText());
}
protected String getBLASTPath() {
return this.txtBLAST.getText().isEmpty() ?
null : new File(this.txtBLAST.getText()).getAbsolutePath();
}
protected String getEMBOSSPath() {
return this.txtEMBOSS.getText().isEmpty() ?
null : new File(this.txtEMBOSS.getText()).getAbsolutePath();
}
protected String getBedToolsPath() {
return this.txtBedTools.getText().isEmpty() ?
null : new File(this.txtBedTools.getText()).getAbsolutePath();
}
protected String getSplignPath() {
return this.txtSplign.getText().isEmpty() ?
null : new File(this.txtSplign.getText()).getAbsolutePath();
}
protected String getCompartPath() {
return this.txtCompart.getText().isEmpty() ?
null : new File(this.txtCompart.getText()).getAbsolutePath();
}
public boolean isValidRepositoryPath() {
return this.controller.getEnvironment()
.getRepositoryPaths()
.checkBaseDirectory(getRepositoryDirectory());
}
public boolean isValidBLASTPath() {
return this.controller.getManager().checkBLASTPath(getBLASTPath());
}
protected boolean isValidEMBOSSPath() {
return this.controller.getManager().checkEMBOSSPath(getEMBOSSPath());
}
protected boolean isValidBedToolsPath() {
return this.controller.getManager().checkBedToolsPath(getBedToolsPath());
}
protected boolean isValidSplignPath() {
return this.controller.getManager().checkSplignPath(getSplignPath());
}
protected boolean isValidCompartPath() {
return this.controller.getManager().checkCompartPath(getCompartPath());
}
protected void buildRepository() {
try {
this.controller.getEnvironment()
.getRepositoryPaths()
.buildBaseDirectory(this.getRepositoryDirectory());
this.btnBuildRepository.setEnabled(false);
JOptionPane.showMessageDialog(
ConfigurationPanel.this,
"Repository structure was correctly built.",
"Repository Built",
JOptionPane.INFORMATION_MESSAGE
);
this.fireChange();
} catch (Exception e) {
this.btnBuildRepository.setEnabled(true);
JOptionPane.showMessageDialog(
ConfigurationPanel.this,
"Error building repository. Please, check path and press 'Build' or change path",
"Repository Building Error",
JOptionPane.ERROR_MESSAGE
);
}
}
public PathsConfiguration getConfiguration() {
if (this.isValidRepositoryPath() && this.isValidBLASTPath()) {
final String blastPath = this.getBLASTPath();
final String embossPath = this.getEMBOSSPath();
final String bedToolsPath = this.getBedToolsPath();
final String splignPath = this.getSplignPath();
final String compartPath = this.getCompartPath();
return new PathsConfiguration(
this.getRepositoryDirectory(),
blastPath == null ? null : new File(blastPath),
embossPath == null ? null : new File(embossPath),
bedToolsPath == null ? null : new File(bedToolsPath),
splignPath == null ? null : new File(splignPath),
compartPath == null ? null : new File(compartPath)
);
} else {
return null;
}
}
private final class SystemPathSelectionActionListener implements
ActionListener {
private final JTextField txtAssociated;
private final Callable<Boolean> callback;
private SystemPathSelectionActionListener(JTextField txtAssociated, Callable<Boolean> callback) {
this.txtAssociated = txtAssociated;
this.callback = callback;
}
@Override
public void actionPerformed(ActionEvent e) {
final String previousPath = this.txtAssociated.getText();
this.txtAssociated.setText("");
try {
if (this.callback.call()) {
ConfigurationPanel.this.fireChange();
} else {
txtAssociated.setText(previousPath);
}
} catch (Exception ex) {
throw new RuntimeException(ex);
}
}
}
private final class PathSelectionActionListener implements ActionListener {
private final JTextField txtAssociated;
private final Callable<Boolean> callback;
private PathSelectionActionListener(JTextField txtAssociated, Callable<Boolean> callback) {
this.txtAssociated = txtAssociated;
this.callback = callback;
}
@Override
public void actionPerformed(ActionEvent e) {
final JFileChooser chooser = new JFileChooser(
new File(txtAssociated.getText())
);
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setMultiSelectionEnabled(false);
if (chooser.showOpenDialog(ConfigurationPanel.this) == JFileChooser.APPROVE_OPTION) {
final String previousPath = txtAssociated.getText();
txtAssociated.setText(chooser.getSelectedFile().getAbsolutePath());
try {
if (this.callback.call()) {
ConfigurationPanel.this.fireChange();
} else {
txtAssociated.setText(previousPath);
}
} catch (Exception e1) {
throw new RuntimeException(e1);
}
}
}
}
public static class ConfigurationChangeEvent extends EventObject {
private static final long serialVersionUID = 1L;
private final PathsConfiguration configuration;
protected ConfigurationChangeEvent(ConfigurationPanel panel) {
this(panel, panel.getConfiguration());
}
public ConfigurationChangeEvent(Object source, PathsConfiguration configuration) {
super(source);
this.configuration = configuration;
}
public PathsConfiguration getConfiguration() {
return configuration;
}
}
public static interface ConfigurationChangeEventListener extends EventListener {
public void configurationChanged(ConfigurationChangeEvent event);
}
}
| lgpl-3.0 |
ayondeep/sonarqube | server/sonar-server/src/main/java/org/sonar/server/batch/GlobalAction.java | 4163 | /*
* SonarQube, open source software quality management tool.
* Copyright (C) 2008-2014 SonarSource
* mailto:contact AT sonarsource DOT com
*
* SonarQube is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* SonarQube is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package org.sonar.server.batch;
import org.apache.commons.io.IOUtils;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.batch.protocol.input.GlobalRepositories;
import org.sonar.db.metric.MetricDto;
import org.sonar.core.permission.GlobalPermissions;
import org.sonar.db.DbSession;
import org.sonar.db.MyBatis;
import org.sonar.db.property.PropertiesDao;
import org.sonar.db.property.PropertyDto;
import org.sonar.server.db.DbClient;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.plugins.MimeTypes;
import org.sonar.server.user.UserSession;
public class GlobalAction implements BatchWsAction {
private final DbClient dbClient;
private final PropertiesDao propertiesDao;
private final UserSession userSession;
public GlobalAction(DbClient dbClient, PropertiesDao propertiesDao, UserSession userSession) {
this.dbClient = dbClient;
this.propertiesDao = propertiesDao;
this.userSession = userSession;
}
@Override
public void define(WebService.NewController controller) {
controller.createAction("global")
.setDescription("Return metrics and global properties")
.setSince("4.5")
.setInternal(true)
.setHandler(this);
}
@Override
public void handle(Request request, Response response) throws Exception {
boolean hasScanPerm = userSession.hasGlobalPermission(GlobalPermissions.SCAN_EXECUTION);
boolean hasPreviewPerm = userSession.hasGlobalPermission(GlobalPermissions.PREVIEW_EXECUTION);
if (!hasPreviewPerm && !hasScanPerm) {
throw new ForbiddenException(Messages.NO_PERMISSION);
}
DbSession session = dbClient.openSession(false);
try {
GlobalRepositories ref = new GlobalRepositories();
addMetrics(ref, session);
addSettings(ref, hasScanPerm, hasPreviewPerm, session);
response.stream().setMediaType(MimeTypes.JSON);
IOUtils.write(ref.toJson(), response.stream().output());
} finally {
MyBatis.closeQuietly(session);
}
}
private void addMetrics(GlobalRepositories ref, DbSession session) {
for (MetricDto metric : dbClient.metricDao().selectEnabled(session)) {
ref.addMetric(
new org.sonar.batch.protocol.input.Metric(metric.getId(), metric.getKey(),
metric.getValueType(),
metric.getDescription(),
metric.getDirection(),
metric.getKey(),
metric.isQualitative(),
metric.isUserManaged(),
metric.getWorstValue(),
metric.getBestValue(),
metric.isOptimizedBestValue()));
}
}
private void addSettings(GlobalRepositories ref, boolean hasScanPerm, boolean hasPreviewPerm, DbSession session) {
for (PropertyDto propertyDto : propertiesDao.selectGlobalProperties(session)) {
String key = propertyDto.getKey();
String value = propertyDto.getValue();
if (isPropertyAllowed(key, hasScanPerm, hasPreviewPerm)) {
ref.addGlobalSetting(key, value);
}
}
}
private static boolean isPropertyAllowed(String key, boolean hasScanPerm, boolean hasPreviewPerm) {
return !key.contains(".secured") || hasScanPerm || (key.contains(".license") && hasPreviewPerm);
}
}
| lgpl-3.0 |
SonarSource/sonarqube | server/sonar-ce/src/main/java/org/sonar/ce/configuration/package-info.java | 966 | /*
* SonarQube
* Copyright (C) 2009-2022 SonarSource SA
* mailto:info AT sonarsource DOT com
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 3 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public License
* along with this program; if not, write to the Free Software Foundation,
* Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
@ParametersAreNonnullByDefault
package org.sonar.ce.configuration;
import javax.annotation.ParametersAreNonnullByDefault;
| lgpl-3.0 |
qiqjiao/study | spring/springinaction/SpringInActionExamples/Chapter_06/thymeleaf/src/test/java/spitter/web/SpittleControllerTest.java | 3786 | package spitter.web;
import static org.hamcrest.Matchers.*;
import static org.mockito.Mockito.*;
import static org.springframework.test.web.servlet.request.MockMvcRequestBuilders.*;
import static org.springframework.test.web.servlet.result.MockMvcResultMatchers.*;
import static org.springframework.test.web.servlet.setup.MockMvcBuilders.*;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.junit.Test;
import org.springframework.test.web.servlet.MockMvc;
import org.springframework.web.servlet.view.InternalResourceView;
import spittr.Spittle;
import spittr.data.SpittleRepository;
import spittr.web.SpittleController;
public class SpittleControllerTest {
@Test
public void houldShowRecentSpittles() throws Exception {
List<Spittle> expectedSpittles = createSpittleList(20);
SpittleRepository mockRepository = mock(SpittleRepository.class);
when(mockRepository.findSpittles(Long.MAX_VALUE, 20))
.thenReturn(expectedSpittles);
SpittleController controller = new SpittleController(mockRepository);
MockMvc mockMvc = standaloneSetup(controller)
.setSingleView(new InternalResourceView("/WEB-INF/views/spittles.jsp"))
.build();
mockMvc.perform(get("/spittles"))
.andExpect(view().name("spittles"))
.andExpect(model().attributeExists("spittleList"))
.andExpect(model().attribute("spittleList",
hasItems(expectedSpittles.toArray())));
}
@Test
public void shouldShowPagedSpittles() throws Exception {
List<Spittle> expectedSpittles = createSpittleList(50);
SpittleRepository mockRepository = mock(SpittleRepository.class);
when(mockRepository.findSpittles(238900, 50))
.thenReturn(expectedSpittles);
SpittleController controller = new SpittleController(mockRepository);
MockMvc mockMvc = standaloneSetup(controller)
.setSingleView(new InternalResourceView("/WEB-INF/views/spittles.jsp"))
.build();
mockMvc.perform(get("/spittles?max=238900&count=50"))
.andExpect(view().name("spittles"))
.andExpect(model().attributeExists("spittleList"))
.andExpect(model().attribute("spittleList",
hasItems(expectedSpittles.toArray())));
}
@Test
public void testSpittle() throws Exception {
Spittle expectedSpittle = new Spittle("Hello", new Date());
SpittleRepository mockRepository = mock(SpittleRepository.class);
when(mockRepository.findOne(12345)).thenReturn(expectedSpittle);
SpittleController controller = new SpittleController(mockRepository);
MockMvc mockMvc = standaloneSetup(controller).build();
mockMvc.perform(get("/spittles/12345"))
.andExpect(view().name("spittle"))
.andExpect(model().attributeExists("spittle"))
.andExpect(model().attribute("spittle", expectedSpittle));
}
@Test
public void saveSpittle() throws Exception {
SpittleRepository mockRepository = mock(SpittleRepository.class);
SpittleController controller = new SpittleController(mockRepository);
MockMvc mockMvc = standaloneSetup(controller).build();
mockMvc.perform(post("/spittles")
.param("message", "Hello World") // this works, but isn't really testing what really happens
.param("longitude", "-81.5811668")
.param("latitude", "28.4159649")
)
.andExpect(redirectedUrl("/spittles"));
verify(mockRepository, atLeastOnce()).save(new Spittle(null, "Hello World", new Date(), -81.5811668, 28.4159649));
}
private List<Spittle> createSpittleList(int count) {
List<Spittle> spittles = new ArrayList<Spittle>();
for (int i=0; i < count; i++) {
spittles.add(new Spittle("Spittle " + i, new Date()));
}
return spittles;
}
}
| lgpl-3.0 |
christianhujer/japi | historic2/src/prj/net/sf/japi/util/filter/file/package-info.java | 936 | /*
* Copyright (C) 2009 Christian Hujer.
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
/**
* File Filtering.
* @author <a href="mailto:cher@riedquat.de">Christian Hujer</a>
* @since 0.1
*/
package net.sf.japi.util.filter.file;
| lgpl-3.0 |
jtdavids/jtdavids-reflex | jtdavids-reflex/src/main/java/com/example/jake/jtdavids_reflex/StatisticCalc.java | 8131 | /*
{{ jtdavids-reflex }}
Copyright (C) 2015 Jake Davidson
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.example.jake.jtdavids_reflex;
import android.content.SharedPreferences;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
* Created by Jake on 28/09/2015.
*/
public class StatisticCalc {
List<Double> reaction_times = new ArrayList<Double>();
public StatisticCalc() {
}
public void add(double time){
reaction_times.add(time);
}
public void clear(){
reaction_times.clear();
}
public String getAllTimeMin(){
//gets the minimum time of all recorded reaction times
//if no reaction times are recored, return 'N/A'
if (reaction_times.size() != 0) {
double min = reaction_times.get(reaction_times.size()-1);
for (int i = reaction_times.size()-2; i >= 0; i--) {
if (reaction_times.get(i) < min) {
min = reaction_times.get(i);
}
}
return String.valueOf(min);
} else{
return "N/A";
}
}
public String getSpecifiedTimeMin(int length){
//Gets the minimum reaction time of the last X reactions
//a negative value should not be passed into this method
//Since reactions are stored in a list, must iterate backwards through the list
//to retrieve reaction times in chronological order
if (reaction_times.size() != 0) {
if(reaction_times.size() < length){
length = reaction_times.size();
}
double min = reaction_times.get(reaction_times.size()-1);
for (int i = reaction_times.size()-2; i > reaction_times.size()-length; i--) {
if (reaction_times.get(i) < min) {
min = reaction_times.get(i);
}
}
return String.valueOf(min);
} else{
return "N/A";
}
}
public String getAllTimeMax(){
//gets the maximum reaction time of all reactions
if (reaction_times.size() !=0 ) {
double max = reaction_times.get(reaction_times.size()-1);
for (int i = reaction_times.size()-2; i >= 0; i--) {
if (reaction_times.get(i) > max) {
max = reaction_times.get(i);
}
}
return String.valueOf(max);
} else{
return "N/A";
}
}
public String getSpecifiedTimeMax(int length){
//Gets the maximum reaction time of the last X reactions
//a negative value should not be passed into this method
//Since reactions are stored in a list, must iterate backwards through the list
//to retrieve reaction times in chronological order
if (reaction_times.size() !=0 ) {
if(reaction_times.size() < length){
length = reaction_times.size();
}
double max = reaction_times.get(reaction_times.size()-1);
for (int i = reaction_times.size()-2; i > reaction_times.size()-length; i--) {
if (reaction_times.get(i) > max) {
max = reaction_times.get(i);
}
}
return String.valueOf(max);
}
else{
return "N/A";
}
}
public String getAllTimeAvg(){
//gets the average reaction time of all reactions
if (reaction_times.size() !=0 ) {
double avg = reaction_times.get(reaction_times.size()-1);
for (int i = reaction_times.size()-2; i >= 0; i--) {
avg = avg + reaction_times.get(i);
}
return String.valueOf((avg / reaction_times.size()));
} else{
return "N/A ";
}
}
public String getSpecifiedTimeAvg(int length){
//Gets the average reaction time of the last X reactions
//a negative value should not be passed into this method
//Since reactions are stored in a list, must iterate backwards through the list
//to retrieve reaction times in chronological order
if (reaction_times.size() !=0 ) {
if(reaction_times.size() < length){
length = reaction_times.size();
}
double avg = reaction_times.get(reaction_times.size()-1);
for (int i = reaction_times.size()-2; i >= reaction_times.size()-length; i--) {
avg = avg + reaction_times.get(i);
}
return String.valueOf((avg / length));
}else{
return "N/A ";
}
}
public String getAllTimeMed(){
//gets the median reaction time of all reactions
if (reaction_times.size() !=0 ) {
List<Double> sorted_times = new ArrayList<Double>(reaction_times);
Collections.sort(sorted_times);
return String.valueOf((sorted_times.get(sorted_times.size() / 2)));
}
else{
return "N/A";
}
}
public String getSpecifiedTimeMed(int length){
//Gets the median reaction time of the last X reactions
//a negative value should not be passed into this method
if (reaction_times.size() != 0 ) {
if(reaction_times.size() < length){
length = reaction_times.size();
}
List<Double> sorted_times = new ArrayList<Double>(reaction_times.subList(0, length));
Collections.sort(sorted_times);
return String.valueOf((sorted_times.get(sorted_times.size() / 2)));
}else{
return "N/A";
}
}
public String getStatsMessage(SharedPreferences twoplayers_score, SharedPreferences threeplayers_score, SharedPreferences fourplayers_score){
return ("______SINGLEPLAYER______\n" +
" MIN TIME:\n" +
"All Time: " + getAllTimeMin() + "\nLast 10 times: " + getSpecifiedTimeMin(10) + "\nLast 100 times: " + getSpecifiedTimeMin(100) + "\n" +
" MAX TIME:\n" +
"All Time: " + getAllTimeMax() + "\nLast 10 times: " + getSpecifiedTimeMax(10) + "\nLast 100 times: " + getSpecifiedTimeMax(100) + "\n" +
" AVERAGE TIME:\n" +
"All Time: " + getAllTimeAvg() + "\nLast 10 times: " + getSpecifiedTimeAvg(10) + "\nLast 100 times: " + getSpecifiedTimeAvg(100) + "\n" +
" MEDIAN TIME:\n" +
"All Time: " + getAllTimeMed() + "\nLast 10 times: " + getSpecifiedTimeMed(10) + "\nLast 100 times: " + getSpecifiedTimeMed(100) + "\n" +
"______PARTY PLAY______\n" +
" 2 PLAYERS:\n" +
"Player 1: " + String.valueOf(twoplayers_score.getInt("player1", 0)) + "\nPlayer 2: " + String.valueOf(twoplayers_score.getInt("player2", 0)) + "\n" +
" 3 PLAYERS:\n" +
"Player 1: " + String.valueOf(threeplayers_score.getInt("player1", 0)) + "\nPlayer 2: " + String.valueOf(threeplayers_score.getInt("player2", 0)) + "\nPlayer 3: " + String.valueOf(threeplayers_score.getInt("player3", 0)) + "\n" +
" 4 PLAYERS:\n" +
"Player 1: " + String.valueOf(fourplayers_score.getInt("player1", 0)) + "\nPlayer 2: " + String.valueOf(fourplayers_score.getInt("player2", 0)) + "\nPlayer 3: " + String.valueOf(fourplayers_score.getInt("player3", 0)) + "\nPlayer 4: " + String.valueOf(fourplayers_score.getInt("player4", 0)) + "\n");
}
}
| lgpl-3.0 |
swethapts/cloudsim | sources/org/cloudbus/cloudsim/examples/power/steady/ThrMmt.java | 1797 | package org.cloudbus.cloudsim.examples.power.steady;
import java.io.IOException;
/**
* A simulation of a heterogeneous power aware data center that applies the
* Static Threshold (THR) VM allocation policy and Minimum Migration Time (MMT)
* VM selection policy.
*
* The remaining configuration parameters are in the Constants and
* SteadyConstants classes.
*
* If you are using any algorithms, policies or workload included in the power
* package please cite the following paper:
*
* Anton Beloglazov, and Rajkumar Buyya, "Optimal Online Deterministic
* Algorithms and Adaptive Heuristics for Energy and Performance Efficient
* Dynamic Consolidation of Virtual Machines in Cloud Data Centers", Concurrency
* and Computation: Practice and Experience (CCPE), Volume 24, Issue 13, Pages:
* 1397-1420, John Wiley & Sons, Ltd, New York, USA, 2012
*
* @author Anton Beloglazov
* @since Jan 5, 2012
*/
public class ThrMmt {
/**
* The main method.
*
* @param args
* the arguments
* @throws IOException
* Signals that an I/O exception has occurred.
*/
public static void main(String[] args) throws IOException {
boolean enableOutput = true;
boolean outputToFile = false;
String inputFolder = "";
String outputFolder = "";
String workload = "steady"; // Steady workload
String vmAllocationPolicy = "thr"; // Static Threshold (THR) VM
// allocation policy
String vmSelectionPolicy = "mmt"; // Minimum Migration Time (MMT) VM
// selection policy
String parameter = "0.8"; // the static utilization threshold
new SteadyRunner(enableOutput, outputToFile, inputFolder, outputFolder,
workload, vmAllocationPolicy, vmSelectionPolicy, parameter);
}
}
| lgpl-3.0 |
dresden-ocl/dresdenocl | plugins/org.dresdenocl.tools.CWM/src/orgomg/cwm/analysis/olap/impl/LevelBasedHierarchyImpl.java | 4857 | /**
* <copyright>
* </copyright>
*
* $Id$
*/
package orgomg.cwm.analysis.olap.impl;
import java.util.Collection;
import org.eclipse.emf.common.notify.NotificationChain;
import org.eclipse.emf.common.util.EList;
import org.eclipse.emf.ecore.EClass;
import org.eclipse.emf.ecore.InternalEObject;
import org.eclipse.emf.ecore.util.EObjectContainmentWithInverseEList;
import org.eclipse.emf.ecore.util.InternalEList;
import orgomg.cwm.analysis.olap.HierarchyLevelAssociation;
import orgomg.cwm.analysis.olap.LevelBasedHierarchy;
import orgomg.cwm.analysis.olap.OlapPackage;
/**
* <!-- begin-user-doc -->
* An implementation of the model object '<em><b>Level Based Hierarchy</b></em>'.
* <!-- end-user-doc -->
* <p>
* The following features are implemented:
* <ul>
* <li>{@link orgomg.cwm.analysis.olap.impl.LevelBasedHierarchyImpl#getHierarchyLevelAssociation <em>Hierarchy Level Association</em>}</li>
* </ul>
* </p>
*
* @generated
*/
public class LevelBasedHierarchyImpl extends HierarchyImpl implements LevelBasedHierarchy {
/**
* The cached value of the '{@link #getHierarchyLevelAssociation() <em>Hierarchy Level Association</em>}' containment reference list.
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @see #getHierarchyLevelAssociation()
* @generated
* @ordered
*/
protected EList<HierarchyLevelAssociation> hierarchyLevelAssociation;
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
protected LevelBasedHierarchyImpl() {
super();
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
protected EClass eStaticClass() {
return OlapPackage.Literals.LEVEL_BASED_HIERARCHY;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
public EList<HierarchyLevelAssociation> getHierarchyLevelAssociation() {
if (hierarchyLevelAssociation == null) {
hierarchyLevelAssociation = new EObjectContainmentWithInverseEList<HierarchyLevelAssociation>(HierarchyLevelAssociation.class, this, OlapPackage.LEVEL_BASED_HIERARCHY__HIERARCHY_LEVEL_ASSOCIATION, OlapPackage.HIERARCHY_LEVEL_ASSOCIATION__LEVEL_BASED_HIERARCHY);
}
return hierarchyLevelAssociation;
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public NotificationChain eInverseAdd(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case OlapPackage.LEVEL_BASED_HIERARCHY__HIERARCHY_LEVEL_ASSOCIATION:
return ((InternalEList<InternalEObject>)(InternalEList<?>)getHierarchyLevelAssociation()).basicAdd(otherEnd, msgs);
}
return super.eInverseAdd(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public NotificationChain eInverseRemove(InternalEObject otherEnd, int featureID, NotificationChain msgs) {
switch (featureID) {
case OlapPackage.LEVEL_BASED_HIERARCHY__HIERARCHY_LEVEL_ASSOCIATION:
return ((InternalEList<?>)getHierarchyLevelAssociation()).basicRemove(otherEnd, msgs);
}
return super.eInverseRemove(otherEnd, featureID, msgs);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public Object eGet(int featureID, boolean resolve, boolean coreType) {
switch (featureID) {
case OlapPackage.LEVEL_BASED_HIERARCHY__HIERARCHY_LEVEL_ASSOCIATION:
return getHierarchyLevelAssociation();
}
return super.eGet(featureID, resolve, coreType);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@SuppressWarnings("unchecked")
@Override
public void eSet(int featureID, Object newValue) {
switch (featureID) {
case OlapPackage.LEVEL_BASED_HIERARCHY__HIERARCHY_LEVEL_ASSOCIATION:
getHierarchyLevelAssociation().clear();
getHierarchyLevelAssociation().addAll((Collection<? extends HierarchyLevelAssociation>)newValue);
return;
}
super.eSet(featureID, newValue);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public void eUnset(int featureID) {
switch (featureID) {
case OlapPackage.LEVEL_BASED_HIERARCHY__HIERARCHY_LEVEL_ASSOCIATION:
getHierarchyLevelAssociation().clear();
return;
}
super.eUnset(featureID);
}
/**
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
* @generated
*/
@Override
public boolean eIsSet(int featureID) {
switch (featureID) {
case OlapPackage.LEVEL_BASED_HIERARCHY__HIERARCHY_LEVEL_ASSOCIATION:
return hierarchyLevelAssociation != null && !hierarchyLevelAssociation.isEmpty();
}
return super.eIsSet(featureID);
}
} //LevelBasedHierarchyImpl
| lgpl-3.0 |
jacky8hyf/musique | dependencies/wavpack/src/main/java/com/wavpack/decoder/WavpackContext.java | 1036 | package com.wavpack.decoder;
import java.io.RandomAccessFile;
/*
** WavpackContext.java
**
** Copyright (c) 2007 - 2008 Peter McQuillan
**
** All Rights Reserved.
**
** Distributed under the BSD Software License (see license.txt)
**
*/
public class WavpackContext {
WavpackConfig config = new WavpackConfig();
WavpackStream stream = new WavpackStream();
byte read_buffer[] = new byte[65536]; // was uchar in C
int[] temp_buffer = new int[Defines.SAMPLE_BUFFER_SIZE];
int[] temp_buffer2 = new int[Defines.SAMPLE_BUFFER_SIZE];
String error_message = "";
boolean error;
RandomAccessFile infile;
long total_samples, crc_errors, first_flags; // was uint32_t in C
int open_flags, norm_offset;
int reduced_channels = 0;
int lossy_blocks;
int status = 0; // 0 ok, 1 error
public boolean isError() {
return error;
}
public String getErrorMessage() {
return error_message;
}
} | lgpl-3.0 |
kidaa/isis | core/metamodel/src/main/java/org/apache/isis/core/metamodel/facets/object/callbacks/remove/RemovingCallbackFacetViaMethod.java | 2249 | /*
* 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.isis.core.metamodel.facets.object.callbacks.remove;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import org.apache.isis.core.metamodel.adapter.ObjectAdapter;
import org.apache.isis.core.metamodel.facetapi.FacetHolder;
import org.apache.isis.core.metamodel.facets.ImperativeFacet;
public class RemovingCallbackFacetViaMethod extends RemovingCallbackFacetAbstract implements ImperativeFacet {
private final List<Method> methods = new ArrayList<Method>();
public RemovingCallbackFacetViaMethod(final Method method, final FacetHolder holder) {
super(holder);
addMethod(method);
}
@Override
public void addMethod(final Method method) {
methods.add(method);
}
@Override
public boolean impliesResolve() {
return false;
}
@Override
public Intent getIntent(final Method method) {
return Intent.LIFECYCLE;
}
@Override
public boolean impliesObjectChanged() {
return false;
}
@Override
public List<Method> getMethods() {
return Collections.unmodifiableList(methods);
}
@Override
public void invoke(final ObjectAdapter adapter) {
ObjectAdapter.InvokeUtils.invokeAll(methods, adapter);
}
@Override
protected String toStringValues() {
return "methods=" + methods;
}
}
| apache-2.0 |
alibaba/jstorm | jstorm-core/src/main/java/com/alibaba/jstorm/message/netty/NettyContext.java | 4482 | /**
* 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 com.alibaba.jstorm.message.netty;
import backtype.storm.Config;
import backtype.storm.messaging.IConnection;
import backtype.storm.messaging.IContext;
import backtype.storm.utils.DisruptorQueue;
import backtype.storm.utils.Utils;
import com.alibaba.jstorm.callback.AsyncLoopThread;
import com.alibaba.jstorm.metric.MetricDef;
import com.alibaba.jstorm.utils.JStormUtils;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
import org.jboss.netty.channel.socket.nio.NioClientSocketChannelFactory;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class NettyContext implements IContext {
private final static Logger LOG = LoggerFactory.getLogger(NettyContext.class);
@SuppressWarnings("rawtypes")
private Map stormConf;
private NioClientSocketChannelFactory clientChannelFactory;
private ReconnectRunnable reconnector;
@SuppressWarnings("unused")
public NettyContext() {
}
/**
* initialization per Storm configuration
*/
@SuppressWarnings("rawtypes")
public void prepare(Map stormConf) {
this.stormConf = stormConf;
int maxWorkers = Utils.getInt(stormConf.get(Config.STORM_MESSAGING_NETTY_CLIENT_WORKER_THREADS));
ThreadFactory bossFactory = new NettyRenameThreadFactory(MetricDef.NETTY_CLI + "boss");
ThreadFactory workerFactory = new NettyRenameThreadFactory(MetricDef.NETTY_CLI + "worker");
if (maxWorkers > 0) {
clientChannelFactory = new NioClientSocketChannelFactory(Executors.newCachedThreadPool(bossFactory),
Executors.newCachedThreadPool(workerFactory), maxWorkers);
} else {
clientChannelFactory = new NioClientSocketChannelFactory(Executors.newCachedThreadPool(bossFactory),
Executors.newCachedThreadPool(workerFactory));
}
reconnector = new ReconnectRunnable();
new AsyncLoopThread(reconnector, true, Thread.MIN_PRIORITY, true);
}
@Override
public IConnection bind(String topologyId, int port, ConcurrentHashMap<Integer, DisruptorQueue> deserializedQueue,
DisruptorQueue recvControlQueue, boolean bstartRec, Set<Integer> workerTasks) {
IConnection retConnection = null;
try {
retConnection = new NettyServer(stormConf, port, deserializedQueue, recvControlQueue, bstartRec, workerTasks);
} catch (Throwable e) {
LOG.error("Failed to create NettyServer", e);
JStormUtils.halt_process(-1, "Failed to bind " + port);
}
return retConnection;
}
@Override
public IConnection connect(String topologyId, String host, int port) {
return new NettyClientAsync(stormConf, clientChannelFactory, host, port, reconnector, new HashSet<Integer>(), new HashSet<Integer>());
}
@Override
public IConnection connect(String topologyId, String host, int port, Set<Integer> sourceTasks, Set<Integer> targetTasks) {
return new NettyClientAsync(stormConf, clientChannelFactory, host, port, reconnector, sourceTasks, targetTasks);
}
/**
* terminate this context
*/
public void term() {
/* clientScheduleService.shutdown();
try {
clientScheduleService.awaitTermination(10, TimeUnit.SECONDS);
} catch (InterruptedException e) {
LOG.error("Error when shutting down client scheduler", e);
}*/
clientChannelFactory.releaseExternalResources();
reconnector.shutdown();
}
}
| apache-2.0 |
awhitford/Resteasy | testsuite/integration-tests/src/test/java/org/jboss/resteasy/test/providers/multipart/resource/ContextProvidersCustomer.java | 607 | package org.jboss.resteasy.test.providers.multipart.resource;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement(name = "customer")
@XmlAccessorType(XmlAccessType.FIELD)
public class ContextProvidersCustomer {
@XmlElement
private String name;
public ContextProvidersCustomer() {
}
public ContextProvidersCustomer(final String name) {
this.name = name;
}
public String getName() {
return name;
}
}
| apache-2.0 |
KeithYokoma/Amalgam | amalgam/src/main/java/com/amalgam/database/CursorUtils.java | 5998 | /*
* Copyright (C) 2013 nohana, Inc. 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.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.amalgam.database;
import android.annotation.TargetApi;
import android.database.Cursor;
import android.os.Build;
/**
* Utility for the {@link android.database.Cursor}
*/
@SuppressWarnings("unused") // public APIs
public final class CursorUtils {
private static final int TRUE = 1;
private CursorUtils() {
throw new AssertionError();
}
/**
* Close with null checks.
* @param cursor to close.
*/
public static void close(Cursor cursor) {
if (cursor == null) {
return;
}
cursor.close();
}
/**
* Read the boolean data for the column.
* @see android.database.Cursor#getColumnIndex(String).
* @param cursor the cursor.
* @param columnName the column name.
* @return the boolean value.
*/
public static boolean getBoolean(Cursor cursor, String columnName) {
return cursor != null && cursor.getInt(cursor.getColumnIndex(columnName)) == TRUE;
}
/**
* Read the int data for the column.
* @see android.database.Cursor#getInt(int).
* @see android.database.Cursor#getColumnIndex(String).
* @param cursor the cursor.
* @param columnName the column name.
* @return the int value.
*/
public static int getInt(Cursor cursor, String columnName) {
if (cursor == null) {
return -1;
}
return cursor.getInt(cursor.getColumnIndex(columnName));
}
/**
* Read the String data for the column.
* @see android.database.Cursor#getString(int).
* @see android.database.Cursor#getColumnIndex(String).
* @param cursor the cursor.
* @param columnName the column name.
* @return the String value.
*/
public static String getString(Cursor cursor, String columnName) {
if (cursor == null) {
return null;
}
return cursor.getString(cursor.getColumnIndex(columnName));
}
/**
* Read the short data for the column.
* @see android.database.Cursor#getShort(int).
* @see android.database.Cursor#getColumnIndex(String).
* @param cursor the cursor.
* @param columnName the column name.
* @return the short value.
*/
public static short getShort(Cursor cursor, String columnName) {
if (cursor == null) {
return -1;
}
return cursor.getShort(cursor.getColumnIndex(columnName));
}
/**
* Read the long data for the column.
* @see android.database.Cursor#getLong(int).
* @see android.database.Cursor#getColumnIndex(String).
* @param cursor the cursor.
* @param columnName the column name.
* @return the long value.
*/
public static long getLong(Cursor cursor, String columnName) {
if (cursor == null) {
return -1;
}
return cursor.getLong(cursor.getColumnIndex(columnName));
}
/**
* Read the double data for the column.
* @see android.database.Cursor#getDouble(int).
* @see android.database.Cursor#getColumnIndex(String).
* @param cursor the cursor.
* @param columnName the column name.
* @return the double value.
*/
public static double getDouble(Cursor cursor, String columnName) {
if (cursor == null) {
return -1;
}
return cursor.getDouble(cursor.getColumnIndex(columnName));
}
/**
* Read the float data for the column.
* @see android.database.Cursor#getFloat(int).
* @see android.database.Cursor#getColumnIndex(String).
* @param cursor the cursor.
* @param columnName the column name.
* @return the float value.
*/
public static float getFloat(Cursor cursor, String columnName) {
if (cursor == null) {
return -1;
}
return cursor.getFloat(cursor.getColumnIndex(columnName));
}
/**
* Read the blob data for the column.
* @see android.database.Cursor#getBlob(int).
* @see android.database.Cursor#getColumnIndex(String).
* @param cursor the cursor.
* @param columnName the column name.
* @return the blob value.
*/
public static byte[] getBlob(Cursor cursor, String columnName) {
if (cursor == null) {
return null;
}
return cursor.getBlob(cursor.getColumnIndex(columnName));
}
/**
* Checks the type of the column.
* @see android.database.Cursor#getType(int).
* @see android.database.Cursor#getColumnIndex(String).
* @param cursor the cursor.
* @param columnName the column name.
* @return the type of the column.
*/
@TargetApi(Build.VERSION_CODES.HONEYCOMB)
public static int getType(Cursor cursor, String columnName) {
if (cursor == null) {
return Cursor.FIELD_TYPE_NULL;
}
return cursor.getType(cursor.getColumnIndex(columnName));
}
/**
* Checks if the column value is null or not.
* @see android.database.Cursor#isNull(int).
* @see android.database.Cursor#getColumnIndex(String).
* @param cursor the cursor.
* @param columnName the column name.
* @return true if the column value is null.
*/
public static boolean isNull(Cursor cursor, String columnName) {
return cursor != null && cursor.isNull(cursor.getColumnIndex(columnName));
}
}
| apache-2.0 |
vivantech/kc_fixes | src/main/java/org/kuali/kra/irb/ProtocolDaoOjb.java | 6383 | /*
* Copyright 2005-2014 The Kuali Foundation
*
* Licensed under the Educational Community 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.opensource.org/licenses/ecl1.php
*
* 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.kuali.kra.irb;
import org.kuali.kra.irb.actions.submit.ProtocolSubmission;
import org.kuali.kra.irb.personnel.ProtocolPerson;
import org.kuali.kra.irb.personnel.ProtocolUnit;
import org.kuali.kra.irb.protocol.funding.ProtocolFundingSource;
import org.kuali.kra.irb.protocol.location.ProtocolLocation;
import org.kuali.kra.irb.protocol.research.ProtocolResearchArea;
import org.kuali.kra.protocol.CriteriaFieldHelper;
import org.kuali.kra.protocol.ProtocolBase;
import org.kuali.kra.protocol.ProtocolDaoOjbBase;
import org.kuali.kra.protocol.ProtocolLookupConstants;
import org.kuali.kra.protocol.actions.ProtocolActionBase;
import org.kuali.kra.protocol.actions.submit.ProtocolSubmissionBase;
import org.kuali.kra.protocol.personnel.ProtocolPersonBase;
import org.kuali.kra.protocol.personnel.ProtocolUnitBase;
import org.kuali.rice.krad.service.util.OjbCollectionAware;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
/**
*
* This class is the implementation for ProtocolDao interface.
*/
class ProtocolDaoOjb extends ProtocolDaoOjbBase<Protocol> implements OjbCollectionAware, ProtocolDao {
/**
* The APPROVED_SUBMISSION_STATUS_CODE contains the status code of approved protocol submissions (i.e. 203).
*/
private static final Collection<String> APPROVED_SUBMISSION_STATUS_CODES = Arrays.asList(new String[] {"203"});
/**
* The ACTIVE_PROTOCOL_STATUS_CODES contains the various active status codes for a protocol.
* <li> 200 - Active, open to enrollment
* <li> 201 - Active, closed to enrollment
* <li> 202 - Active, data analysis only
*/
private static final Collection<String> ACTIVE_PROTOCOL_STATUS_CODES = Arrays.asList(new String[] {"200", "201", "202"});
/**
* The REVISION_REQUESTED_PROTOCOL_ACTION_TYPE_CODES contains the protocol action codes for the protocol revision requests.
* <li> 202 - Specific Minor Revision
* <li> 203 - Substantive Revision Requested
*/
private static final Collection<String> REVISION_REQUESTED_PROTOCOL_ACTION_TYPE_CODES = Arrays.asList(new String[] {"202", "203"});
/**
* The REVISION_REQUESTED_PROTOCOL_STATUS_CODES contains the various status codes for protocol revision requests.
* <li> 102 - Specific Minor Revision
* <li> 104 - Substantive Revision Requested
*/
private static final Collection<String> REVISION_REQUESTED_PROTOCOL_STATUS_CODES = Arrays.asList(new String[] {"102", "104"});
private static final Collection<String> PENDING_AMENDMENT_RENEWALS_STATUS_CODES = Arrays.asList(new String[]{"100", "101", "102", "103", "104", "105", "106"});
@Override
protected Collection<String> getApprovedSubmissionStatusCodesHook() {
return APPROVED_SUBMISSION_STATUS_CODES;
}
@Override
protected Collection<String> getActiveProtocolStatusCodesHook() {
return ACTIVE_PROTOCOL_STATUS_CODES;
}
@Override
protected Collection<String> getRevisionRequestedProtocolActionTypeCodesHook() {
return REVISION_REQUESTED_PROTOCOL_ACTION_TYPE_CODES;
}
@Override
protected Collection<String> getRevisionRequestedProtocolStatusCodesHook() {
return REVISION_REQUESTED_PROTOCOL_STATUS_CODES;
}
@Override
protected Class<? extends ProtocolActionBase> getProtocolActionBOClassHoook() {
return org.kuali.kra.irb.actions.ProtocolAction.class;
}
@Override
protected void initRoleListsHook(List<String> investigatorRoles, List<String> personRoles) {
investigatorRoles.add("PI");
investigatorRoles.add("COI");
personRoles.add("SP");
personRoles.add("CA");
personRoles.add("CRC");
}
@Override
protected Collection<String> getPendingAmendmentRenewalsProtocolStatusCodesHook() {
return PENDING_AMENDMENT_RENEWALS_STATUS_CODES;
}
@Override
protected Class<? extends ProtocolBase> getProtocolBOClassHook() {
return Protocol.class;
}
@Override
protected Class<? extends ProtocolPersonBase> getProtocolPersonBOClassHook() {
return ProtocolPerson.class;
}
@Override
protected Class<? extends ProtocolUnitBase> getProtocolUnitBOClassHook() {
return ProtocolUnit.class;
}
@Override
protected Class<? extends ProtocolSubmissionBase> getProtocolSubmissionBOClassHook() {
return ProtocolSubmission.class;
}
@Override
protected List<CriteriaFieldHelper> getCriteriaFields() {
List<CriteriaFieldHelper> criteriaFields = new ArrayList<CriteriaFieldHelper>();
criteriaFields.add(new CriteriaFieldHelper(ProtocolLookupConstants.Property.KEY_PERSON,
ProtocolLookupConstants.Property.PERSON_NAME,
ProtocolPerson.class));
criteriaFields.add(new CriteriaFieldHelper(ProtocolLookupConstants.Property.INVESTIGATOR,
ProtocolLookupConstants.Property.PERSON_NAME,
ProtocolPerson.class));
criteriaFields.add(new CriteriaFieldHelper(ProtocolLookupConstants.Property.FUNDING_SOURCE,
ProtocolLookupConstants.Property.FUNDING_SOURCE_NUMBER,
ProtocolFundingSource.class));
criteriaFields.add(new CriteriaFieldHelper(ProtocolLookupConstants.Property.PERFORMING_ORGANIZATION_ID,
ProtocolLookupConstants.Property.ORGANIZATION_ID,
ProtocolLocation.class));
criteriaFields.add(new CriteriaFieldHelper(ProtocolLookupConstants.Property.RESEARCH_AREA_CODE,
ProtocolLookupConstants.Property.RESEARCH_AREA_CODE,
ProtocolResearchArea.class));
return criteriaFields;
}
}
| apache-2.0 |
snakerflow/snaker-web | src/main/java/com/snakerflow/framework/orm/PropertyFilter.java | 4884 | /**
* Copyright (c) 2005-20010 springside.org.cn
*
* Licensed under the Apache License, Version 2.0 (the "License");
*
* $Id: PropertyFilter.java 1205 2010-09-09 15:12:17Z calvinxiu $
*/
package com.snakerflow.framework.orm;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import com.snakerflow.framework.utils.ConvertUtils;
import com.snakerflow.framework.utils.ServletUtils;
import org.springframework.util.Assert;
/**
* 与具体ORM实现无关的属性过滤条件封装类, 主要记录页面中简单的搜索过滤条件.
*
* @author calvin
*/
public class PropertyFilter {
/** 多个属性间OR关系的分隔符. */
public static final String OR_SEPARATOR = "_OR_";
/** 属性比较类型. */
public enum MatchType {
EQ, LIKE, LT, GT, LE, GE;
}
/** 属性数据类型. */
public enum PropertyType {
S(String.class), I(Integer.class), L(Long.class), N(Double.class), D(Date.class), B(Boolean.class);
private Class<?> clazz;
private PropertyType(Class<?> clazz) {
this.clazz = clazz;
}
public Class<?> getValue() {
return clazz;
}
}
private MatchType matchType = null;
private Object matchValue = null;
private Class<?> propertyClass = null;
private String[] propertyNames = null;
public PropertyFilter() {
}
/**
* @param filterName 比较属性字符串,含待比较的比较类型、属性值类型及属性列表.
* eg. LIKES_NAME_OR_LOGIN_NAME
* @param value 待比较的值.
*/
public PropertyFilter(final String filterName, final String value) {
String firstPart = StringUtils.substringBefore(filterName, "_");
String matchTypeCode = StringUtils.substring(firstPart, 0, firstPart.length() - 1);
String propertyTypeCode = StringUtils.substring(firstPart, firstPart.length() - 1, firstPart.length());
try {
matchType = Enum.valueOf(MatchType.class, matchTypeCode);
} catch (RuntimeException e) {
throw new IllegalArgumentException("filter名称" + filterName + "没有按规则编写,无法得到属性比较类型.", e);
}
try {
propertyClass = Enum.valueOf(PropertyType.class, propertyTypeCode).getValue();
} catch (RuntimeException e) {
throw new IllegalArgumentException("filter名称" + filterName + "没有按规则编写,无法得到属性值类型.", e);
}
String propertyNameStr = StringUtils.substringAfter(filterName, "_");
Assert.isTrue(StringUtils.isNotBlank(propertyNameStr), "filter名称" + filterName + "没有按规则编写,无法得到属性名称.");
propertyNames = StringUtils.splitByWholeSeparator(propertyNameStr, PropertyFilter.OR_SEPARATOR);
this.matchValue = ConvertUtils.convertStringToObject(value, propertyClass);
}
/**
* 从HttpRequest中创建PropertyFilter列表, 默认Filter属性名前缀为filter.
*
* @see #buildFromHttpRequest(HttpServletRequest, String)
*/
public static List<PropertyFilter> buildFromHttpRequest(final HttpServletRequest request) {
return buildFromHttpRequest(request, "filter");
}
/**
* 从HttpRequest中创建PropertyFilter列表
* PropertyFilter命名规则为Filter属性前缀_比较类型属性类型_属性名.
*
* eg.
* filter_EQS_name
* filter_LIKES_name_OR_email
*/
public static List<PropertyFilter> buildFromHttpRequest(final HttpServletRequest request, final String filterPrefix) {
List<PropertyFilter> filterList = new ArrayList<PropertyFilter>();
//从request中获取含属性前缀名的参数,构造去除前缀名后的参数Map.
Map<String, Object> filterParamMap = ServletUtils.getParametersStartingWith(request, filterPrefix + "_");
//分析参数Map,构造PropertyFilter列表
for (Map.Entry<String, Object> entry : filterParamMap.entrySet()) {
String filterName = entry.getKey();
String value = (String) entry.getValue();
//如果value值为空,则忽略此filter.
if (StringUtils.isNotBlank(value)) {
PropertyFilter filter = new PropertyFilter(filterName, value);
filterList.add(filter);
}
}
return filterList;
}
/**
* 获取比较值的类型.
*/
public Class<?> getPropertyClass() {
return propertyClass;
}
/**
* 获取比较方式.
*/
public MatchType getMatchType() {
return matchType;
}
/**
* 获取比较值.
*/
public Object getMatchValue() {
return matchValue;
}
/**
* 获取比较属性名称列表.
*/
public String[] getPropertyNames() {
return propertyNames;
}
/**
* 获取唯一的比较属性名称.
*/
public String getPropertyName() {
Assert.isTrue(propertyNames.length == 1, "There are not only one property in this filter.");
return propertyNames[0];
}
/**
* 是否比较多个属性.
*/
public boolean hasMultiProperties() {
return (propertyNames.length > 1);
}
}
| apache-2.0 |
immortius/gestalt | gestalt-module/src/main/java/org/terasology/gestalt/module/exceptions/MissingModuleMetadataException.java | 1036 | /*
* Copyright 2019 MovingBlocks
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.terasology.gestalt.module.exceptions;
/**
* Exception for when metadata cannot be resolved for a module
*/
public class MissingModuleMetadataException extends RuntimeException {
public MissingModuleMetadataException() {
}
public MissingModuleMetadataException(String s) {
super(s);
}
public MissingModuleMetadataException(String s, Throwable throwable) {
super(s, throwable);
}
}
| apache-2.0 |
apache/avro | lang/java/avro/src/main/java/org/apache/avro/SchemaBuilderException.java | 1094 | /*
* 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
*
* https://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.avro;
/** Thrown for errors building schemas. */
public class SchemaBuilderException extends AvroRuntimeException {
public SchemaBuilderException(Throwable cause) {
super(cause);
}
public SchemaBuilderException(String message) {
super(message);
}
}
| apache-2.0 |
tgroh/incubator-beam | sdks/java/harness/src/test/java/org/apache/beam/fn/harness/state/MultimapSideInputTest.java | 2861 | /*
* 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.beam.fn.harness.state;
import static org.junit.Assert.assertArrayEquals;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.Iterables;
import com.google.protobuf.ByteString;
import java.io.IOException;
import org.apache.beam.model.fnexecution.v1.BeamFnApi.StateKey;
import org.apache.beam.sdk.coders.StringUtf8Coder;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
/** Tests for {@link MultimapSideInput}. */
@RunWith(JUnit4.class)
public class MultimapSideInputTest {
@Test
public void testGet() throws Exception {
FakeBeamFnStateClient fakeBeamFnStateClient = new FakeBeamFnStateClient(ImmutableMap.of(
key("A"), encode("A1", "A2", "A3"),
key("B"), encode("B1", "B2")));
MultimapSideInput<String, String> multimapSideInput = new MultimapSideInput<>(
fakeBeamFnStateClient,
"instructionId",
"ptransformId",
"sideInputId",
ByteString.copyFromUtf8("encodedWindow"),
StringUtf8Coder.of(),
StringUtf8Coder.of());
assertArrayEquals(new String[]{ "A1", "A2", "A3" },
Iterables.toArray(multimapSideInput.get("A"), String.class));
assertArrayEquals(new String[]{ "B1", "B2" },
Iterables.toArray(multimapSideInput.get("B"), String.class));
assertArrayEquals(new String[]{ },
Iterables.toArray(multimapSideInput.get("unknown"), String.class));
}
private StateKey key(String id) throws IOException {
return StateKey.newBuilder().setMultimapSideInput(
StateKey.MultimapSideInput.newBuilder()
.setPtransformId("ptransformId")
.setSideInputId("sideInputId")
.setWindow(ByteString.copyFromUtf8("encodedWindow"))
.setKey(encode(id))).build();
}
private ByteString encode(String ... values) throws IOException {
ByteString.Output out = ByteString.newOutput();
for (String value : values) {
StringUtf8Coder.of().encode(value, out);
}
return out.toByteString();
}
}
| apache-2.0 |
Rakesh627/PhoneFinder | ParseStarterProject/src/main/java/com/mc/phonefinder/usersettings/FindPhoneInterface.java | 10791 | package com.mc.phonefinder.usersettings;
import android.content.Intent;
import android.content.SharedPreferences;
import android.net.Uri;
import android.preference.PreferenceManager;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.util.Log;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
import com.mc.phonefinder.R;
import com.mc.phonefinder.login.FindPhoneActivity;
import com.mc.phonefinder.login.SampleApplication;
import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseGeoPoint;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseUser;
import java.io.Serializable;
import java.util.List;
import java.util.Locale;
import java.util.concurrent.atomic.AtomicBoolean;
public class FindPhoneInterface extends ActionBarActivity {
/*
For the below: check if the setting is set for the user and if so let the user use the functionality.
View location - Referes to location column in Settings table
Show Phone finder image - Displays the image of the person who find the phone
View nearby users - Refers to otherUsers in Settings table
Alert my phone - Rings the phone to easily identify it
*/
static final boolean[] nearByUserSetting = new boolean[1];
static final boolean[] locationSetting = new boolean[1];
AtomicBoolean nearByUserSetting_check = new AtomicBoolean();
AtomicBoolean locPrefs_check = new AtomicBoolean();
public static String test = "Class";
static final String TAG="bharathdebug";
public void savePrefs(String key, boolean value)
{
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor edit = sp.edit();
edit.putBoolean(key, value);
edit.commit();
}
public boolean loadBoolPrefs(String key)
{
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
boolean cbVal = sp.getBoolean(key, false);
return cbVal;
}
public void savePrefs(String key, String value)
{
SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this);
SharedPreferences.Editor edit = sp.edit();
edit.putString(key, value);
edit.commit();
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_find_phone_interface);
final String ObjectId = (String)this.getIntent().getSerializableExtra("userObjectId");
nearByUserSetting[0] = false;
locationSetting[0] = false;
savePrefs("nearByUserSetting", false);
savePrefs("locationSetting", false);
Log.i(TAG,"Before inner class"+test);
// final String ObjectId = (String)this.getIntent().getSerializableExtra("userObjectId");
ParseQuery<ParseObject> getSettings = new ParseQuery<ParseObject>("Settings");
getSettings.whereEqualTo("userObjectId", ObjectId);
getSettings.findInBackground(new FindCallback<ParseObject>() {
@Override
public void done(List<ParseObject> objects, ParseException e) {
if (objects != null) {
Log.i(TAG, "Object not null");
if(objects.size()>0){
// nearByUserSetting[0] = objects.get(0).getBoolean("otherUser");
// locationSetting[0] = objects.get(0).getBoolean("location");
// test = "Inner class";
nearByUserSetting_check.set( objects.get(0).getBoolean("otherUser"));
locPrefs_check.set(objects.get(0).getBoolean("location"));
Log.i(TAG, "Inner class neary by " + String.valueOf(nearByUserSetting_check.get()));
Log.i(TAG,"Inner class Location pref "+ (String.valueOf(locPrefs_check.get())));
//
// savePrefs("nearByUserSetting", nearByUserSetting[0]);
// savePrefs("locationSetting", locationSetting[0]);
}
}
}
});
// nearByUserSetting_check=loadBoolPrefs("nearByUserSetting");
// locPrefs_check = loadBoolPrefs("locationSetting");
//
// Log.i(TAG,"Final val after inner class "+test);
// System.out.print("Camera Setting " + nearByUserSetting[0]);
Log.i(TAG,"Near by user "+ (String.valueOf(nearByUserSetting_check.get())));
Log.i(TAG,"Location pref "+ (String.valueOf(locPrefs_check.get())));
((Button) findViewById(R.id.nearbyUsers)).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(nearByUserSetting_check.get()) {
Intent i = new Intent();
savePrefs("findPhoneId", ObjectId);
Log.i(TAG, "FindPhoneInterface Object id " + ObjectId);
i.setClass(FindPhoneInterface.this, NearbyUserView.class);
//i.putExtra("userObjectId", ObjectId);
startActivity(i);
startActivity(new Intent(FindPhoneInterface.this, NearbyUserView.class));
}
else
{
Toast.makeText(FindPhoneInterface.this, "Find nearby user service not set ", Toast.LENGTH_SHORT).show();
}
}
});
((Button) findViewById(R.id.viewLocation)).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if(locPrefs_check.get()) {
Toast.makeText(FindPhoneInterface.this, "Getting Your Location", Toast.LENGTH_LONG)
.show();
String ObjectId = (String) FindPhoneInterface.this.getIntent().getSerializableExtra("userObjectId");
ParseQuery<ParseObject> query = ParseQuery.getQuery("Location");
if (!ObjectId.equals(null) && !ObjectId.equals("")) {
query.whereEqualTo("userId", ObjectId);
query.findInBackground(new FindCallback<ParseObject>() {
@Override
public void done(List<ParseObject> objects, ParseException e) {
ParseGeoPoint userLocation;
for (int i = 0; i < objects.size(); i++) {
userLocation = objects.get(i).getParseGeoPoint("location");
String uri = String.format(Locale.ENGLISH, "geo:%f,%f?q=%f,%f", userLocation.getLatitude(), userLocation.getLongitude(), userLocation.getLatitude(), userLocation.getLongitude());
//Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse("geo:%f,%f?q=%f,%f",userLocation.getLatitude(), userLocation.getLongitude(),userLocation.getLatitude(), userLocation.getLongitude()));
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(uri));
startActivity(intent);
Toast.makeText(FindPhoneInterface.this, "Opening Maps", Toast.LENGTH_LONG)
.show();
}
}
});
}
}
else {
Toast.makeText(FindPhoneInterface.this, "Location Preference service not set ", Toast.LENGTH_SHORT).show();
}
}});
//Bharath - View image of person who picked phone
((Button) findViewById(R.id.btn_phonepicker)).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// Starts an intent of the log in activity
Log.i(TAG,"Find face object id "+ObjectId);
savePrefs("findfaceObjId",ObjectId);
startActivity(new Intent(FindPhoneInterface.this, ShowPhoneFinderImage.class));
}
});
//Change ringer alert
((Button) findViewById(R.id.triggerAlert)).setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
ParseQuery<ParseObject> query = ParseQuery.getQuery("Settings");
query.whereEqualTo("userObjectId", ObjectId);
query.findInBackground(new FindCallback<ParseObject>() {
public void done(List<ParseObject> scoreList, ParseException e) {
//get current user
ParseUser user = ParseUser.getCurrentUser();
if (e == null) {
if (scoreList != null) {
if (scoreList.size() > 0) {
//store the location of the user with the objectId of the user
scoreList.get(0).put("alertPhone", true);
scoreList.get(0).saveInBackground();
Toast.makeText(FindPhoneInterface.this, "Phone Alerted", Toast.LENGTH_LONG)
.show();
}
} else {
ParseObject alertVal = new ParseObject("Settings");
alertVal.put("userObjectId", ObjectId);
alertVal.put("alertPhone", true);
scoreList.get(0).saveInBackground();
Toast.makeText(FindPhoneInterface.this, "Phone Alerted", Toast.LENGTH_LONG)
.show();
}
}
}
});
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_find_phone_interface, menu);
return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
| apache-2.0 |
jdeppe-pivotal/geode | geode-core/src/main/java/org/apache/geode/internal/cache/DiskStoreAttributes.java | 8257 | /*
* 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.geode.internal.cache;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import java.util.UUID;
import org.apache.geode.annotations.Immutable;
import org.apache.geode.cache.DiskStore;
import org.apache.geode.cache.DiskStoreFactory;
import org.apache.geode.internal.cache.persistence.DefaultDiskDirs;
/**
* Creates an attribute object for DiskStore.
* </p>
*
* @since GemFire prPersistSprint2
*/
public class DiskStoreAttributes implements Serializable, DiskStore {
private static final long serialVersionUID = 1L;
public boolean allowForceCompaction;
public boolean autoCompact;
public int compactionThreshold;
public int queueSize;
public int writeBufferSize;
public long maxOplogSizeInBytes;
public long timeInterval;
public int[] diskDirSizes;
private DiskDirSizesUnit diskDirSizesUnit;
public File[] diskDirs;
public String name;
private volatile float diskUsageWarningPct;
private volatile float diskUsageCriticalPct;
/**
* The default disk directory size unit.
*/
@Immutable
static final DiskDirSizesUnit DEFAULT_DISK_DIR_SIZES_UNIT = DiskDirSizesUnit.MEGABYTES;
public DiskStoreAttributes() {
// set all to defaults
autoCompact = DiskStoreFactory.DEFAULT_AUTO_COMPACT;
compactionThreshold = DiskStoreFactory.DEFAULT_COMPACTION_THRESHOLD;
allowForceCompaction = DiskStoreFactory.DEFAULT_ALLOW_FORCE_COMPACTION;
maxOplogSizeInBytes = DiskStoreFactory.DEFAULT_MAX_OPLOG_SIZE * (1024 * 1024);
timeInterval = DiskStoreFactory.DEFAULT_TIME_INTERVAL;
writeBufferSize = DiskStoreFactory.DEFAULT_WRITE_BUFFER_SIZE;
queueSize = DiskStoreFactory.DEFAULT_QUEUE_SIZE;
diskDirs = DefaultDiskDirs.getDefaultDiskDirs();
diskDirSizes = DiskStoreFactory.DEFAULT_DISK_DIR_SIZES;
diskDirSizesUnit = DEFAULT_DISK_DIR_SIZES_UNIT;
diskUsageWarningPct = DiskStoreFactory.DEFAULT_DISK_USAGE_WARNING_PERCENTAGE;
diskUsageCriticalPct = DiskStoreFactory.DEFAULT_DISK_USAGE_CRITICAL_PERCENTAGE;
}
@Override
public UUID getDiskStoreUUID() {
throw new UnsupportedOperationException("Not Implemented!");
}
/*
* (non-Javadoc)
*
* @see org.apache.geode.cache.DiskStore#getAllowForceCompaction()
*/
@Override
public boolean getAllowForceCompaction() {
return allowForceCompaction;
}
/*
* (non-Javadoc)
*
* @see org.apache.geode.cache.DiskStore#getAutoCompact()
*/
@Override
public boolean getAutoCompact() {
return autoCompact;
}
/*
* (non-Javadoc)
*
* @see org.apache.geode.cache.DiskStore#getCompactionThreshold()
*/
@Override
public int getCompactionThreshold() {
return compactionThreshold;
}
/*
* (non-Javadoc)
*
* @see org.apache.geode.cache.DiskStore#getDiskDirSizes()
*/
@Override
public int[] getDiskDirSizes() {
int[] result = new int[diskDirSizes.length];
System.arraycopy(diskDirSizes, 0, result, 0, diskDirSizes.length);
return result;
}
public DiskDirSizesUnit getDiskDirSizesUnit() {
return diskDirSizesUnit;
}
/*
* (non-Javadoc)
*
* @see org.apache.geode.cache.DiskStore#getDiskDirs()
*/
@Override
public File[] getDiskDirs() {
File[] result = new File[diskDirs.length];
System.arraycopy(diskDirs, 0, result, 0, diskDirs.length);
return result;
}
/*
* (non-Javadoc)
*
* @see org.apache.geode.cache.DiskStore#getMaxOplogSize()
*/
@Override
public long getMaxOplogSize() {
return maxOplogSizeInBytes / (1024 * 1024);
}
/**
* Used by unit tests
*/
public long getMaxOplogSizeInBytes() {
return maxOplogSizeInBytes;
}
/*
* (non-Javadoc)
*
* @see org.apache.geode.cache.DiskStore#getName()
*/
@Override
public String getName() {
return name;
}
/*
* (non-Javadoc)
*
* @see org.apache.geode.cache.DiskStore#getQueueSize()
*/
@Override
public int getQueueSize() {
return queueSize;
}
/*
* (non-Javadoc)
*
* @see org.apache.geode.cache.DiskStore#getTimeInterval()
*/
@Override
public long getTimeInterval() {
return timeInterval;
}
/*
* (non-Javadoc)
*
* @see org.apache.geode.cache.DiskStore#getWriteBufferSize()
*/
@Override
public int getWriteBufferSize() {
return writeBufferSize;
}
@Override
public void flush() {
// nothing needed
}
@Override
public void forceRoll() {
// nothing needed
}
@Override
public boolean forceCompaction() {
return false;
}
@Override
public void destroy() {
// nothing needed
}
@Override
public float getDiskUsageWarningPercentage() {
return diskUsageWarningPct;
}
@Override
public float getDiskUsageCriticalPercentage() {
return diskUsageCriticalPct;
}
@Override
public void setDiskUsageWarningPercentage(float warningPercent) {
DiskStoreMonitor.checkWarning(warningPercent);
diskUsageWarningPct = warningPercent;
}
@Override
public void setDiskUsageCriticalPercentage(float criticalPercent) {
DiskStoreMonitor.checkCritical(criticalPercent);
diskUsageCriticalPct = criticalPercent;
}
public void setDiskDirSizesUnit(DiskDirSizesUnit unit) {
diskDirSizesUnit = unit;
}
private void readObject(final java.io.ObjectInputStream in)
throws IOException, ClassNotFoundException {
in.defaultReadObject();
if (diskDirSizesUnit == null) {
diskDirSizesUnit = DEFAULT_DISK_DIR_SIZES_UNIT;
}
}
public static void checkMinAndMaxOplogSize(long maxOplogSize) {
long MAX = Long.MAX_VALUE / (1024 * 1024);
if (maxOplogSize > MAX) {
throw new IllegalArgumentException(
String.format(
"%s has to be a number that does not exceed %s so the value given %s is not acceptable",
"max oplog size", maxOplogSize, MAX));
}
checkMinOplogSize(maxOplogSize);
}
public static void checkMinOplogSize(long maxOplogSize) {
if (maxOplogSize < 0) {
throw new IllegalArgumentException(
String.format(
"Maximum Oplog size specified has to be a non-negative number and the value given %s is not acceptable",
maxOplogSize));
}
}
public static void checkQueueSize(int queueSize) {
if (queueSize < 0) {
throw new IllegalArgumentException(
String.format(
"Queue size specified has to be a non-negative number and the value given %s is not acceptable",
queueSize));
}
}
public static void checkWriteBufferSize(int writeBufferSize) {
if (writeBufferSize < 0) {
throw new IllegalArgumentException(
String.format(
"Write buffer size specified has to be a non-negative number and the value given %s is not acceptable",
writeBufferSize));
}
}
/**
* Verify all directory sizes are positive
*/
public static void verifyNonNegativeDirSize(int[] sizes) {
for (int size : sizes) {
if (size < 0) {
throw new IllegalArgumentException(
String.format("Dir size cannot be negative : %s",
size));
}
}
}
public static void checkTimeInterval(long timeInterval) {
if (timeInterval < 0) {
throw new IllegalArgumentException(
String.format(
"Time Interval specified has to be a non-negative number and the value given %s is not acceptable",
timeInterval));
}
}
}
| apache-2.0 |
Longri/cachebox3.0 | launcher/desktop_lwjgl/src/com/kitfox/svg/pathcmd/Arc.java | 9856 | /*
* SVG Salamander
* Copyright (c) 2004, Mark McKay
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or
* without modification, are permitted provided that the following
* conditions are met:
*
* - Redistributions of source code must retain the above
* copyright notice, this list of conditions and the following
* disclaimer.
* - Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following
* disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS
* FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE
* COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT,
* INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION)
* HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT,
* STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED
* OF THE POSSIBILITY OF SUCH DAMAGE.
*
* Mark McKay can be contacted at mark@kitfox.com. Salamander and other
* projects can be found at http://www.kitfox.com
*
* Created on January 26, 2004, 8:40 PM
*/
package com.kitfox.svg.pathcmd;
//import org.apache.batik.ext.awt.geom.ExtendedGeneralPath;
import java.awt.*;
import java.awt.geom.*;
/**
* This is a little used SVG function, as most editors will save curves as
* Beziers. To reduce the need to rely on the Batik library, this functionallity
* is being bypassed for the time being. In the future, it would be nice to
* extend the GeneralPath command to include the arcTo ability provided by Batik.
*
* @author Mark McKay
* @author <a href="mailto:mark@kitfox.com">Mark McKay</a>
*/
public class Arc extends PathCommand
{
public float rx = 0f;
public float ry = 0f;
public float xAxisRot = 0f;
public boolean largeArc = false;
public boolean sweep = false;
public float x = 0f;
public float y = 0f;
/** Creates a new instance of MoveTo */
public Arc() {
}
public Arc(boolean isRelative, float rx, float ry, float xAxisRot, boolean largeArc, boolean sweep, float x, float y) {
super(isRelative);
this.rx = rx;
this.ry = ry;
this.xAxisRot = xAxisRot;
this.largeArc = largeArc;
this.sweep = sweep;
this.x = x;
this.y = y;
}
// public void appendPath(ExtendedGeneralPath path, BuildHistory hist)
@Override
public void appendPath(GeneralPath path, BuildHistory hist)
{
float offx = isRelative ? hist.lastPoint.x : 0f;
float offy = isRelative ? hist.lastPoint.y : 0f;
arcTo(path, rx, ry, xAxisRot, largeArc, sweep,
x + offx, y + offy,
hist.lastPoint.x, hist.lastPoint.y);
// path.lineTo(x + offx, y + offy);
// hist.setPoint(x + offx, y + offy);
hist.setLastPoint(x + offx, y + offy);
hist.setLastKnot(x + offx, y + offy);
}
@Override
public int getNumKnotsAdded()
{
return 6;
}
/**
* Adds an elliptical arc, defined by two radii, an angle from the
* x-axis, a flag to choose the large arc or not, a flag to
* indicate if we increase or decrease the angles and the final
* point of the arc.
*
* @param rx the x radius of the ellipse
* @param ry the y radius of the ellipse
*
* @param angle the angle from the x-axis of the current
* coordinate system to the x-axis of the ellipse in degrees.
*
* @param largeArcFlag the large arc flag. If true the arc
* spanning less than or equal to 180 degrees is chosen, otherwise
* the arc spanning greater than 180 degrees is chosen
*
* @param sweepFlag the sweep flag. If true the line joining
* center to arc sweeps through decreasing angles otherwise it
* sweeps through increasing angles
*
* @param x the absolute x coordinate of the final point of the arc.
* @param y the absolute y coordinate of the final point of the arc.
* @param x0 - The absolute x coordinate of the initial point of the arc.
* @param y0 - The absolute y coordinate of the initial point of the arc.
*/
public void arcTo(GeneralPath path, float rx, float ry,
float angle,
boolean largeArcFlag,
boolean sweepFlag,
float x, float y, float x0, float y0)
{
// Ensure radii are valid
if (rx == 0 || ry == 0) {
path.lineTo((float) x, (float) y);
return;
}
if (x0 == x && y0 == y) {
// If the endpoints (x, y) and (x0, y0) are identical, then this
// is equivalent to omitting the elliptical arc segment entirely.
return;
}
Arc2D arc = computeArc(x0, y0, rx, ry, angle,
largeArcFlag, sweepFlag, x, y);
if (arc == null) return;
AffineTransform t = AffineTransform.getRotateInstance
(Math.toRadians(angle), arc.getCenterX(), arc.getCenterY());
Shape s = t.createTransformedShape(arc);
path.append(s, true);
}
/**
* This constructs an unrotated Arc2D from the SVG specification of an
* Elliptical arc. To get the final arc you need to apply a rotation
* transform such as:
*
* AffineTransform.getRotateInstance
* (angle, arc.getX()+arc.getWidth()/2, arc.getY()+arc.getHeight()/2);
*/
public static Arc2D computeArc(double x0, double y0,
double rx, double ry,
double angle,
boolean largeArcFlag,
boolean sweepFlag,
double x, double y) {
//
// Elliptical arc implementation based on the SVG specification notes
//
// Compute the half distance between the current and the final point
double dx2 = (x0 - x) / 2.0;
double dy2 = (y0 - y) / 2.0;
// Convert angle from degrees to radians
angle = Math.toRadians(angle % 360.0);
double cosAngle = Math.cos(angle);
double sinAngle = Math.sin(angle);
//
// Step 1 : Compute (x1, y1)
//
double x1 = (cosAngle * dx2 + sinAngle * dy2);
double y1 = (-sinAngle * dx2 + cosAngle * dy2);
// Ensure radii are large enough
rx = Math.abs(rx);
ry = Math.abs(ry);
double Prx = rx * rx;
double Pry = ry * ry;
double Px1 = x1 * x1;
double Py1 = y1 * y1;
// check that radii are large enough
double radiiCheck = Px1/Prx + Py1/Pry;
if (radiiCheck > 1) {
rx = Math.sqrt(radiiCheck) * rx;
ry = Math.sqrt(radiiCheck) * ry;
Prx = rx * rx;
Pry = ry * ry;
}
//
// Step 2 : Compute (cx1, cy1)
//
double sign = (largeArcFlag == sweepFlag) ? -1 : 1;
double sq = ((Prx*Pry)-(Prx*Py1)-(Pry*Px1)) / ((Prx*Py1)+(Pry*Px1));
sq = (sq < 0) ? 0 : sq;
double coef = (sign * Math.sqrt(sq));
double cx1 = coef * ((rx * y1) / ry);
double cy1 = coef * -((ry * x1) / rx);
//
// Step 3 : Compute (cx, cy) from (cx1, cy1)
//
double sx2 = (x0 + x) / 2.0;
double sy2 = (y0 + y) / 2.0;
double cx = sx2 + (cosAngle * cx1 - sinAngle * cy1);
double cy = sy2 + (sinAngle * cx1 + cosAngle * cy1);
//
// Step 4 : Compute the angleStart (angle1) and the angleExtent (dangle)
//
double ux = (x1 - cx1) / rx;
double uy = (y1 - cy1) / ry;
double vx = (-x1 - cx1) / rx;
double vy = (-y1 - cy1) / ry;
double p, n;
// Compute the angle start
n = Math.sqrt((ux * ux) + (uy * uy));
p = ux; // (1 * ux) + (0 * uy)
sign = (uy < 0) ? -1d : 1d;
double angleStart = Math.toDegrees(sign * Math.acos(p / n));
// Compute the angle extent
n = Math.sqrt((ux * ux + uy * uy) * (vx * vx + vy * vy));
p = ux * vx + uy * vy;
sign = (ux * vy - uy * vx < 0) ? -1d : 1d;
double angleExtent = Math.toDegrees(sign * Math.acos(p / n));
if(!sweepFlag && angleExtent > 0) {
angleExtent -= 360f;
} else if (sweepFlag && angleExtent < 0) {
angleExtent += 360f;
}
angleExtent %= 360f;
angleStart %= 360f;
//
// We can now build the resulting Arc2D in double precision
//
Arc2D.Double arc = new Arc2D.Double();
arc.x = cx - rx;
arc.y = cy - ry;
arc.width = rx * 2.0;
arc.height = ry * 2.0;
arc.start = -angleStart;
arc.extent = -angleExtent;
return arc;
}
@Override
public String toString()
{
return "A " + rx + " " + ry
+ " " + xAxisRot + " " + largeArc
+ " " + sweep
+ " " + x + " " + y;
}
}
| apache-2.0 |
mdogan/hazelcast | hazelcast/src/test/java/com/hazelcast/cache/CacheSerializationTest.java | 7031 | /*
* Copyright (c) 2008-2020, Hazelcast, Inc. 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.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.hazelcast.cache;
import com.hazelcast.cache.impl.CachePartitionEventData;
import com.hazelcast.cache.impl.CachePartitionSegment;
import com.hazelcast.cache.impl.CacheService;
import com.hazelcast.cache.impl.operation.CacheReplicationOperation;
import com.hazelcast.cache.impl.record.CacheRecord;
import com.hazelcast.cache.impl.record.CacheRecordFactory;
import com.hazelcast.cluster.Address;
import com.hazelcast.cluster.Member;
import com.hazelcast.cluster.impl.MemberImpl;
import com.hazelcast.config.InMemoryFormat;
import com.hazelcast.core.HazelcastInstance;
import com.hazelcast.instance.impl.HazelcastInstanceImpl;
import com.hazelcast.instance.impl.HazelcastInstanceProxy;
import com.hazelcast.internal.serialization.Data;
import com.hazelcast.internal.serialization.SerializationService;
import com.hazelcast.internal.serialization.SerializationServiceBuilder;
import com.hazelcast.internal.serialization.impl.DefaultSerializationServiceBuilder;
import com.hazelcast.internal.services.ServiceNamespace;
import com.hazelcast.internal.util.Clock;
import com.hazelcast.internal.util.CollectionUtil;
import com.hazelcast.spi.impl.NodeEngineImpl;
import com.hazelcast.test.HazelcastParallelClassRunner;
import com.hazelcast.test.HazelcastTestSupport;
import com.hazelcast.test.TestHazelcastInstanceFactory;
import com.hazelcast.test.annotation.ParallelJVMTest;
import com.hazelcast.test.annotation.QuickTest;
import com.hazelcast.version.MemberVersion;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.experimental.categories.Category;
import org.junit.runner.RunWith;
import javax.cache.Cache;
import javax.cache.CacheManager;
import javax.cache.configuration.CompleteConfiguration;
import javax.cache.configuration.MutableConfiguration;
import javax.cache.spi.CachingProvider;
import java.lang.reflect.Field;
import java.net.UnknownHostException;
import java.util.Collection;
import static com.hazelcast.cache.CacheTestSupport.createServerCachingProvider;
import static org.junit.Assert.assertEquals;
/**
* Serialization test class for JCache
*/
@RunWith(HazelcastParallelClassRunner.class)
@Category({QuickTest.class, ParallelJVMTest.class})
public class CacheSerializationTest extends HazelcastTestSupport {
SerializationService service;
@Before
public void setup() {
SerializationServiceBuilder builder = new DefaultSerializationServiceBuilder();
service = builder.build();
}
@After
public void tearDown() {
}
@Test
public void testCacheRecord_withBinaryInMemoryData() {
String value = randomString();
CacheRecord cacheRecord = createRecord(InMemoryFormat.BINARY, value);
Data cacheRecordData = service.toData(cacheRecord);
CacheRecord deserialized = service.toObject(cacheRecordData);
assertEquals(value, service.toObject(deserialized.getValue()));
}
@Test
public void testCacheRecord_withObjectInMemoryData() {
String value = randomString();
CacheRecord cacheRecord = createRecord(InMemoryFormat.OBJECT, value);
Data cacheRecordData = service.toData(cacheRecord);
CacheRecord deserialized = service.toObject(cacheRecordData);
assertEquals(value, deserialized.getValue());
}
@Test
public void test_CacheReplicationOperation_serialization() throws Exception {
TestHazelcastInstanceFactory factory = new TestHazelcastInstanceFactory(1);
HazelcastInstance hazelcastInstance = factory.newHazelcastInstance();
try {
CachingProvider provider = createServerCachingProvider(hazelcastInstance);
CacheManager manager = provider.getCacheManager();
CompleteConfiguration configuration = new MutableConfiguration();
Cache cache1 = manager.createCache("cache1", configuration);
Cache cache2 = manager.createCache("cache2", configuration);
Cache cache3 = manager.createCache("cache3", configuration);
for (int i = 0; i < 1000; i++) {
cache1.put("key" + i, i);
cache2.put("key" + i, i);
cache3.put("key" + i, i);
}
HazelcastInstanceProxy proxy = (HazelcastInstanceProxy) hazelcastInstance;
Field original = HazelcastInstanceProxy.class.getDeclaredField("original");
original.setAccessible(true);
HazelcastInstanceImpl impl = (HazelcastInstanceImpl) original.get(proxy);
NodeEngineImpl nodeEngine = impl.node.nodeEngine;
CacheService cacheService = nodeEngine.getService(CacheService.SERVICE_NAME);
int partitionCount = nodeEngine.getPartitionService().getPartitionCount();
for (int partitionId = 0; partitionId < partitionCount; partitionId++) {
CachePartitionSegment segment = cacheService.getSegment(partitionId);
int replicaIndex = 1;
Collection<ServiceNamespace> namespaces = segment.getAllNamespaces(replicaIndex);
if (CollectionUtil.isEmpty(namespaces)) {
continue;
}
CacheReplicationOperation operation = new CacheReplicationOperation();
operation.prepare(segment, namespaces, replicaIndex);
Data serialized = service.toData(operation);
try {
service.toObject(serialized);
} catch (Exception e) {
throw new Exception("Partition: " + partitionId, e);
}
}
} finally {
factory.shutdownAll();
}
}
@Test
public void testCachePartitionEventData() throws UnknownHostException {
Address address = new Address("127.0.0.1", 5701);
Member member = new MemberImpl(address, MemberVersion.UNKNOWN, true);
CachePartitionEventData cachePartitionEventData = new CachePartitionEventData("test", 1, member);
CachePartitionEventData deserialized = service.toObject(cachePartitionEventData);
assertEquals(cachePartitionEventData, deserialized);
}
private CacheRecord createRecord(InMemoryFormat format, String value) {
CacheRecordFactory factory = new CacheRecordFactory(format, service);
return factory.newRecordWithExpiry(value, Clock.currentTimeMillis(), -1);
}
}
| apache-2.0 |
seanzwx/tmp | seatalk/im/im-client/src/main/java/com/sean/im/client/push/handler/KickOutFlockHandler.java | 1004 | package com.sean.im.client.push.handler;
import com.alibaba.fastjson.JSON;
import com.sean.im.client.constant.Global;
import com.sean.im.client.core.ApplicationContext;
import com.sean.im.client.core.PushHandler;
import com.sean.im.client.form.MainForm;
import com.sean.im.client.tray.TrayManager;
import com.sean.im.client.util.MusicUtil;
import com.sean.im.commom.core.Protocol;
import com.sean.im.commom.entity.Message;
/**
* 移除群成员
* @author sean
*/
public class KickOutFlockHandler implements PushHandler
{
@Override
public void execute(Protocol notify)
{
Message msg = JSON.parseObject(notify.getParameter("msg"), Message.class);
// 界面上删除群
long flockId = Long.parseLong(msg.getContent());
MainForm.FORM.getFlockList().removeFlock(flockId);
// 压入消息队列
ApplicationContext.CTX.getMessageQueue().add(msg);
// 提示系统托盘闪烁
TrayManager.getInstance().startLight(0);
MusicUtil.play(Global.Root + "resource/sound/msg.wav");
}
}
| apache-2.0 |
jexp/idea2 | xml/impl/src/com/intellij/psi/impl/cache/impl/idCache/XHtmlIdIndexer.java | 1077 | /*
* Copyright 2000-2009 JetBrains s.r.o.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.intellij.psi.impl.cache.impl.idCache;
import com.intellij.lexer.Lexer;
import com.intellij.lexer.XHtmlHighlightingLexer;
import com.intellij.psi.impl.cache.impl.BaseFilterLexer;
import com.intellij.psi.impl.cache.impl.id.LexerBasedIdIndexer;
public class XHtmlIdIndexer extends LexerBasedIdIndexer {
protected Lexer createLexer(final BaseFilterLexer.OccurrenceConsumer consumer) {
return new XHtmlFilterLexer(new XHtmlHighlightingLexer(), consumer);
}
}
| apache-2.0 |
asanka88/apache-synapse | modules/core/src/main/java/org/apache/synapse/deployers/TaskDeployer.java | 7123 | /*
* 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.synapse.deployers;
import org.apache.axiom.om.OMElement;
import org.apache.axis2.deployment.DeploymentException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.synapse.Startup;
import org.apache.synapse.config.xml.MultiXMLConfigurationBuilder;
import org.apache.synapse.config.xml.StartupFinder;
import java.io.File;
import java.util.Properties;
/**
* Handles the <code>Startup Task</code> deployment and undeployment
*
* @see org.apache.synapse.deployers.AbstractSynapseArtifactDeployer
*/
public class TaskDeployer extends AbstractSynapseArtifactDeployer {
private static Log log = LogFactory.getLog(TaskDeployer.class);
@Override
public String deploySynapseArtifact(OMElement artifactConfig, String fileName, Properties properties) {
if (log.isDebugEnabled()) {
log.debug("StartupTask Deployment from file : " + fileName + " : Started");
}
try {
Startup st = StartupFinder.getInstance().getStartup(artifactConfig, properties);
st.setFileName((new File(fileName)).getName());
if (log.isDebugEnabled()) {
log.debug("StartupTask named '" + st.getName()
+ "' has been built from the file " + fileName);
}
st.init(getSynapseEnvironment());
if (log.isDebugEnabled()) {
log.debug("Initialized the StartupTask : " + st.getName());
}
getSynapseConfiguration().addStartup(st);
if (log.isDebugEnabled()) {
log.debug("StartupTask Deployment from file : " + fileName + " : Completed");
}
log.info("StartupTask named '" + st.getName()
+ "' has been deployed from file : " + fileName);
return st.getName();
} catch (Exception e) {
handleSynapseArtifactDeploymentError(
"StartupTask Deployment from the file : " + fileName + " : Failed.", e);
}
return null;
}
@Override
public String updateSynapseArtifact(OMElement artifactConfig, String fileName,
String existingArtifactName, Properties properties) {
if (log.isDebugEnabled()) {
log.debug("StartupTask update from file : " + fileName + " has started");
}
try {
Startup st = StartupFinder.getInstance().getStartup(artifactConfig, properties);
st.setFileName((new File(fileName)).getName());
if (log.isDebugEnabled()) {
log.debug("StartupTask: " + st.getName() + " has been built from the file: " + fileName);
}
Startup existingSt = getSynapseConfiguration().getStartup(existingArtifactName);
existingSt.destroy();
st.init(getSynapseEnvironment());
if (existingArtifactName.equals(st.getName())) {
getSynapseConfiguration().updateStartup(st);
} else {
getSynapseConfiguration().addStartup(st);
getSynapseConfiguration().removeStartup(existingArtifactName);
log.info("StartupTask: " + existingArtifactName + " has been undeployed");
}
log.info("StartupTask: " + st.getName() + " has been updated from the file: " + fileName);
return st.getName();
} catch (DeploymentException e) {
handleSynapseArtifactDeploymentError("Error while updating the startup task from the " +
"file: " + fileName);
}
return null;
}
@Override
public void undeploySynapseArtifact(String artifactName) {
if (log.isDebugEnabled()) {
log.debug("StartupTask Undeployment of the task named : "
+ artifactName + " : Started");
}
try {
Startup st = getSynapseConfiguration().getStartup(artifactName);
if (st != null) {
getSynapseConfiguration().removeStartup(artifactName);
if (log.isDebugEnabled()) {
log.debug("Destroying the StartupTask named : " + artifactName);
}
st.destroy();
if (log.isDebugEnabled()) {
log.debug("StartupTask Undeployment of the sequence named : "
+ artifactName + " : Completed");
}
log.info("StartupTask named '" + st.getName() + "' has been undeployed");
} else if (log.isDebugEnabled()) {
log.debug("Startup task " + artifactName + " has already been undeployed");
}
} catch (Exception e) {
handleSynapseArtifactDeploymentError(
"StartupTask Undeployement of task named : " + artifactName + " : Failed", e);
}
}
@Override
public void restoreSynapseArtifact(String artifactName) {
if (log.isDebugEnabled()) {
log.debug("Restoring the StartupTask with name : " + artifactName + " : Started");
}
try {
Startup st = getSynapseConfiguration().getStartup(artifactName);
OMElement stElem = StartupFinder.getInstance().serializeStartup(null, st);
if (st.getFileName() != null) {
String fileName = getServerConfigurationInformation().getSynapseXMLLocation()
+ File.separator + MultiXMLConfigurationBuilder.TASKS_DIR
+ File.separator + st.getFileName();
writeToFile(stElem, fileName);
if (log.isDebugEnabled()) {
log.debug("Restoring the StartupTask with name : " + artifactName + " : Completed");
}
log.info("StartupTask named '" + artifactName + "' has been restored");
} else {
handleSynapseArtifactDeploymentError("Couldn't restore the StartupTask named '"
+ artifactName + "', filename cannot be found");
}
} catch (Exception e) {
handleSynapseArtifactDeploymentError(
"Restoring of the StartupTask named '" + artifactName + "' has failed", e);
}
}
}
| apache-2.0 |
consulo/consulo-android | android/android/src/com/android/tools/idea/lang/rs/RenderscriptParser.java | 1189 | /*
* Copyright (C) 2013 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.tools.idea.lang.rs;
import com.intellij.lang.ASTNode;
import com.intellij.lang.PsiBuilder;
import com.intellij.lang.PsiParser;
import com.intellij.psi.tree.IElementType;
import org.jetbrains.annotations.NotNull;
public class RenderscriptParser implements PsiParser {
@NotNull
@Override
public ASTNode parse(IElementType root, PsiBuilder builder) {
final PsiBuilder.Marker rootMarker = builder.mark();
while (!builder.eof()) {
builder.advanceLexer();
}
rootMarker.done(root);
return builder.getTreeBuilt();
}
}
| apache-2.0 |
asoldano/wss4j | ws-security-stax/src/main/java/org/apache/wss4j/stax/impl/securityToken/UsernameSecurityTokenImpl.java | 7035 | /**
* 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.wss4j.stax.impl.securityToken;
import org.apache.wss4j.common.bsp.BSPRule;
import org.apache.wss4j.common.ext.WSSecurityException;
import org.apache.wss4j.common.principal.UsernameTokenPrincipal;
import org.apache.wss4j.common.util.UsernameTokenUtil;
import org.apache.wss4j.stax.ext.WSInboundSecurityContext;
import org.apache.wss4j.stax.ext.WSSConstants;
import org.apache.wss4j.stax.securityToken.UsernameSecurityToken;
import org.apache.wss4j.stax.securityToken.WSSecurityTokenConstants;
import org.apache.xml.security.exceptions.XMLSecurityException;
import org.apache.xml.security.stax.config.JCEAlgorithmMapper;
import org.apache.xml.security.stax.ext.XMLSecurityConstants;
import org.apache.xml.security.stax.impl.securityToken.AbstractInboundSecurityToken;
import javax.crypto.spec.SecretKeySpec;
import javax.security.auth.Subject;
import java.security.Key;
import java.security.Principal;
public class UsernameSecurityTokenImpl extends AbstractInboundSecurityToken implements UsernameSecurityToken {
private static final long DEFAULT_ITERATION = 1000;
private WSSConstants.UsernameTokenPasswordType usernameTokenPasswordType;
private String username;
private String password;
private String createdTime;
private byte[] nonce;
private byte[] salt;
private Long iteration;
private final WSInboundSecurityContext wsInboundSecurityContext;
private Subject subject;
private Principal principal;
public UsernameSecurityTokenImpl(WSSConstants.UsernameTokenPasswordType usernameTokenPasswordType,
String username, String password, String createdTime, byte[] nonce,
byte[] salt, Long iteration,
WSInboundSecurityContext wsInboundSecurityContext, String id,
WSSecurityTokenConstants.KeyIdentifier keyIdentifier) {
super(wsInboundSecurityContext, id, keyIdentifier, true);
this.usernameTokenPasswordType = usernameTokenPasswordType;
this.username = username;
this.password = password;
this.createdTime = createdTime;
this.nonce = nonce;
this.salt = salt;
this.iteration = iteration;
this.wsInboundSecurityContext = wsInboundSecurityContext;
}
@Override
public boolean isAsymmetric() throws XMLSecurityException {
return false;
}
@Override
protected Key getKey(String algorithmURI, XMLSecurityConstants.AlgorithmUsage algorithmUsage,
String correlationID) throws XMLSecurityException {
Key key = getSecretKey().get(algorithmURI);
if (key != null) {
return key;
}
byte[] secretToken = generateDerivedKey(wsInboundSecurityContext);
String algoFamily = JCEAlgorithmMapper.getJCEKeyAlgorithmFromURI(algorithmURI);
key = new SecretKeySpec(secretToken, algoFamily);
setSecretKey(algorithmURI, key);
return key;
}
@Override
public WSSecurityTokenConstants.TokenType getTokenType() {
return WSSecurityTokenConstants.UsernameToken;
}
/**
* This method generates a derived key as defined in WSS Username
* Token Profile.
*
* @return Returns the derived key a byte array
* @throws WSSecurityException
*/
public byte[] generateDerivedKey() throws WSSecurityException {
return generateDerivedKey(wsInboundSecurityContext);
}
/**
* This method generates a derived key as defined in WSS Username
* Token Profile.
*
* @return Returns the derived key a byte array
* @throws org.apache.wss4j.common.ext.WSSecurityException
*
*/
protected byte[] generateDerivedKey(WSInboundSecurityContext wsInboundSecurityContext) throws WSSecurityException {
if (wsInboundSecurityContext != null) {
if (salt == null || salt.length == 0) {
wsInboundSecurityContext.handleBSPRule(BSPRule.R4217);
}
if (iteration == null || iteration < DEFAULT_ITERATION) {
wsInboundSecurityContext.handleBSPRule(BSPRule.R4218);
}
}
return UsernameTokenUtil.generateDerivedKey(password, salt, iteration.intValue());
}
@Override
public Principal getPrincipal() throws WSSecurityException {
if (this.principal == null) {
this.principal = new UsernameTokenPrincipal() {
//todo passwordType and passwordDigest return Enum-Type ?
@Override
public boolean isPasswordDigest() {
return usernameTokenPasswordType == WSSConstants.UsernameTokenPasswordType.PASSWORD_DIGEST;
}
@Override
public String getPasswordType() {
return usernameTokenPasswordType.getNamespace();
}
@Override
public String getName() {
return username;
}
@Override
public String getPassword() {
return password;
}
@Override
public String getCreatedTime() {
return createdTime;
}
@Override
public byte[] getNonce() {
return nonce;
}
};
}
return this.principal;
}
public WSSConstants.UsernameTokenPasswordType getUsernameTokenPasswordType() {
return usernameTokenPasswordType;
}
public String getCreatedTime() {
return createdTime;
}
public String getPassword() {
return password;
}
public String getUsername() {
return username;
}
public byte[] getNonce() {
return nonce;
}
public byte[] getSalt() {
return salt;
}
public Long getIteration() {
return iteration;
}
public void setSubject(Subject subject) {
this.subject = subject;
}
@Override
public Subject getSubject() throws WSSecurityException {
return subject;
}
}
| apache-2.0 |
datanucleus/tests | jdo/general/src/java/org/datanucleus/samples/metadata/datastoreidentity/D3.java | 1143 | /**********************************************************************
Copyright (c) 2005 Erik Bengtson and others.
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.
Contributors:
...
**********************************************************************/
package org.datanucleus.samples.metadata.datastoreidentity;
public class D3
{
private String name;
/**
* @return Returns the name.
*/
public String getName()
{
return name;
}
/**
* @param name The name to set.
*/
public void setName(String name)
{
this.name = name;
}
}
| apache-2.0 |
yifzhang/storm-miclog | src/jvm/com/mic/log/spouts/AppLogWriterSpout.java | 885 | package com.mic.log.spouts;
import java.util.Map;
import backtype.storm.spout.SpoutOutputCollector;
import backtype.storm.task.TopologyContext;
import backtype.storm.topology.OutputFieldsDeclarer;
import backtype.storm.topology.base.BaseRichSpout;
import backtype.storm.tuple.Fields;
import backtype.storm.tuple.Values;
public class AppLogWriterSpout extends BaseRichSpout {
private SpoutOutputCollector _collector;
public void open(Map conf, TopologyContext context,
SpoutOutputCollector collector) {
this._collector = collector;
}
@Override
public void nextTuple() {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
_collector.emit(new Values("command"));
}
@Override
public void declareOutputFields(OutputFieldsDeclarer declarer) {
declarer.declare(new Fields("command"));
}
}
| apache-2.0 |
jamesagnew/hapi-fhir | hapi-fhir-jpaserver-cql/src/main/java/ca/uhn/fhir/cql/dstu3/builder/MeasureReportBuilder.java | 2503 | package ca.uhn.fhir.cql.dstu3.builder;
/*-
* #%L
* HAPI FHIR JPA Server - Clinical Quality Language
* %%
* Copyright (C) 2014 - 2022 Smile CDR, 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.
* #L%
*/
import ca.uhn.fhir.cql.common.builder.BaseBuilder;
import org.hl7.fhir.dstu3.model.MeasureReport;
import org.hl7.fhir.dstu3.model.Period;
import org.hl7.fhir.dstu3.model.Reference;
import org.hl7.fhir.exceptions.FHIRException;
import org.opencds.cqf.cql.engine.runtime.Interval;
import java.util.Date;
public class MeasureReportBuilder extends BaseBuilder<MeasureReport> {
private static final org.slf4j.Logger ourLog = org.slf4j.LoggerFactory.getLogger(MeasureReportBuilder.class);
public MeasureReportBuilder() {
super(new MeasureReport());
}
public MeasureReportBuilder buildStatus(String status) {
try {
this.complexProperty.setStatus(MeasureReport.MeasureReportStatus.fromCode(status));
} catch (FHIRException e) {
ourLog.warn("Exception caught while attempting to set Status to '" + status + "', assuming status COMPLETE!"
+ System.lineSeparator() + e.getMessage());
this.complexProperty.setStatus(MeasureReport.MeasureReportStatus.COMPLETE);
}
return this;
}
public MeasureReportBuilder buildType(MeasureReport.MeasureReportType type) {
this.complexProperty.setType(type);
return this;
}
public MeasureReportBuilder buildMeasureReference(String measureRef) {
this.complexProperty.setMeasure(new Reference(measureRef));
return this;
}
public MeasureReportBuilder buildPatientReference(String patientRef) {
this.complexProperty.setPatient(new Reference(patientRef));
return this;
}
public MeasureReportBuilder buildPeriod(Interval period) {
this.complexProperty.setPeriod(new Period().setStart((Date) period.getStart()).setEnd((Date) period.getEnd()));
return this;
}
}
| apache-2.0 |